argo-search 1.0.1 → 2.9.8

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 (472) hide show
  1. package/LICENSE +201 -21
  2. package/README.en.md +735 -0
  3. package/README.es.md +777 -0
  4. package/README.ja.md +777 -0
  5. package/README.ko.md +777 -0
  6. package/README.md +778 -320
  7. package/SKILL.md +135 -0
  8. package/assets/readme/hero.svg +121 -0
  9. package/assets/readme/made-with-beautify.svg +10 -0
  10. package/assets/readme/proof-routes.svg +73 -0
  11. package/assets/readme/why-better.svg +104 -0
  12. package/assets/readme/workflow.svg +83 -0
  13. package/backends/domain_profiles.json +2356 -96
  14. package/backends/engine_registry.yaml +3428 -503
  15. package/backends/query_synonyms_cn.json +35 -0
  16. package/backends/quota_profiles.json +2488 -160
  17. package/backends/source_types_cn.json +109 -0
  18. package/backends/text_lexicon.json +44 -0
  19. package/bin/argo +772 -0
  20. package/bin/argo.js +102 -39
  21. package/config.yaml +5139 -367
  22. package/cordis.patch.yml +21 -0
  23. package/data/countries.json +40 -0
  24. package/data/lang_matrix/lang_capability.json +842 -0
  25. package/data/lang_matrix/matrix_2026-09-10.json +11921 -0
  26. package/data/regions_cn.json +1 -0
  27. package/docs/ADDING_NEW_ENGINE.md +184 -0
  28. package/docs/ARGO_INTRO.md +124 -0
  29. package/docs/DATA_SOURCE_GAPS.md +81 -0
  30. package/docs/DESIGN_LOCAL_DATA_FUSION.md +90 -0
  31. package/docs/ENGINE_CATALOG.md +575 -0
  32. package/docs/MCP_SETUP.md +108 -0
  33. package/docs/PLATFORM_PATHS.md +111 -0
  34. package/docs/RELEASE_NOTES_v2.8.0.md +71 -0
  35. package/docs/RELEASE_NOTES_v2.8.2.md +63 -0
  36. package/docs/RELEASE_NOTES_v2.8.3.md +55 -0
  37. package/docs/RELEASE_NOTES_v2.8.4.md +79 -0
  38. package/docs/RELEASE_NOTES_v2.8.5.md +102 -0
  39. package/docs/RELEASE_NOTES_v2.8.6.md +66 -0
  40. package/docs/RELEASE_NOTES_v2.8.7.md +65 -0
  41. package/docs/RELEASE_NOTES_v2.8.8.md +67 -0
  42. package/docs/RELEASE_NOTES_v2.8.9.md +67 -0
  43. package/docs/RELEASE_NOTES_v2.9.0.md +64 -0
  44. package/docs/RELEASE_NOTES_v2.9.8.md +73 -0
  45. package/docs/SEARCH_ARCHIVE.md +115 -0
  46. package/docs/assets/architecture.svg +104 -0
  47. package/docs/assets/hero.svg +98 -0
  48. package/docs/engines/bangumi.md +27 -0
  49. package/docs/engines/biorxiv.md +27 -0
  50. package/docs/engines/clawhub.md +27 -0
  51. package/docs/engines/crt_sh.md +27 -0
  52. package/docs/engines/datacite.md +27 -0
  53. package/docs/engines/deps_dev.md +27 -0
  54. package/docs/engines/douban_movie.md +27 -0
  55. package/docs/engines/endoflife.md +27 -0
  56. package/docs/engines/flk_law.md +27 -0
  57. package/docs/engines/fxtwitter.md +27 -0
  58. package/docs/engines/google_news.md +27 -0
  59. package/docs/engines/gov_regulations.md +27 -0
  60. package/docs/engines/guqian.md +27 -0
  61. package/docs/engines/hackernews.md +27 -0
  62. package/docs/engines/iplant.md +27 -0
  63. package/docs/engines/keenable.md +27 -0
  64. package/docs/engines/met_museum.md +27 -0
  65. package/docs/engines/nasa_images.md +27 -0
  66. package/docs/engines/netease_music.md +27 -0
  67. package/docs/engines/npm.md +27 -0
  68. package/docs/engines/nvd.md +27 -0
  69. package/docs/engines/openreview.md +27 -0
  70. package/docs/engines/openstd.md +27 -0
  71. package/docs/engines/parallel_free.md +27 -0
  72. package/docs/engines/people_daily.md +27 -0
  73. package/docs/engines/realtime_index.md +27 -0
  74. package/docs/engines/sec_edgar.md +27 -0
  75. package/docs/engines/seltz.md +27 -0
  76. package/docs/engines/skillsmp.md +27 -0
  77. package/docs/engines/sspai.md +27 -0
  78. package/docs/engines/std_samr.md +27 -0
  79. package/docs/engines/train.md +27 -0
  80. package/docs/engines/un_comtrade.md +27 -0
  81. package/docs/engines/wikisource.md +27 -0
  82. package/docs/engines/zdic.md +27 -0
  83. package/docs/engines/zenodo.md +27 -0
  84. package/docs/engines/zhihu_hot_app.md +27 -0
  85. package/docs//344/270/272/344/273/200/344/271/210/351/200/211/346/213/251argo.md +176 -0
  86. package/engines/README.md +10 -0
  87. package/engines/_template_cli.yaml +39 -0
  88. package/engines/_template_http.yaml +37 -0
  89. package/engines/plugins/_template_plugin.py +50 -0
  90. package/engines/specs/_cisa_kev.yaml +54 -0
  91. package/engines/specs/_osv.yaml +63 -0
  92. package/engines/specs/aljazeera.yaml +43 -0
  93. package/engines/specs/antara.yaml +43 -0
  94. package/engines/specs/artic.yaml +20 -0
  95. package/engines/specs/aviation_weather.yaml +39 -0
  96. package/engines/specs/bangumi.yaml +21 -0
  97. package/engines/specs/biorxiv.yaml +24 -0
  98. package/engines/specs/carbon_intensity.yaml +32 -0
  99. package/engines/specs/cfets.yaml +41 -0
  100. package/engines/specs/cinii.yaml +44 -0
  101. package/engines/specs/clawhub.yaml +49 -0
  102. package/engines/specs/cleveland.yaml +19 -0
  103. package/engines/specs/cn_ai_news.yaml +43 -0
  104. package/engines/specs/core.yaml +35 -0
  105. package/engines/specs/crt_sh.yaml +38 -0
  106. package/engines/specs/ct24.yaml +43 -0
  107. package/engines/specs/datacite.yaml +27 -0
  108. package/engines/specs/datagov_uk.yaml +41 -0
  109. package/engines/specs/ddgs_images.yaml +45 -0
  110. package/engines/specs/deepseek_search.yaml +74 -0
  111. package/engines/specs/deezer.yaml +20 -0
  112. package/engines/specs/defillama.yaml +38 -0
  113. package/engines/specs/deps_dev.yaml +21 -0
  114. package/engines/specs/digup.yaml +36 -0
  115. package/engines/specs/doi.yaml +39 -0
  116. package/engines/specs/douban_movie.yaml +22 -0
  117. package/engines/specs/dw_news.yaml +47 -0
  118. package/engines/specs/egov_law.yaml +21 -0
  119. package/engines/specs/elpais.yaml +43 -0
  120. package/engines/specs/endoflife.yaml +21 -0
  121. package/engines/specs/energy_charts.yaml +21 -0
  122. package/engines/specs/factcheck_org.yaml +52 -0
  123. package/engines/specs/faz.yaml +43 -0
  124. package/engines/specs/federal_register.yaml +57 -0
  125. package/engines/specs/firecrawl.yaml +53 -0
  126. package/engines/specs/flk_law.yaml +24 -0
  127. package/engines/specs/folha.yaml +43 -0
  128. package/engines/specs/france24.yaml +44 -0
  129. package/engines/specs/full_fact.yaml +47 -0
  130. package/engines/specs/fxtwitter.yaml +36 -0
  131. package/engines/specs/gbfs_nyc.yaml +32 -0
  132. package/engines/specs/gdacs.yaml +21 -0
  133. package/engines/specs/gdelt.yaml +64 -0
  134. package/engines/specs/gleif.yaml +55 -0
  135. package/engines/specs/google_news.yaml +22 -0
  136. package/engines/specs/gov_regulations.yaml +38 -0
  137. package/engines/specs/guardian_rss.yaml +59 -0
  138. package/engines/specs/hkex.yaml +40 -0
  139. package/engines/specs/hurriyet.yaml +43 -0
  140. package/engines/specs/iplant.yaml +25 -0
  141. package/engines/specs/jikan.yaml +24 -0
  142. package/engines/specs/jolpica.yaml +20 -0
  143. package/engines/specs/k10plus.yaml +20 -0
  144. package/engines/specs/keenable.yaml +44 -0
  145. package/engines/specs/keenable_free.yaml +36 -0
  146. package/engines/specs/lefigaro.yaml +43 -0
  147. package/engines/specs/listenbrainz.yaml +19 -0
  148. package/engines/specs/matichon.yaml +43 -0
  149. package/engines/specs/met_museum.yaml +21 -0
  150. package/engines/specs/nasa_images.yaml +45 -0
  151. package/engines/specs/netease_music.yaml +38 -0
  152. package/engines/specs/nhk.yaml +43 -0
  153. package/engines/specs/nhtsa_vpic.yaml +20 -0
  154. package/engines/specs/noaa_swpc.yaml +20 -0
  155. package/engines/specs/nvd.yaml +38 -0
  156. package/engines/specs/obis.yaml +20 -0
  157. package/engines/specs/opencitations.yaml +52 -0
  158. package/engines/specs/openf1.yaml +21 -0
  159. package/engines/specs/openfoodfacts.yaml +45 -0
  160. package/engines/specs/openligadb.yaml +20 -0
  161. package/engines/specs/openreview.yaml +37 -0
  162. package/engines/specs/openstd.yaml +21 -0
  163. package/engines/specs/people_daily.yaml +22 -0
  164. package/engines/specs/realtime_index.yaml +34 -0
  165. package/engines/specs/ror.yaml +20 -0
  166. package/engines/specs/satnogs.yaml +20 -0
  167. package/engines/specs/sec_edgar.yaml +46 -0
  168. package/engines/specs/shfe.yaml +39 -0
  169. package/engines/specs/skillsmp.yaml +50 -0
  170. package/engines/specs/sogou_weixin_browser.yaml +30 -0
  171. package/engines/specs/soilgrids.yaml +25 -0
  172. package/engines/specs/sspai.yaml +36 -0
  173. package/engines/specs/stackexchange.yaml +46 -0
  174. package/engines/specs/std_samr.yaml +21 -0
  175. package/engines/specs/tass.yaml +43 -0
  176. package/engines/specs/tavily_free.yaml +56 -0
  177. package/engines/specs/tle_mirror.yaml +21 -0
  178. package/engines/specs/train.yaml +37 -0
  179. package/engines/specs/tvmaze.yaml +20 -0
  180. package/engines/specs/twitter_syndication.yaml +31 -0
  181. package/engines/specs/un_comtrade.yaml +23 -0
  182. package/engines/specs/unpaywall.yaml +54 -0
  183. package/engines/specs/vnpress.yaml +43 -0
  184. package/engines/specs/weather.yaml +32 -0
  185. package/engines/specs/who_don.yaml +21 -0
  186. package/engines/specs/who_gho.yaml +20 -0
  187. package/engines/specs/wikimedia_commons.yaml +34 -0
  188. package/engines/specs/wikisource.yaml +22 -0
  189. package/engines/specs/worms.yaml +19 -0
  190. package/engines/specs/x_trending.yaml +34 -0
  191. package/engines/specs/yna.yaml +43 -0
  192. package/engines/specs/ynet.yaml +43 -0
  193. package/engines/specs/yuanbao.yaml +93 -0
  194. package/engines/specs/zbmath.yaml +40 -0
  195. package/engines/specs/zdic.yaml +22 -0
  196. package/engines/specs/zenodo.yaml +27 -0
  197. package/engines/specs/zhihu_hot_app.yaml +35 -0
  198. package/mcp/clients.yaml +106 -0
  199. package/package.json +55 -12
  200. package/packages/dsh-plugin/README.md +152 -0
  201. package/packages/dsh-plugin/cordis.patch.yml +48 -0
  202. package/packages/dsh-plugin/dsh/client.js +1533 -0
  203. package/packages/dsh-plugin/dsh/diagnostics.js +54 -0
  204. package/packages/dsh-plugin/dsh/index.js +527 -0
  205. package/packages/dsh-plugin/dsh/native-tools.mjs +749 -0
  206. package/packages/dsh-plugin/dsh/runner.js +666 -0
  207. package/packages/dsh-plugin/dsh/wide-research.js +878 -0
  208. package/packages/dsh-plugin/package.json +38 -0
  209. package/packages/dsh-plugin/scripts/sync-local.sh +70 -0
  210. package/packages/dsh-plugin/test/client.test.js +406 -0
  211. package/packages/dsh-plugin/test/config.test.js +30 -0
  212. package/packages/dsh-plugin/test/diagnostics.test.js +28 -0
  213. package/packages/dsh-plugin/test/index.test.js +1382 -0
  214. package/references/query-templates.md +96 -0
  215. package/references/query-templates.yaml +118 -0
  216. package/scripts/ab_eval.py +219 -0
  217. package/scripts/ab_eval_p0p1.py +266 -0
  218. package/scripts/adaptive.py +294 -70
  219. package/scripts/answer.py +154 -0
  220. package/scripts/archive_run.py +591 -0
  221. package/scripts/argo_engine_registry.py +172 -0
  222. package/scripts/argo_paths.py +728 -0
  223. package/scripts/article.py +136 -0
  224. package/scripts/article_meta.py +131 -0
  225. package/scripts/arxiv_source.py +201 -0
  226. package/scripts/badcase_ledger.py +252 -0
  227. package/scripts/batch_probe.py +241 -0
  228. package/scripts/benchmark.py +19 -0
  229. package/scripts/bounded_run.py +144 -0
  230. package/scripts/browser_auth.py +323 -0
  231. package/scripts/budget.py +247 -0
  232. package/scripts/budget_cli.py +93 -0
  233. package/scripts/build_release_assets.sh +65 -0
  234. package/scripts/burstiness_detector.py +147 -0
  235. package/scripts/cache.py +1066 -67
  236. package/scripts/cache_guard.py +271 -0
  237. package/scripts/cache_key_vdom.py +56 -0
  238. package/scripts/cache_similarity.py +170 -0
  239. package/scripts/caliber_isolation.py +195 -0
  240. package/scripts/calibrate_lowquality.py +210 -0
  241. package/scripts/candidate_envelope.py +366 -0
  242. package/scripts/chrome_cdp.py +871 -0
  243. package/scripts/ci_drift_gate.py +90 -0
  244. package/scripts/circuit_breaker.py +389 -0
  245. package/scripts/citations.py +334 -0
  246. package/scripts/cite_cli.py +59 -0
  247. package/scripts/cjk_tokens.py +95 -0
  248. package/scripts/clarify.py +47 -24
  249. package/scripts/cli_io.py +240 -0
  250. package/scripts/config.py +683 -45
  251. package/scripts/config_cache.py +402 -0
  252. package/scripts/conn_pool.py +220 -0
  253. package/scripts/content_boundary.py +46 -0
  254. package/scripts/content_security.py +685 -0
  255. package/scripts/content_signals.py +751 -0
  256. package/scripts/crawl.py +74 -35
  257. package/scripts/cross_lingual_trace.py +293 -0
  258. package/scripts/daemon.py +866 -0
  259. package/scripts/digup_bridge.py +214 -0
  260. package/scripts/dispatch_result.py +98 -0
  261. package/scripts/engine_admission.py +366 -0
  262. package/scripts/engine_dispatch.py +982 -0
  263. package/scripts/engine_env.py +539 -0
  264. package/scripts/engine_failure.py +411 -0
  265. package/scripts/engine_families.py +738 -0
  266. package/scripts/engine_policy.py +218 -0
  267. package/scripts/engine_requires.py +190 -0
  268. package/scripts/engine_status.py +322 -0
  269. package/scripts/engine_validate.py +638 -0
  270. package/scripts/engines.py +799 -294
  271. package/scripts/engines_base.py +1521 -0
  272. package/scripts/engines_builders.py +310 -0
  273. package/scripts/engines_builders_batch10.py +204 -0
  274. package/scripts/engines_builders_batch11.py +174 -0
  275. package/scripts/engines_builders_batch12.py +103 -0
  276. package/scripts/engines_builders_batch13.py +340 -0
  277. package/scripts/engines_builders_batch14.py +656 -0
  278. package/scripts/engines_builders_batch15.py +249 -0
  279. package/scripts/engines_builders_batch9.py +1468 -0
  280. package/scripts/engines_builders_cn.py +2283 -0
  281. package/scripts/engines_builders_data.py +2923 -0
  282. package/scripts/engines_builders_data_macro.py +775 -0
  283. package/scripts/engines_builders_feeds.py +255 -0
  284. package/scripts/engines_builders_intl.py +1239 -0
  285. package/scripts/engines_builders_keyless.py +111 -0
  286. package/scripts/engines_builders_search.py +440 -0
  287. package/scripts/engines_builders_tech.py +1359 -0
  288. package/scripts/evidence.py +620 -166
  289. package/scripts/evidence_loop.py +624 -0
  290. package/scripts/evidence_tier.py +298 -0
  291. package/scripts/except_sets.py +25 -0
  292. package/scripts/extract.py +55 -16
  293. package/scripts/fact_align.py +207 -0
  294. package/scripts/fact_crosscheck.py +230 -0
  295. package/scripts/fetch.py +25 -12
  296. package/scripts/fetch_browser.py +87 -0
  297. package/scripts/fetch_jsrun.py +122 -0
  298. package/scripts/fetch_quality.py +225 -0
  299. package/scripts/fetch_render_tinyfish.py +117 -0
  300. package/scripts/fetch_v3.py +1804 -0
  301. package/scripts/focus_extract.py +350 -0
  302. package/scripts/fulltext_store.py +169 -0
  303. package/scripts/fxtwitter_api.py +325 -0
  304. package/scripts/gen_engine_catalog.py +364 -0
  305. package/scripts/gen_native_tools.py +91 -0
  306. package/scripts/gen_routing_snapshot.py +195 -0
  307. package/scripts/health_check.py +140 -402
  308. package/scripts/health_probe.py +23 -8
  309. package/scripts/hot_state.py +134 -0
  310. package/scripts/http_client.py +1053 -0
  311. package/scripts/image_ops.py +430 -0
  312. package/scripts/image_vision/vision_probe.swift +126 -0
  313. package/scripts/install.ps1 +166 -0
  314. package/scripts/install.sh +221 -0
  315. package/scripts/job.py +1186 -0
  316. package/scripts/jump_resolver.py +235 -0
  317. package/scripts/lang_capability.py +150 -0
  318. package/scripts/lang_detect.py +289 -0
  319. package/scripts/lang_matrix_probe.py +329 -0
  320. package/scripts/lang_pref.py +311 -0
  321. package/scripts/link_source.py +340 -0
  322. package/scripts/local_image.py +970 -0
  323. package/scripts/local_seek.py +402 -0
  324. package/scripts/macro_countries.py +97 -0
  325. package/scripts/matrix_search_eval.py +1187 -0
  326. package/scripts/mcp_compact.py +234 -0
  327. package/scripts/mcp_diag.py +8 -3
  328. package/scripts/mcp_handlers.py +492 -0
  329. package/scripts/mcp_handlers_surface.py +157 -0
  330. package/scripts/mcp_launch.sh +124 -0
  331. package/scripts/mcp_local.py +241 -0
  332. package/scripts/mcp_server.py +125 -419
  333. package/scripts/mcp_setup.py +431 -0
  334. package/scripts/mcp_tools.py +331 -0
  335. package/scripts/mcp_transport.py +191 -0
  336. package/scripts/mcp_warm.py +127 -0
  337. package/scripts/min_version_scan.py +335 -0
  338. package/scripts/net_proxy.py +258 -0
  339. package/scripts/network_aware.py +152 -0
  340. package/scripts/output_transparency.py +200 -0
  341. package/scripts/paid_policy.py +98 -0
  342. package/scripts/paper.py +274 -0
  343. package/scripts/pdf_extract.py +518 -0
  344. package/scripts/phrase_filter.py +66 -0
  345. package/scripts/plan.py +422 -0
  346. package/scripts/postprocess_signals.py +150 -0
  347. package/scripts/pre-commit +48 -0
  348. package/scripts/query_enhance.py +157 -0
  349. package/scripts/query_operators.py +196 -0
  350. package/scripts/query_rewriter.py +116 -7
  351. package/scripts/query_signals.py +300 -0
  352. package/scripts/query_templates.py +167 -0
  353. package/scripts/query_understanding.py +411 -0
  354. package/scripts/query_variants.py +298 -0
  355. package/scripts/quota.py +633 -76
  356. package/scripts/rank_signals.py +775 -0
  357. package/scripts/ranking_eval.py +319 -0
  358. package/scripts/readability_extract.py +433 -0
  359. package/scripts/recompute.py +415 -0
  360. package/scripts/recovery.py +616 -0
  361. package/scripts/recovery_l0.py +160 -0
  362. package/scripts/recovery_runner.py +150 -0
  363. package/scripts/redskill/redskill_engine.py +332 -0
  364. package/scripts/regression_p0p1.py +318 -0
  365. package/scripts/replay_eval.py +658 -0
  366. package/scripts/rerank_tfidf.py +225 -0
  367. package/scripts/research.py +607 -403
  368. package/scripts/research_cli.py +361 -0
  369. package/scripts/research_dossier.py +492 -0
  370. package/scripts/research_expand.py +169 -0
  371. package/scripts/research_gates.py +272 -0
  372. package/scripts/research_report.py +209 -0
  373. package/scripts/research_strategy.py +37 -0
  374. package/scripts/research_work_packages.py +195 -0
  375. package/scripts/result_lang.py +311 -0
  376. package/scripts/retry_policy.py +76 -0
  377. package/scripts/robots_guard.py +259 -0
  378. package/scripts/route.py +921 -254
  379. package/scripts/route_bangs.py +40 -0
  380. package/scripts/route_cache.py +243 -0
  381. package/scripts/route_combo.py +917 -0
  382. package/scripts/route_domains.py +341 -0
  383. package/scripts/route_lang.py +605 -0
  384. package/scripts/route_log.py +63 -0
  385. package/scripts/route_policy.py +250 -0
  386. package/scripts/rrf_classic.py +66 -0
  387. package/scripts/screenshot.py +73 -0
  388. package/scripts/search.py +886 -406
  389. package/scripts/search_attribution.py +185 -0
  390. package/scripts/search_benchmark.py +407 -0
  391. package/scripts/search_cli.py +640 -0
  392. package/scripts/search_entry.py +395 -0
  393. package/scripts/search_output.py +690 -0
  394. package/scripts/search_pipeline.py +926 -0
  395. package/scripts/search_rank.py +991 -0
  396. package/scripts/search_types.py +129 -16
  397. package/scripts/seek_locator.py +68 -0
  398. package/scripts/semantic_evidence.py +391 -0
  399. package/scripts/serp_guard.py +336 -0
  400. package/scripts/serp_kill_log.py +74 -0
  401. package/scripts/single_flight.py +120 -0
  402. package/scripts/social_engines/__init__.py +10 -0
  403. package/scripts/social_engines/bilibili_engine.py +131 -0
  404. package/scripts/social_engines/hackernews_engine.py +113 -0
  405. package/scripts/social_engines/reddit_engine.py +172 -0
  406. package/scripts/social_engines/twitter_engine.py +397 -0
  407. package/scripts/social_engines/v2ex_engine.py +101 -0
  408. package/scripts/social_engines/weibo_engine.py +128 -0
  409. package/scripts/social_engines/xiaohongshu_engine.py +137 -0
  410. package/scripts/social_engines/zhihu_engine.py +139 -0
  411. package/scripts/social_research.py +201 -0
  412. package/scripts/sogou_weixin_browser.py +318 -0
  413. package/scripts/source_ledger.py +249 -0
  414. package/scripts/stage_timing.py +58 -0
  415. package/scripts/stats_cli.py +107 -0
  416. package/scripts/straggler_policy.py +60 -0
  417. package/scripts/stylometry_detector.py +231 -0
  418. package/scripts/sync_backends.py +353 -0
  419. package/scripts/sync_installs.py +29 -0
  420. package/scripts/template_cli.py +127 -0
  421. package/scripts/text_lexicon.py +72 -0
  422. package/scripts/tfidf_router.py +109 -37
  423. package/scripts/time_utils.py +233 -0
  424. package/scripts/topic_research_profiles.py +643 -0
  425. package/scripts/train.py +737 -0
  426. package/scripts/tweet.py +596 -0
  427. package/scripts/url_canon.py +217 -0
  428. package/scripts/url_optimize.py +56 -0
  429. package/scripts/url_safety.py +236 -0
  430. package/scripts/usage_log.py +116 -0
  431. package/scripts/usage_log_clean.py +113 -0
  432. package/scripts/v2ex_nodes.py +311 -0
  433. package/scripts/variant_recall.py +188 -0
  434. package/scripts/watch.py +205 -0
  435. package/scripts/wechat_article.py +258 -0
  436. package/scripts/wide_research.py +447 -0
  437. package/scripts/wx.py +349 -0
  438. package/scripts/x_article_fetch.py +141 -0
  439. package/scripts/x_search.py +234 -0
  440. package/scripts/x_trending.py +189 -0
  441. package/scripts/yaml_load.py +67 -0
  442. package/scripts/zhihu_quota.py +139 -0
  443. package/sub-skills/ego-search/SKILL.md +253 -0
  444. package/sub-skills/ego-search/scripts/ego_search.py +800 -0
  445. package/sub-skills/ego-search/scripts/merge.py +226 -0
  446. package/sub-skills/ego-search/scripts/quality.py +64 -0
  447. package/sub-skills/ego-search/scripts/runtime.py +172 -0
  448. package/sub-skills/ego-search/scripts/safety.py +109 -0
  449. package/sub-skills/ego-search/scripts/serp_spec.py +109 -0
  450. package/sub-skills/ego-search/scripts/webbridge_adapter.py +374 -0
  451. package/sub-skills/js-run/SKILL.md +67 -0
  452. package/sub-skills/js-run/scripts/jsrun.py +112 -0
  453. package/sub-skills/js-run/scripts/shim.js +188 -0
  454. package/sub-skills/local-search/SKILL.md +50 -53
  455. package/sub-skills/local-search/bm25.py +186 -0
  456. package/sub-skills/local-search/cli_runner.py +331 -0
  457. package/sub-skills/local-search/config.yaml +152 -55
  458. package/sub-skills/local-search/engine_registry.py +91 -26
  459. package/sub-skills/local-search/{health_check.py → local_health_check.py} +140 -10
  460. package/sub-skills/local-search/local_search_adapter.py +13 -2
  461. package/sub-skills/local-search/parse_maps.yaml +40 -42
  462. package/sub-skills/local-search/parsers.py +328 -0
  463. package/sub-skills/local-search/search_v3.py +716 -242
  464. package/sub-skills/local-search/smart_router.py +47 -7
  465. package/sub-skills/local-seek/SKILL.md +110 -0
  466. package/sub-skills/local-seek/config/domains.yaml +20 -0
  467. package/sub-skills/local-seek/scripts/eval_rank.py +216 -0
  468. package/sub-skills/local-seek/scripts/eval_seek.py +224 -0
  469. package/sub-skills/local-seek/scripts/seek.py +1465 -0
  470. package/sub-skills/local-seek/scripts/seek_frecency.py +126 -0
  471. package/sub-skills/local-seek/scripts/seek_fts.py +430 -0
  472. package/sub-skills/local-seek/scripts/seek_rank.py +197 -0
@@ -1,277 +1,236 @@
1
1
  #!/usr/bin/env python3
2
2
  """
3
- research.py — 深度研究工具(wigolo research 理念移植)
4
-
5
- 核心能力:
6
- 1. 问题分解:将复杂查询拆分为 3-5 个子查询
7
- 2. 多源采集:对每个子查询并行执行搜索
8
- 3. 综合报告:合并去重 + 来源标注 + 知识缺口识别
9
- 4. 引用追踪:每个结论可追溯到具体搜索结果
10
-
11
- 用法:
12
- python3 research.py "CRISPR-Cas9 脱靶效应的 AI 预测方法综述"
13
- python3 research.py "CVE-2024-6387 生产环境影响评估" --depth deep
14
- python3 research.py "台积电财报分歧分析" --sub-queries 5
3
+ research.py — 深度研究取证机(含社交舆情模式)
4
+
5
+ 取证:扩词或工作包 → 多源采集 → dossier。
6
+ 判断稿由 Agent 按 references/research-protocol.md 写。
15
7
  """
16
8
 
17
9
  from __future__ import annotations
18
10
 
19
- import argparse
20
- import json
21
11
  import os
12
+ import re
22
13
  import sys
23
14
  import time
24
- from concurrent.futures import ThreadPoolExecutor, as_completed
15
+ from bounded_run import run_bounded, TaskError
25
16
  from typing import Any
26
17
 
27
18
  SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
28
19
  sys.path.insert(0, SCRIPT_DIR)
29
20
 
30
21
  from search import super_search, rrf_merge, deduplicate_by_url
22
+ from research_strategy import resolve_route_strategy, should_use_local_first
23
+ from research_expand import expand_query, decompose_query, _deduplicate_sub_queries
24
+ from research_dossier import (
25
+ detect_cross_references,
26
+ build_dossier,
27
+ synthesize_report,
28
+ )
29
+ from research_work_packages import (
30
+ parse_work_packages,
31
+ stage_work_packages,
32
+ packages_to_sub_queries,
33
+ )
34
+ from research_gates import evaluate_dossier_gates
35
+
36
+
37
+ # ── 子查询语言/领域分发(2026-09-07)─────────────────────────────────────
38
+ # 中英混合研究的英文子查询此前只吃 profile 通用组合,英文源基本不参与
39
+ # (实测 11 引擎仅 2 个有结果)。boosts 是加法不替换:语言源前置,profile
40
+ # 组合殿后。与 route 语言表同计算方式;学术顺序按 references/academic-query.md
41
+ # §2 协议(S2 起步 → arXiv 补预印本 → openalex/crossref 结构化 → GS 保底)。
42
+ _RESEARCH_EN_BOOSTS: tuple[str, ...] = ("octen", "anysearch", "github", "exa")
43
+ _RESEARCH_JA_KO_BOOSTS: tuple[str, ...] = ("anysearch", "local_bing")
44
+ _RESEARCH_ACADEMIC_BOOSTS: tuple[str, ...] = (
45
+ "semantic_scholar", "arxiv", "openalex", "crossref", "google_scholar",
46
+ "openreview", "biorxiv",
47
+ )
48
+ _ACADEMIC_QUERY_RE = re.compile(
49
+ r"(?i)(论文|文献|综述|引用网络|预印本|学术|期刊|会议论文|研究现状"
50
+ r"|arxiv|semantic\s*scholar|literature( review)?|survey\b|preprint|"
51
+ r"citation|doi\b|state.of.the.art)")
52
+
53
+
54
+ def _subquery_lang(query: str) -> str:
55
+ """子查询主语言:ja/ko 按假名/谚文,en 看拉丁字符占比,其余 zh。"""
56
+ q = query or ""
57
+ if re.search(r"[\u3040-\u309f\u30a0-\u30ff]", q):
58
+ return "ja"
59
+ if re.search(r"[\uac00-\ud7af]", q):
60
+ return "ko"
61
+ cjk = sum(1 for ch in q if "\u4e00" <= ch <= "\u9fff")
62
+ latin = sum(1 for ch in q if ch.isascii() and ch.isalpha())
63
+ if cjk == 0 and latin > 0:
64
+ return "en"
65
+ if cjk > 0 and latin >= cjk * 2:
66
+ # 拉丁明显占优的混合句(术语/产品名为主体)→ 英文源前置也有效
67
+ return "en"
68
+ return "zh"
69
+
70
+
71
+ def _subquery_lang_boosts(query: str,
72
+ profile: dict[str, Any] | None) -> list[str]:
73
+ """子查询语言/学术意图 → 引擎前置清单(空 = 不干预)。"""
74
+ if _ACADEMIC_QUERY_RE.search(query or "") or (
75
+ profile or {}).get("key") == "academic":
76
+ return list(_RESEARCH_ACADEMIC_BOOSTS)
77
+ lang = _subquery_lang(query)
78
+ if lang == "en":
79
+ return list(_RESEARCH_EN_BOOSTS)
80
+ if lang in ("ja", "ko"):
81
+ return list(_RESEARCH_JA_KO_BOOSTS)
82
+ return []
31
83
 
32
84
 
33
- # ── 交叉引用检测 ──────────────────────────────────────────────────────────────
34
-
35
- def detect_cross_references(results: list[dict[str, Any]], min_sources: int = 2,
36
- min_ngram_len: int = 3) -> list[dict[str, Any]]:
37
- """检测多个来源的交叉引用(n-gram 重叠)。
38
-
39
- 如果同一 n-gram 出现在 ≥min_sources 个不同域名的结果中,
40
- 标记为「潜在佐证」。
41
- """
42
- import re
43
- from urllib.parse import urlparse
44
-
45
- # 提取所有 snippet 的 n-gram
46
- ngram_sources: dict[str, set] = {} # ngram -> set of (url, title)
47
- for r in results:
48
- url = r.get("url", "")
49
- domain = urlparse(url).netloc.lower().strip("www.") if url else "unknown"
50
- text = f"{r.get('title', '')} {r.get('snippet', '')}"
51
- # 简单分词(中英文混合)
52
- # 英文按空格分
53
- en_tokens = re.findall(r"[a-zA-Z]+", text.lower())
54
- # 中文按字符 bigram/trigram
55
- cn_chars = re.findall(r"[\u4e00-\u9fff]+", text)
56
- cn_tokens = []
57
- for seg in cn_chars:
58
- for i in range(len(seg) - min_ngram_len + 1):
59
- cn_tokens.append(seg[i:i + min_ngram_len])
60
-
61
- all_tokens = en_tokens + cn_tokens
62
- for n in range(min_ngram_len, min(min_ngram_len + 1, len(all_tokens) + 1)):
63
- for i in range(len(all_tokens) - n + 1):
64
- ngram = " ".join(all_tokens[i:i + n])
65
- if len(ngram) >= 4: # 过滤太短的 ngram
66
- ngram_sources.setdefault(ngram, set()).add(domain)
67
-
68
- # 找出被多个来源佐证的 n-gram
69
- cross_refs = []
70
- for ngram, domains in ngram_sources.items():
71
- if len(domains) >= min_sources:
72
- cross_refs.append({
73
- "ngram": ngram,
74
- "source_count": len(domains),
75
- "domains": sorted(domains),
76
- })
77
-
78
- # 按来源数排序,取 top 10
79
- cross_refs.sort(key=lambda x: x["source_count"], reverse=True)
80
- return cross_refs[:10]
81
-
82
-
83
- # ── 问题分解 ──────────────────────────────────────────────────────────────────
84
-
85
- def decompose_query(query: str, num_sub: int = 4) -> list[dict[str, str]]:
86
- """将复杂查询分解为子查询。
87
-
88
- 策略:基于关键词特征自动分解,不依赖 LLM。
89
- """
90
- sub_queries = []
91
-
92
- # 策略 1:中英文混合 → 分语言搜索
93
- has_chinese = any("\u4e00" <= c <= "\u9fff" for c in query)
94
- has_english = any(c.isascii() and c.isalpha() for c in query)
95
-
96
- if has_chinese and has_english:
97
- # 提取英文核心词
98
- eng_words = " ".join(w for w in query.split() if w.isascii() and len(w) > 2)
99
- if eng_words:
100
- sub_queries.append({
101
- "query": eng_words,
102
- "intent": "英文核心概念搜索",
103
- "strategy": "english_focused"
104
- })
105
-
106
- # 策略 2:包含年份/时间 → 补充时效性搜索
107
- import re
108
- year_match = re.search(r"20\d{2}", query)
109
- if year_match:
110
- year = year_match.group()
111
- sub_queries.append({
112
- "query": f"{query} {year} latest update",
113
- "intent": f"{year}年最新进展",
114
- "strategy": "temporal"
115
- })
116
-
117
- # 策略 3:包含对比词 → 分别搜索各对象
118
- compare_match = re.search(r"(?:vs| versus |对比|比较|和|与|及)", query, re.I)
119
- if compare_match:
120
- parts = re.split(r"(?:vs| versus |对比|比较|和|与|及)", query, flags=re.I)
121
- for part in parts[:2]:
122
- part = part.strip()
123
- if part and len(part) > 2:
124
- sub_queries.append({
125
- "query": part,
126
- "intent": f"独立搜索:{part[:20]}",
127
- "strategy": "split_compare"
128
- })
129
-
130
- # 策略 4:包含「如何/怎么/why」→ 补充教程/方案搜索
131
- how_match = re.search(r"(?:如何|怎么|how|why|为什么|最佳实践|best practice)", query, re.I)
132
- if how_match:
133
- sub_queries.append({
134
- "query": f"{query} tutorial guide best practices",
135
- "intent": "教程/最佳实践",
136
- "strategy": "tutorial"
137
- })
138
-
139
- # 策略 5:包含「问题/bug/错误」→ 补充社区讨论搜索
140
- bug_match = re.search(r"(?:bug|error|问题|报错|故障|issue|panic|crash|exception)", query, re.I)
141
- if bug_match:
142
- sub_queries.append({
143
- "query": f"{query} solution fix workaround community",
144
- "intent": "社区解决方案",
145
- "strategy": "community_fix"
146
- })
147
-
148
- # 策略 6:包含「论文/学术」→ 补充学术搜索
149
- academic_match = re.search(r"(?:论文|paper|arxiv|学术|综述|review|survey|研究)", query, re.I)
150
- if academic_match:
151
- sub_queries.append({
152
- "query": f"{query} arxiv semantic scholar 2024 2025",
153
- "intent": "学术文献补充",
154
- "strategy": "academic"
155
- })
156
-
157
- # 策略 7:包含「安全/CVE」→ 补充安全源
158
- security_match = re.search(r"(?:CVE|漏洞|vulnerability|security|exploit|PoC)", query, re.I)
159
- if security_match:
160
- sub_queries.append({
161
- "query": f"{query} NVD exploit PoC advisory",
162
- "intent": "安全数据源补充",
163
- "strategy": "security"
164
- })
165
-
166
- # 策略 8:包含「金融/股票/财报」→ 补充金融源
167
- finance_match = re.search(r"(?:股价|财报|基金|股票|行情|金融|financial|earnings|stock)", query, re.I)
168
- if finance_match:
169
- sub_queries.append({
170
- "query": f"{query} 东方财富 雪球 研报",
171
- "intent": "金融数据补充",
172
- "strategy": "finance"
173
- })
174
-
175
- # 确保至少有原始查询
176
- if not sub_queries:
177
- sub_queries.append({
178
- "query": query,
179
- "intent": "原始查询",
180
- "strategy": "direct"
181
- })
182
-
183
- # 补充通用搜索
184
- if len(sub_queries) < num_sub:
185
- sub_queries.append({
186
- "query": query,
187
- "intent": "综合搜索",
188
- "strategy": "general"
189
- })
190
-
191
- return _deduplicate_sub_queries(sub_queries[:num_sub])
192
-
193
-
194
- def _deduplicate_sub_queries(sub_queries: list[dict[str, str]]) -> list[dict[str, str]]:
195
- """基于 Jaccard 相似度去重子查询。"""
196
- import re as _re
197
- def _tokens(q: str) -> set:
198
- return set(_re.findall(r'[a-zA-Z]+|[\u4e00-\u9fff]', q.lower()))
199
- unique = []
200
- seen_tokens = []
201
- for sq in sub_queries:
202
- tokens = _tokens(sq["query"])
203
- is_dup = False
204
- for prev in seen_tokens:
205
- jaccard = len(tokens & prev) / max(len(tokens | prev), 1)
206
- if jaccard > 0.6:
207
- is_dup = True
208
- break
209
- if not is_dup:
210
- unique.append(sq)
211
- seen_tokens.append(tokens)
212
- return unique
213
-
214
-
215
- # ── 多源采集 ──────────────────────────────────────────────────────────────────
216
-
217
85
  def collect_sources(sub_queries: list[dict[str, str]], max_results: int = 5,
218
86
  timeout: int = 15, depth: str = "balanced",
219
- mode: str = "auto") -> dict[str, Any]:
87
+ mode: str = "auto",
88
+ engines_priority: list[str] | None = None,
89
+ profile: dict[str, Any] | None = None,
90
+ budget: int | None = None,
91
+ route_strategy: str | None = None) -> dict[str, Any]:
220
92
  """对每个子查询并行执行搜索,返回聚合结果。"""
221
93
  all_results = []
222
94
  engines_used = set()
223
95
  sub_results = []
224
96
  t0 = time.time()
97
+ try:
98
+ from cache import SearchCache
99
+ shared_cache = SearchCache()
100
+ except Exception:
101
+ shared_cache = None
225
102
 
226
- def _search_one(sq: dict[str, str]) -> dict[str, Any]:
227
- result = super_search(
228
- sq["query"], n=max_results, timeout=timeout,
229
- depth=depth, mode=mode, skip_cache=False
230
- )
231
- return {
103
+ try:
104
+ from engine_policy import research_engine_hints
105
+ except ImportError:
106
+ research_engine_hints = None # type: ignore
107
+
108
+ prio = [e for e in (engines_priority or []) if e]
109
+
110
+ def _boost_for(idx: int, sq: dict[str, str]) -> list[str]:
111
+ boosts: list[str] = []
112
+ if research_engine_hints and profile:
113
+ boosts = list(research_engine_hints(profile, idx) or [])
114
+ elif prio:
115
+ if idx <= 0:
116
+ boosts = prio[:3]
117
+ else:
118
+ n = len(prio)
119
+ start = (idx - 1) % n
120
+ boosts = [prio[(start + i) % n] for i in range(min(2, n))]
121
+ prefs_all = sq.get("preferred_engines") or []
122
+ if not prefs_all:
123
+ pref = sq.get("preferred_engine")
124
+ if pref and pref != "auto":
125
+ prefs_all = [pref]
126
+ if prefs_all:
127
+ # 工作包显式指定 > 机器启发(语言/学术/profile)
128
+ return list(prefs_all) + [e for e in boosts if e not in prefs_all]
129
+ lang_boosts = _subquery_lang_boosts(sq.get("query") or "", profile)
130
+ if lang_boosts:
131
+ boosts = list(lang_boosts) + [e for e in boosts
132
+ if e not in lang_boosts]
133
+ return boosts
134
+
135
+ def _search_one(sq: dict[str, str], idx: int = 0) -> dict[str, Any]:
136
+ boosts = _boost_for(idx, sq)
137
+ strategy = resolve_route_strategy(route_strategy, mode)
138
+ use_local_first = should_use_local_first(strategy)
139
+
140
+ def _run(engine_override: str | None, boost_override: list[str] | None) -> dict:
141
+ return super_search(
142
+ sq["query"], n=max_results, timeout=timeout,
143
+ depth=depth, mode=mode, skip_cache=False,
144
+ cache=shared_cache,
145
+ engine=engine_override or "auto",
146
+ context="research",
147
+ local_first=engine_override == "local_search",
148
+ engines_boost=boost_override or boosts,
149
+ envelope=False,
150
+ )
151
+
152
+ result = None
153
+ upgraded = False
154
+ if use_local_first:
155
+ result = _run("local_search", None)
156
+ if len(result.get("results", [])) < min(3, max_results):
157
+ result = _run(None, None)
158
+ upgraded = True
159
+ if result is None:
160
+ result = _run(None, None)
161
+ out = {
232
162
  "sub_query": sq["query"],
233
163
  "intent": sq["intent"],
234
164
  "strategy": sq["strategy"],
165
+ "engine_hint": "auto",
166
+ "engines_boost": boosts,
235
167
  "results": result.get("results", []),
236
168
  "engines_used": result.get("engines_used", []),
237
169
  "elapsed_ms": result.get("elapsed_ms", 0),
170
+ "cached": result.get("cached", False),
171
+ "upgraded_to_full": upgraded,
172
+ "route_strategy": strategy,
173
+ # 路由域必须随子结果传下去:它是高后果门控(fetch_required)的
174
+ # 唯一输入。此前这一项被丢在这里,下游只能去单条结果上找
175
+ # `domain`——而没有任何 producer 往结果行写它(rerank 写的是
176
+ # authority/absorption/evidence_flags 那一组),于是
177
+ # `_attach_evidence_loop` 永远拿到空域,金融/医疗/法律研究
178
+ # 的 fetch_required 恒为 False。
179
+ "domain": result.get("domain") or "",
238
180
  }
181
+ if sq.get("package_id"):
182
+ out["package_id"] = sq["package_id"]
183
+ return out
184
+
185
+ active_queries = sub_queries
186
+ budget_exhausted = False
187
+ if budget is not None and budget > 0 and len(sub_queries) > budget:
188
+ active_queries = sub_queries[:budget]
189
+ budget_exhausted = True
190
+
191
+ if not active_queries:
192
+ return {
193
+ "merged_results": [],
194
+ "sub_results": [],
195
+ "engines_used": [],
196
+ "total_results": 0,
197
+ "elapsed_ms": int((time.time() - t0) * 1000),
198
+ "budget_exhausted": budget_exhausted,
199
+ "budget_limit": budget,
200
+ }
201
+
202
+ def _fail_sub(sq: dict, message: str) -> dict:
203
+ fail = {
204
+ "sub_query": sq["query"],
205
+ "intent": sq["intent"],
206
+ "strategy": sq["strategy"],
207
+ "results": [],
208
+ "engines_used": [],
209
+ "error": message,
210
+ "elapsed_ms": 0,
211
+ }
212
+ if sq.get("package_id"):
213
+ fail["package_id"] = sq["package_id"]
214
+ return fail
215
+
216
+ # 总时限 timeout*2+5 秒:到点就用已完成的子查询继续,没完成的记失败占位,
217
+ # 不再被卡住的子查询拖住——原先 with ThreadPoolExecutor 退出时会 join 全部慢
218
+ # 线程,as_completed 的超时形同虚设,单个卡住的子查询能拖垮整次研究。
219
+ items = list(enumerate(active_queries))
220
+ bound_s = timeout * 2 + 5
221
+ finished, unfinished = run_bounded(
222
+ items, lambda pair: _search_one(pair[1], pair[0]),
223
+ bound_s, max_workers=min(len(items), 4))
224
+ for (_i, sq), value in finished:
225
+ if isinstance(value, TaskError):
226
+ sub_results.append(_fail_sub(sq, str(value.exc)))
227
+ continue
228
+ sub_results.append(value)
229
+ all_results.extend(value["results"])
230
+ engines_used.update(value["engines_used"])
231
+ for _i, sq in unfinished:
232
+ sub_results.append(_fail_sub(sq, f"timeout (>{bound_s:.0f}s)"))
239
233
 
240
- with ThreadPoolExecutor(max_workers=min(len(sub_queries), 4)) as ex:
241
- futures = {ex.submit(_search_one, sq): sq for sq in sub_queries}
242
- all_futures = list(futures.keys())
243
- try:
244
- for fut in as_completed(futures, timeout=timeout * 2 + 5):
245
- try:
246
- sr = fut.result()
247
- sub_results.append(sr)
248
- all_results.extend(sr["results"])
249
- engines_used.update(sr["engines_used"])
250
- except Exception as e:
251
- sq = futures[fut]
252
- sub_results.append({
253
- "sub_query": sq["query"],
254
- "intent": sq["intent"],
255
- "strategy": sq["strategy"],
256
- "results": [],
257
- "engines_used": [],
258
- "error": str(e),
259
- "elapsed_ms": 0,
260
- })
261
- except Exception:
262
- # 超时后收集已完成的 futures
263
- for fut in all_futures:
264
- if fut.done() and not fut.cancelled():
265
- try:
266
- sr = fut.result()
267
- if sr not in sub_results:
268
- sub_results.append(sr)
269
- all_results.extend(sr["results"])
270
- engines_used.update(sr["engines_used"])
271
- except Exception:
272
- pass
273
-
274
- # RRF 融合
275
234
  result_lists = [sr["results"] for sr in sub_results if sr["results"]]
276
235
  if len(result_lists) > 1:
277
236
  merged = rrf_merge(result_lists)
@@ -280,34 +239,28 @@ def collect_sources(sub_queries: list[dict[str, str]], max_results: int = 5,
280
239
  else:
281
240
  merged = []
282
241
 
283
- elapsed = int((time.time() - t0) * 1000)
284
-
285
242
  return {
286
243
  "merged_results": merged[:max_results * 3],
287
244
  "sub_results": sub_results,
288
245
  "engines_used": sorted(engines_used),
289
246
  "total_results": len(merged),
290
- "elapsed_ms": elapsed,
247
+ "elapsed_ms": int((time.time() - t0) * 1000),
248
+ "budget_exhausted": budget_exhausted,
249
+ "budget_limit": budget,
291
250
  }
292
251
 
293
252
 
294
- # ── 知识缺口识别 ──────────────────────────────────────────────────────────────
295
-
296
253
  def identify_gaps(sub_results: list[dict[str, Any]], query: str) -> list[str]:
297
254
  """识别搜索结果中的知识缺口。"""
298
- gaps = []
255
+ import re
299
256
 
300
- # 检查是否有子查询完全失败
257
+ gaps = []
301
258
  for sr in sub_results:
302
259
  if not sr["results"]:
303
260
  gaps.append(f"子查询「{sr['intent']}」无结果:{sr['sub_query'][:40]}")
304
-
305
- # 检查是否有子查询结果过少
306
- for sr in sub_results:
307
- if sr["results"] and len(sr["results"]) < 2:
261
+ elif len(sr["results"]) < 2:
308
262
  gaps.append(f"子查询「{sr['intent']}」结果稀少(仅 {len(sr['results'])} 条)")
309
263
 
310
- # 检查来源多样性
311
264
  all_sources = set()
312
265
  for sr in sub_results:
313
266
  for r in sr["results"]:
@@ -315,185 +268,436 @@ def identify_gaps(sub_results: list[dict[str, Any]], query: str) -> list[str]:
315
268
  if src:
316
269
  all_sources.add(src)
317
270
  if len(all_sources) < 3:
318
- gaps.append(f"来源多样性不足:仅 {len(all_sources)} 个引擎有结果({', '.join(all_sources)})")
271
+ gaps.append(
272
+ f"来源多样性不足:仅 {len(all_sources)} 个引擎有结果"
273
+ f"({', '.join(all_sources)})"
274
+ )
319
275
 
320
- # 检查时间覆盖
321
- import re
322
276
  year_match = re.search(r"20\d{2}", query)
323
277
  if year_match:
324
278
  target_year = year_match.group()
325
- has_recent = False
326
- for sr in sub_results:
327
- for r in sr["results"]:
328
- title = r.get("title", "")
329
- snippet = r.get("snippet", "")
330
- if target_year in title or target_year in snippet:
331
- has_recent = True
332
- break
279
+ has_recent = any(
280
+ target_year in (r.get("title", "") + r.get("snippet", ""))
281
+ for sr in sub_results
282
+ for r in sr["results"]
283
+ )
333
284
  if not has_recent:
334
285
  gaps.append(f"未找到 {target_year} 年的直接相关内容")
335
-
336
286
  return gaps
337
287
 
338
288
 
339
- # ── 综合报告 ──────────────────────────────────────────────────────────────────
340
-
341
- def synthesize_report(query: str, collection: dict[str, Any],
342
- gaps: list[str]) -> dict[str, Any]:
343
- """生成综合研究报告。"""
344
- merged = collection["merged_results"]
345
- sub_results = collection["sub_results"]
289
+ def merge_collections(parts: list[dict[str, Any]], max_results: int) -> dict[str, Any]:
290
+ """合并分阶段采集结果。"""
291
+ sub_results: list[dict[str, Any]] = []
292
+ engines: set[str] = set()
293
+ elapsed = 0
294
+ budget_exhausted = False
295
+ budget_limit = None
296
+ lists: list[list[dict[str, Any]]] = []
297
+ for p in parts:
298
+ sub_results.extend(p.get("sub_results") or [])
299
+ engines.update(p.get("engines_used") or [])
300
+ elapsed += int(p.get("elapsed_ms") or 0)
301
+ budget_exhausted = budget_exhausted or bool(p.get("budget_exhausted"))
302
+ if p.get("budget_limit") is not None:
303
+ budget_limit = p.get("budget_limit")
304
+ if p.get("merged_results"):
305
+ lists.append(p["merged_results"])
306
+ if len(lists) > 1:
307
+ merged = rrf_merge(lists)
308
+ elif lists:
309
+ merged = deduplicate_by_url(lists[0])
310
+ else:
311
+ merged = []
312
+ return {
313
+ "merged_results": merged[: max_results * 3],
314
+ "sub_results": sub_results,
315
+ "engines_used": sorted(engines),
316
+ "total_results": len(merged),
317
+ "elapsed_ms": elapsed,
318
+ "budget_exhausted": budget_exhausted,
319
+ "budget_limit": budget_limit,
320
+ }
346
321
 
347
- # 按子查询分组的关键发现
348
- key_findings = []
349
- for sr in sub_results:
350
- if sr["results"]:
351
- best = sr["results"][0]
352
- key_findings.append({
353
- "aspect": sr["intent"],
354
- "strategy": sr["strategy"],
355
- "top_result": {
356
- "title": best.get("title", ""),
357
- "url": best.get("url", ""),
358
- "snippet": (best.get("snippet", "") or "")[:200],
359
- "score": best.get("score", 0),
360
- "source": best.get("source", ""),
361
- },
362
- "result_count": len(sr["results"]),
363
- })
364
-
365
- # 来源统计
366
- source_counts = {}
367
- for r in merged:
368
- src = r.get("source", "unknown")
369
- source_counts[src] = source_counts.get(src, 0) + 1
370
-
371
- # 引用列表
372
- citations = []
373
- for i, r in enumerate(merged[:15]):
374
- citations.append({
375
- "id": f"[{i+1}]",
376
- "title": r.get("title", ""),
377
- "url": r.get("url", ""),
378
- "source": r.get("source", ""),
379
- "score": r.get("score", 0),
380
- })
381
-
382
- # 交叉引用检测
383
- all_results = []
384
- for sr in sub_results:
385
- all_results.extend(sr["results"])
386
- cross_refs = detect_cross_references(all_results)
387
322
 
388
- return {
389
- "query": query,
390
- "key_findings": key_findings,
391
- "total_sources": collection["total_results"],
392
- "engines_used": collection["engines_used"],
393
- "source_distribution": source_counts,
394
- "citations": citations,
395
- "cross_references": cross_refs,
396
- "gaps": gaps,
397
- "elapsed_ms": collection["elapsed_ms"],
398
- "sub_query_count": len(sub_results),
323
+ def _expand_sub_queries(
324
+ query: str,
325
+ num_sub_queries: int,
326
+ profile: dict[str, Any] | None,
327
+ ) -> list[dict[str, str]]:
328
+ sub_queries: list[dict[str, str]] = []
329
+ if profile:
330
+ try:
331
+ from topic_research_profiles import build_profile_sub_queries
332
+ sub_queries = build_profile_sub_queries(query, profile, num_sub_queries)
333
+ except Exception:
334
+ sub_queries = []
335
+ heuristic = expand_query(query, num_sub_queries)
336
+ seen_q = {sq["query"] for sq in sub_queries}
337
+ for sq in heuristic:
338
+ if len(sub_queries) >= num_sub_queries:
339
+ break
340
+ if sq["query"] not in seen_q:
341
+ sub_queries.append(sq)
342
+ seen_q.add(sq["query"])
343
+ if not sub_queries:
344
+ sub_queries = heuristic
345
+ # query_variants 变体注入已消融移除(2026-09-20,冷缓存 4 查询实测):
346
+ # 变体(research analysis / 最新进展等)与 anchor 高度同质,URL 边际
347
+ # 「全新」但只是同主题长尾页而非新角度,每个变体却付一次完整
348
+ # super_search(2-10s)——合计墙钟 33.3s → 23.9s(-28%),merged 仅降
349
+ # 约 26%(dossier 的 key_findings 每子查询取 top-1,citations 取前 N,
350
+ # 长尾页极少入账)。覆盖扩展由领域模板(finance/academic/security,
351
+ # 带真实增量词)与 Agent 工作包承担。query_variants 模块保留:
352
+ # parallel 引擎的多路召回在同一次 API 调用内发多查询,无额外成本。
353
+ return _deduplicate_sub_queries(sub_queries[:num_sub_queries])
354
+
355
+
356
+ def _collect_work_packages(
357
+ packages: list[dict[str, Any]],
358
+ max_results: int,
359
+ timeout: int,
360
+ depth: str,
361
+ mode: str,
362
+ engines_priority: list[str] | None,
363
+ profile: dict[str, Any] | None,
364
+ budget: int | None,
365
+ route_strategy: str | None,
366
+ ) -> tuple[dict[str, Any], list[list[str]], list[str]]:
367
+ stages, warnings = stage_work_packages(packages)
368
+ remaining = budget
369
+ parts: list[dict[str, Any]] = []
370
+ exhausted = False
371
+ stage_ids: list[list[str]] = []
372
+ for stage in stages:
373
+ if remaining is not None and remaining <= 0:
374
+ exhausted = True
375
+ break
376
+ take = stage if remaining is None else stage[:remaining]
377
+ if remaining is not None:
378
+ remaining -= len(take)
379
+ if len(take) < len(stage):
380
+ exhausted = True
381
+ stage_ids.append([p["id"] for p in take])
382
+ part = collect_sources(
383
+ packages_to_sub_queries(take),
384
+ max_results, timeout, depth, mode,
385
+ engines_priority=engines_priority,
386
+ profile=profile,
387
+ budget=None,
388
+ route_strategy=route_strategy,
389
+ )
390
+ parts.append(part)
391
+ if exhausted:
392
+ break
393
+ collection = merge_collections(parts, max_results) if parts else {
394
+ "merged_results": [], "sub_results": [], "engines_used": [],
395
+ "total_results": 0, "elapsed_ms": 0,
396
+ "budget_exhausted": True, "budget_limit": budget,
399
397
  }
398
+ if exhausted:
399
+ collection["budget_exhausted"] = True
400
+ collection["budget_limit"] = budget
401
+ return collection, stage_ids, warnings
402
+
403
+
404
+ def _attach_profile_and_plan(
405
+ report: dict[str, Any],
406
+ profile: dict[str, Any] | None,
407
+ engines_priority: list[str],
408
+ vertical_engines: list[str],
409
+ plan_info: dict[str, Any] | None,
410
+ rewrite_result: dict[str, Any] | None,
411
+ ) -> None:
412
+ if profile:
413
+ try:
414
+ from topic_research_profiles import profile_meta
415
+ meta = profile_meta(profile)
416
+ except Exception:
417
+ meta = {
418
+ "name": profile.get("name"),
419
+ "discipline": profile.get("discipline"),
420
+ "quality_gates": profile.get("quality_gates") or [],
421
+ "report_sections": profile.get("report_sections") or [],
422
+ "source_grades": profile.get("source_grades") or {},
423
+ "engines_priority": engines_priority,
424
+ "vertical_engines": vertical_engines,
425
+ }
426
+ report["topic_profile"] = meta.get("name")
427
+ report["topic_profile_key"] = None
428
+ report["discipline"] = meta.get("discipline")
429
+ report["quality_gates"] = meta.get("quality_gates") or []
430
+ report["report_sections"] = meta.get("report_sections") or []
431
+ report["source_grades"] = meta.get("source_grades") or {}
432
+ report["engines_priority"] = meta.get("engines_priority") or engines_priority
433
+ report["vertical_engines"] = meta.get("vertical_engines") or vertical_engines
434
+ if meta.get("discipline") == "finance":
435
+ report["disclaimer"] = (
436
+ "本输出基于公开检索结果整理,供研究线索与信息核验,"
437
+ "不构成投资建议;关键数据请回源核对。"
438
+ )
439
+ if meta.get("discipline") == "academic":
440
+ report["academic_discipline"] = {
441
+ "no_fabricated_doi": True,
442
+ "separate_evidence_layers": True,
443
+ "note": "公开摘要≠已审稿结论;DOI/期刊要求须回官方核验",
444
+ }
445
+ if plan_info is not None:
446
+ report["plan"] = plan_info
447
+ plan_lims = plan_info.get("limitations") or []
448
+ if plan_lims:
449
+ report.setdefault("plan_limitations", plan_lims)
450
+ if rewrite_result and rewrite_result.get("rewritten"):
451
+ report["rewritten_query"] = {
452
+ "original": rewrite_result["original"],
453
+ "rewritten": rewrite_result["rewritten"],
454
+ "confidence": rewrite_result["confidence"],
455
+ "reason": rewrite_result["reason"],
456
+ }
457
+
400
458
 
459
+ def _attach_evidence_loop(report: dict[str, Any], collection: dict[str, Any]) -> None:
460
+ try:
461
+ from evidence_loop import gate_results
462
+ all_results: list[dict[str, Any]] = []
463
+ sub_results = collection.get("sub_results") or []
464
+ domain_counts: dict[str, int] = {}
465
+ for sr in sub_results:
466
+ # 子查询级路由域是主来源(每个子查询各自路由,取多数);
467
+ # 单条结果上的 domain 只作补充——目前没有 producer 写它,但
468
+ # 留这条路是为了将来结果行带上更细的域时能自动升级判据。
469
+ sr_domain = (sr.get("domain") or "").strip()
470
+ if sr_domain:
471
+ domain_counts[sr_domain] = domain_counts.get(sr_domain, 0) + 1
472
+ for r in (sr.get("results") or [])[:3]:
473
+ if isinstance(r, dict):
474
+ all_results.append(r)
475
+ d = (r.get("domain") or "").strip()
476
+ if d:
477
+ domain_counts[d] = domain_counts.get(d, 0) + 1
478
+ domain = max(domain_counts, key=domain_counts.get) if domain_counts else ""
479
+ gate = gate_results(all_results, domain or None)
480
+ report["fetch_required"] = gate["fetch_required"]
481
+ pending = []
482
+ for sr in sub_results:
483
+ for r in (sr.get("results") or [])[:3]:
484
+ if isinstance(r, dict) and r.get("fetch_suggested"):
485
+ pending.append({
486
+ "sub_query": sr.get("sub_query") or sr.get("query") or sr.get("intent") or "",
487
+ "title": (r.get("title") or "")[:120],
488
+ "url": r.get("url"),
489
+ "snippet": (r.get("snippet") or "")[:160],
490
+ })
491
+ report["evidence_loop"] = {
492
+ "high_consequence_domain": gate["high_consequence_domain"],
493
+ "pending_fetch": pending,
494
+ "verified_count": gate["verified_count"],
495
+ "pending_count": gate["pending_count"],
496
+ "note": (
497
+ "高后果研究建议先核验 pending_fetch 中的信源再下结论;"
498
+ "可用 --verify 对本报告 top 结果执行 fetch 回填。"
499
+ if gate["fetch_required"] and pending else
500
+ "日常研究:结果已含证据分,关键主张仍建议回源核对。"
501
+ ),
502
+ }
503
+ except Exception as e:
504
+ # fail-open 必须可见(与 search_output 证据门控同款修正):被跳过的是
505
+ # 高后果研究的 fetch_required/pending_fetch 提示。debug 级在默认
506
+ # WARNING 下永不输出,静默跳过的门控比没有门控更危险。
507
+ import logging
508
+ logging.getLogger("unified_search").warning(
509
+ "研究证据门控跳过: %s(fetch_required/pending_fetch 本次不可用)",
510
+ type(e).__name__)
401
511
 
402
- # ── 主入口 ────────────────────────────────────────────────────────────────────
403
512
 
404
513
  def deep_research(query: str, num_sub_queries: int = 4, max_results: int = 5,
405
514
  timeout: int = 15, depth: str = "balanced",
406
- mode: str = "auto") -> dict[str, Any]:
407
- """执行深度研究。"""
408
- # 0. 查询改写
515
+ mode: str = "auto",
516
+ profile: dict[str, Any] | None = None,
517
+ budget: int | None = None,
518
+ route_strategy: str | None = None,
519
+ work_packages: Any = None,
520
+ allow_recompute: bool = False,
521
+ broaden: bool = False,
522
+ cross_lingual_trace: bool = False) -> dict[str, Any]:
523
+ """执行取证。有工作包则按依赖分阶段;否则扩词检索。产出 dossier。"""
524
+ import time as _time
525
+ _deadline = _time.time() + timeout * 3
526
+ original_query = query
527
+ engines_priority = list((profile or {}).get("engines_priority") or [])
528
+ vertical_engines = list((profile or {}).get("vertical_engines") or [])
529
+
530
+ plan_info: dict[str, Any] | None = None
531
+ try:
532
+ if _time.time() < _deadline:
533
+ from plan import build_plan
534
+ plan_info = build_plan(
535
+ query, mode=mode, depth=depth, max_results=max_results,
536
+ context="research",
537
+ )
538
+ except Exception:
539
+ plan_info = None
540
+
409
541
  rewrite_result = None
410
542
  try:
411
- from query_rewriter import rewrite_query as do_rewrite
412
- rewrite_result = do_rewrite(query)
413
- if rewrite_result["rewritten"] and rewrite_result["confidence"] >= 0.7:
414
- query = rewrite_result["rewritten"]
543
+ if _time.time() < _deadline:
544
+ from query_rewriter import rewrite_query as do_rewrite
545
+ rewrite_result = do_rewrite(query)
546
+ if rewrite_result["rewritten"] and rewrite_result["confidence"] >= 0.7:
547
+ query = rewrite_result["rewritten"]
415
548
  except Exception:
416
549
  pass
417
550
 
418
- # 1. 问题分解
419
- sub_queries = decompose_query(query, num_sub_queries)
420
-
421
- # 2. 多源采集
422
- collection = collect_sources(sub_queries, max_results, timeout, depth, mode)
551
+ packages: list[dict[str, Any]] = []
552
+ if work_packages:
553
+ packages = parse_work_packages(work_packages)
423
554
 
424
- # 3. 知识缺口
425
- gaps = identify_gaps(collection["sub_results"], query)
426
-
427
- # 4. 综合报告
428
- report = synthesize_report(query, collection, gaps)
555
+ stage_ids: list[list[str]] = []
556
+ package_warnings: list[str] = []
557
+ if packages:
558
+ collection, stage_ids, package_warnings = _collect_work_packages(
559
+ packages, max_results, timeout, depth, mode,
560
+ engines_priority or None, profile, budget, route_strategy,
561
+ )
562
+ sub_queries = packages_to_sub_queries(packages)
563
+ else:
564
+ sub_queries = _expand_sub_queries(query, num_sub_queries, profile)
565
+ collection = collect_sources(
566
+ sub_queries, max_results, timeout, depth, mode,
567
+ engines_priority=engines_priority or None,
568
+ profile=profile,
569
+ budget=budget,
570
+ route_strategy=route_strategy,
571
+ )
429
572
 
430
- if rewrite_result and rewrite_result["rewritten"]:
431
- report["rewritten_query"] = {
432
- "original": rewrite_result["original"],
433
- "rewritten": rewrite_result["rewritten"],
434
- "confidence": rewrite_result["confidence"],
435
- "reason": rewrite_result["reason"],
573
+ # ── 跨语言长程搜索与溯源链路(Cross-Lingual Long-Range Trace & Pivot)──
574
+ trace_report: dict[str, Any] | None = None
575
+ try:
576
+ from cross_lingual_trace import (
577
+ assess_cross_lingual_need,
578
+ build_cross_lingual_trace_queries,
579
+ synthesize_cross_lingual_evidence,
580
+ )
581
+ assess = assess_cross_lingual_need(
582
+ original_query,
583
+ collection.get("merged_results", []),
584
+ domain=(profile or {}).get("key") or "",
585
+ force_trace=bool(cross_lingual_trace or broaden),
586
+ )
587
+ should_trace = cross_lingual_trace or (not packages and (broaden or assess["needed"]))
588
+ if should_trace and _time.time() < _deadline:
589
+ trace_subs = []
590
+ for t_lang in assess.get("target_langs", ["en"])[:2]:
591
+ trace_subs.extend(build_cross_lingual_trace_queries(original_query, target_lang=t_lang))
592
+ existing_queries = {sq["query"] for sq in sub_queries}
593
+ trace_subs = [sq for sq in trace_subs if sq["query"] not in existing_queries]
594
+ if trace_subs:
595
+ trace_collection = collect_sources(
596
+ trace_subs, max_results, timeout, depth, mode,
597
+ engines_priority=engines_priority or None,
598
+ profile=profile, budget=budget, route_strategy=route_strategy,
599
+ )
600
+ collection["sub_results"].extend(trace_collection["sub_results"])
601
+ sub_queries.extend(trace_subs)
602
+ trace_report = synthesize_cross_lingual_evidence(
603
+ collection.get("merged_results", []),
604
+ trace_collection.get("merged_results", []),
605
+ original_query,
606
+ )
607
+ result_lists = [sr["results"] for sr in collection["sub_results"] if sr.get("results")]
608
+ if len(result_lists) > 1:
609
+ from search_rank import rrf_merge
610
+ collection["merged_results"] = rrf_merge(result_lists)[:max_results * 3]
611
+ elif result_lists:
612
+ collection["merged_results"] = result_lists[0]
613
+ except Exception as _trace_err:
614
+ import logging
615
+ logging.getLogger("unified_search").warning("跨语言长程溯源跳过: %s", _trace_err)
616
+
617
+ gaps = identify_gaps(collection["sub_results"], original_query)
618
+ source_grades = (profile or {}).get("source_grades") if profile else None
619
+ all_file_inputs: list[dict[str, Any]] = []
620
+ recompute_results: list[dict[str, Any]] = []
621
+ recompute_expected = False
622
+ if packages:
623
+ for p in packages:
624
+ if _time.time() >= _deadline:
625
+ break
626
+ all_file_inputs.extend(p.get("file_inputs") or [])
627
+ rec = p.get("recompute")
628
+ if rec:
629
+ recompute_expected = True
630
+ try:
631
+ from recompute import run_recompute
632
+ res = run_recompute(
633
+ rec["script"],
634
+ p.get("file_inputs") or [],
635
+ timeout_s=rec["budget"]["timeout_s"],
636
+ max_mem_mb=rec["budget"]["max_mem_mb"],
637
+ allow_exec=allow_recompute,
638
+ )
639
+ except Exception as e: # 执行器自身异常不入账为失败
640
+ res = {"ok": False, "skipped_reason": f"执行器异常: {e}"}
641
+ res["package_id"] = p.get("id") or ""
642
+ recompute_results.append(res)
643
+ report = build_dossier(
644
+ original_query, collection, gaps,
645
+ source_grades=source_grades, mode=mode, depth=depth,
646
+ file_inputs=all_file_inputs or None,
647
+ recompute_results=recompute_results or None,
648
+ )
649
+ report["recompute_expected"] = recompute_expected
650
+
651
+ report["execution_tier"] = "deep_research"
652
+ report["requires_confirmation"] = False
653
+ report["query_original"] = original_query
654
+ report["sub_queries"] = [
655
+ {"query": sq["query"], "intent": sq["intent"], "strategy": sq["strategy"]}
656
+ for sq in sub_queries
657
+ ]
658
+ if packages:
659
+ report["work_packages"] = packages
660
+ report["work_package_stages"] = stage_ids
661
+ if package_warnings:
662
+ report["work_package_warnings"] = package_warnings
663
+ else:
664
+ report["query_expansion"] = report["sub_queries"]
665
+
666
+ if collection.get("budget_exhausted"):
667
+ report["budget"] = {
668
+ "limit": collection.get("budget_limit"),
669
+ "exhausted": True,
670
+ "note": (
671
+ f"工具预算 {collection.get('budget_limit')} 已用尽,"
672
+ "仅覆盖部分子查询,以下为基于已完成查询的最佳部分答案,"
673
+ "剩余维度见 blind_spots / gaps"
674
+ ),
436
675
  }
437
-
676
+ elif budget is not None:
677
+ report["budget"] = {"limit": budget, "exhausted": False}
678
+ if route_strategy:
679
+ report["route_strategy"] = route_strategy
680
+
681
+ _attach_profile_and_plan(
682
+ report, profile, engines_priority, vertical_engines,
683
+ plan_info, rewrite_result,
684
+ )
685
+ _attach_evidence_loop(report, collection)
686
+ if trace_report is not None:
687
+ report["cross_lingual_trace"] = trace_report
688
+ report["quality_gate_results"] = evaluate_dossier_gates(report)
689
+ report["conclusion_cap"] = report["quality_gate_results"]["conclusion_cap"]
438
690
  return report
439
691
 
440
692
 
441
- # ── CLI ───────────────────────────────────────────────────────────────────────
442
-
443
- def main():
444
- parser = argparse.ArgumentParser(description="深度研究工具")
445
- parser.add_argument("query", help="研究查询")
446
- parser.add_argument("--sub-queries", type=int, default=4, help="子查询数量")
447
- parser.add_argument("-n", "--max-results", type=int, default=5, help="每个子查询最大结果数")
448
- parser.add_argument("--timeout", type=int, default=15, help="超时秒数")
449
- parser.add_argument("--depth", choices=["fast", "balanced", "deep"], default="balanced")
450
- parser.add_argument("--mode", choices=["fast", "auto", "deep", "budget"], default="auto")
451
- parser.add_argument("--json", action="store_true", help="JSON 输出")
452
- args = parser.parse_args()
453
-
454
- report = deep_research(
455
- args.query, args.sub_queries, args.max_results,
456
- args.timeout, args.depth, args.mode
457
- )
458
-
459
- if args.json:
460
- print(json.dumps(report, ensure_ascii=False, indent=2))
461
- else:
462
- # 人类可读输出
463
- print(f"\n{'='*60}")
464
- print(f"深度研究报告:{report['query']}")
465
- print(f"{'='*60}")
466
- print(f"子查询数:{report['sub_query_count']} | 引擎:{', '.join(report['engines_used'])}")
467
- print(f"总结果:{report['total_sources']} | 耗时:{report['elapsed_ms']}ms")
468
- print()
469
-
470
- for f in report["key_findings"]:
471
- print(f"▸ {f['aspect']}")
472
- print(f" 策略:{f['strategy']} | 结果数:{f['result_count']}")
473
- if f["top_result"]:
474
- tr = f["top_result"]
475
- print(f" 最佳:{tr['title'][:60]}")
476
- print(f" 来源:{tr['source']} | 分数:{tr['score']}")
477
- print()
478
-
479
- if report["citations"]:
480
- print("── 引用列表 ──")
481
- for c in report["citations"]:
482
- print(f" {c['id']} {c['title'][:50]} ({c['source']})")
483
- print()
484
-
485
- if report.get("cross_references"):
486
- print("── 交叉引用(多源佐证)──")
487
- for cr in report["cross_references"]:
488
- print(f" 「{cr['ngram'][:30]}」 ← {cr['source_count']} 个来源:{', '.join(cr['domains'][:3])}")
489
- print()
490
-
491
- if report["gaps"]:
492
- print("── 知识缺口 ──")
493
- for g in report["gaps"]:
494
- print(f" ⚠ {g}")
495
- print()
693
+ from social_research import ( # noqa: E402
694
+ social_sentiment_research,
695
+ aggregate_social_sentiment,
696
+ _extract_topics,
697
+ _print_social_report,
698
+ )
496
699
 
497
700
 
498
701
  if __name__ == "__main__":
702
+ from research_cli import main
499
703
  main()