qwen-sci 0.2.2__py3-none-any.whl

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 (549) hide show
  1. qwen_sci-0.2.2.dist-info/METADATA +492 -0
  2. qwen_sci-0.2.2.dist-info/RECORD +549 -0
  3. qwen_sci-0.2.2.dist-info/WHEEL +4 -0
  4. qwen_sci-0.2.2.dist-info/entry_points.txt +6 -0
  5. qwen_sci-0.2.2.dist-info/licenses/LICENSE +21 -0
  6. src/1.txt +1 -0
  7. src/__init__.py +1 -0
  8. src/__main__.py +5 -0
  9. src/agents/__init__.py +1 -0
  10. src/agents/experiment_design_agent/__init__.py +268 -0
  11. src/agents/experiment_design_agent/artifacts.py +747 -0
  12. src/agents/experiment_design_agent/cache.py +319 -0
  13. src/agents/experiment_design_agent/completeness.py +130 -0
  14. src/agents/experiment_design_agent/contracts.py +771 -0
  15. src/agents/experiment_design_agent/counterexample_analyzer.py +187 -0
  16. src/agents/experiment_design_agent/design_evidence_paper_screener.py +470 -0
  17. src/agents/experiment_design_agent/discipline_catalog.py +178 -0
  18. src/agents/experiment_design_agent/evidence_cards.py +338 -0
  19. src/agents/experiment_design_agent/evidence_planner.py +452 -0
  20. src/agents/experiment_design_agent/formal_reasoning_planner.py +884 -0
  21. src/agents/experiment_design_agent/fulltext_acquisition.py +863 -0
  22. src/agents/experiment_design_agent/idea_adapter.py +100 -0
  23. src/agents/experiment_design_agent/idea_intake.py +87 -0
  24. src/agents/experiment_design_agent/llm_json.py +328 -0
  25. src/agents/experiment_design_agent/orchestrator.py +1220 -0
  26. src/agents/experiment_design_agent/reasoning_context.py +183 -0
  27. src/agents/experiment_design_agent/reasoning_validation.py +546 -0
  28. src/agents/experiment_design_agent/run.py +481 -0
  29. src/agents/experiment_design_agent/run_logging.py +292 -0
  30. src/agents/experiment_design_agent/scope_gate.py +198 -0
  31. src/agents/experiment_design_agent/study_type_composer.py +1360 -0
  32. src/agents/experiment_design_agent/survey_evidence.py +1381 -0
  33. src/agents/experiment_design_agent/template_router.py +195 -0
  34. src/agents/experiment_design_agent/variable_claim_extractor.py +93 -0
  35. src/agents/idea_agent/__init__.py +1 -0
  36. src/agents/idea_agent/agent/__init__.py +6 -0
  37. src/agents/idea_agent/agent/artifacts.py +308 -0
  38. src/agents/idea_agent/agent/base.py +122 -0
  39. src/agents/idea_agent/agent/ligagent.py +488 -0
  40. src/agents/idea_agent/agent/mcts.py +2060 -0
  41. src/agents/idea_agent/agent/prompts/__init__.py +48 -0
  42. src/agents/idea_agent/agent/prompts/advanced_analysis.py +235 -0
  43. src/agents/idea_agent/agent/prompts/algorithm_alignment.py +55 -0
  44. src/agents/idea_agent/agent/prompts/algorithm_structuring.py +48 -0
  45. src/agents/idea_agent/agent/prompts/component_extraction.py +62 -0
  46. src/agents/idea_agent/agent/prompts/component_novelty_evaluation.py +54 -0
  47. src/agents/idea_agent/agent/prompts/experiment_findings_extraction.py +39 -0
  48. src/agents/idea_agent/agent/prompts/idea_fusion.py +295 -0
  49. src/agents/idea_agent/agent/prompts/idea_introduction.py +30 -0
  50. src/agents/idea_agent/agent/prompts/idea_result_alignment.py +39 -0
  51. src/agents/idea_agent/agent/prompts/input_interpreter.py +52 -0
  52. src/agents/idea_agent/agent/prompts/keynote_ops.py +78 -0
  53. src/agents/idea_agent/agent/prompts/mcts_evaluation.py +235 -0
  54. src/agents/idea_agent/agent/prompts/mcts_generation.py +140 -0
  55. src/agents/idea_agent/agent/prompts/mechanism_commit_query.py +99 -0
  56. src/agents/idea_agent/agent/prompts/memory_selection.py +0 -0
  57. src/agents/idea_agent/agent/prompts/prompt_modes.py +16 -0
  58. src/agents/idea_agent/agent/prompts/rag_query.py +34 -0
  59. src/agents/idea_agent/agent/prompts/re_analysis_replan.py +48 -0
  60. src/agents/idea_agent/agent/prompts/reference_grounding.py +34 -0
  61. src/agents/idea_agent/agent/prompts/root_domain_classification.py +32 -0
  62. src/agents/idea_agent/agent/prompts/scientific_debate.py +88 -0
  63. src/agents/idea_agent/agent/prompts/scientific_materialization.py +45 -0
  64. src/agents/idea_agent/agent/prompts/skill_instantiation.py +193 -0
  65. src/agents/idea_agent/agent/prompts/theory_transfer_query.py +93 -0
  66. src/agents/idea_agent/agent/prompts/topic_background.py +15 -0
  67. src/agents/idea_agent/agent/skills/DEFAULT_SKILL_TEMPLATES.json +263 -0
  68. src/agents/idea_agent/agent/skills/edit_operator_skills/alternative-path-contrast/SKILL.md +40 -0
  69. src/agents/idea_agent/agent/skills/edit_operator_skills/alternative-path-contrast/references/contrast_patterns.md +22 -0
  70. src/agents/idea_agent/agent/skills/edit_operator_skills/feedback-closed-loop/SKILL.md +40 -0
  71. src/agents/idea_agent/agent/skills/edit_operator_skills/feedback-closed-loop/references/mechanism_cards.md +24 -0
  72. src/agents/idea_agent/agent/skills/edit_operator_skills/hierarchical-decomposition/SKILL.md +39 -0
  73. src/agents/idea_agent/agent/skills/edit_operator_skills/hierarchical-decomposition/references/hierarchy_patterns.md +22 -0
  74. src/agents/idea_agent/agent/skills/edit_operator_skills/mechanism-commit-innovation/SKILL.md +39 -0
  75. src/agents/idea_agent/agent/skills/edit_operator_skills/mechanism-commit-innovation/references/mechanism_commit_patterns.md +24 -0
  76. src/agents/idea_agent/agent/skills/edit_operator_skills/multi-scale-coordinator/SKILL.md +39 -0
  77. src/agents/idea_agent/agent/skills/edit_operator_skills/multi-scale-coordinator/references/coordination_patterns.md +22 -0
  78. src/agents/idea_agent/agent/skills/edit_operator_skills/speculative-execution-with-repair/SKILL.md +41 -0
  79. src/agents/idea_agent/agent/skills/edit_operator_skills/speculative-execution-with-repair/references/speculation_patterns.md +22 -0
  80. src/agents/idea_agent/agent/skills/edit_operator_skills/surgical-modularity/SKILL.md +39 -0
  81. src/agents/idea_agent/agent/skills/edit_operator_skills/surgical-modularity/references/modularity_patterns.md +22 -0
  82. src/agents/idea_agent/agent/skills/edit_operator_skills/theory-transfer-injection/SKILL.md +40 -0
  83. src/agents/idea_agent/agent/skills/edit_operator_skills/theory-transfer-injection/references/transfer_patterns.md +24 -0
  84. src/agents/idea_agent/example/idea_result.json +900 -0
  85. src/agents/idea_agent/run.py +276 -0
  86. src/agents/idea_agent/tests/test_advanced_analysis_contract.py +90 -0
  87. src/agents/idea_agent/tests/test_gap_hypothesis_bridge.py +166 -0
  88. src/agents/idea_agent/tests/test_idea_debate.py +480 -0
  89. src/agents/idea_agent/tests/test_idea_result_v5.py +99 -0
  90. src/agents/idea_agent/tests/test_idea_synthesis.py +92 -0
  91. src/agents/idea_agent/tests/test_mature_idea_sources.py +27 -0
  92. src/agents/idea_agent/tests/test_multimodal_idea_integration.py +386 -0
  93. src/agents/idea_agent/tests/test_profile_materialization_and_scoring.py +219 -0
  94. src/agents/idea_agent/tests/test_profile_native_skill_rendering.py +122 -0
  95. src/agents/idea_agent/tests/test_result_persistence.py +183 -0
  96. src/agents/idea_agent/tests/test_scientific_intervention_profiles.py +241 -0
  97. src/agents/idea_agent/tests/test_scientific_rubric_and_prompts.py +559 -0
  98. src/agents/idea_agent/tests/test_strict_json_object_responses.py +48 -0
  99. src/agents/idea_agent/utils/core/__init__.py +1 -0
  100. src/agents/idea_agent/utils/core/ablation_inputs.py +60 -0
  101. src/agents/idea_agent/utils/core/chat_errors.py +95 -0
  102. src/agents/idea_agent/utils/core/chat_router.py +130 -0
  103. src/agents/idea_agent/utils/core/chat_transport.py +188 -0
  104. src/agents/idea_agent/utils/core/config_loader.py +166 -0
  105. src/agents/idea_agent/utils/core/json_utils.py +28 -0
  106. src/agents/idea_agent/utils/core/logger.py +287 -0
  107. src/agents/idea_agent/utils/core/progress.py +58 -0
  108. src/agents/idea_agent/utils/core/response_parsing.py +57 -0
  109. src/agents/idea_agent/utils/core/run_inputs.py +198 -0
  110. src/agents/idea_agent/utils/mcts/__init__.py +1 -0
  111. src/agents/idea_agent/utils/mcts/component_novelty.py +342 -0
  112. src/agents/idea_agent/utils/mcts/defect_registry.py +302 -0
  113. src/agents/idea_agent/utils/mcts/idea_routes.py +61 -0
  114. src/agents/idea_agent/utils/mcts/idea_taste_presets.py +312 -0
  115. src/agents/idea_agent/utils/mcts/mcts_helpers.py +738 -0
  116. src/agents/idea_agent/utils/mcts/mcts_runtime.py +3000 -0
  117. src/agents/idea_agent/utils/mcts/scientific_intervention_ontology.py +1561 -0
  118. src/agents/idea_agent/utils/mcts/scientific_rubric.py +211 -0
  119. src/agents/idea_agent/utils/mcts/skill_parsing.py +92 -0
  120. src/agents/idea_agent/utils/papers/__init__.py +1 -0
  121. src/agents/idea_agent/utils/papers/paper_graph_vector_store.py +499 -0
  122. src/agents/idea_agent/utils/papers/paper_repository.py +372 -0
  123. src/agents/idea_agent/utils/prompting/__init__.py +1 -0
  124. src/agents/idea_agent/utils/prompting/prompt_views.py +637 -0
  125. src/agents/idea_agent/utils/workflow/__init__.py +1 -0
  126. src/agents/idea_agent/utils/workflow/advanced_analysis_contract.py +244 -0
  127. src/agents/idea_agent/utils/workflow/gap_hypothesis_bridge.py +461 -0
  128. src/agents/idea_agent/utils/workflow/idea_contract.py +426 -0
  129. src/agents/idea_agent/utils/workflow/idea_debate.py +1238 -0
  130. src/agents/idea_agent/utils/workflow/idea_diversity.py +163 -0
  131. src/agents/idea_agent/utils/workflow/idea_fusion.py +889 -0
  132. src/agents/idea_agent/utils/workflow/idea_helpers.py +478 -0
  133. src/agents/idea_agent/utils/workflow/idea_portfolio.py +422 -0
  134. src/agents/idea_agent/utils/workflow/idea_synthesis.py +482 -0
  135. src/agents/idea_agent/utils/workflow/ligagent_flow.py +581 -0
  136. src/agents/idea_agent/utils/workflow/ligagent_handlers.py +1836 -0
  137. src/agents/idea_agent/utils/workflow/ligagent_helpers.py +1331 -0
  138. src/agents/idea_agent/utils/workflow/ligagent_utils.py +322 -0
  139. src/agents/idea_agent/utils/workflow/mature_idea_sources.py +648 -0
  140. src/agents/idea_agent/utils/workflow/multimodal_data_anchoring.py +578 -0
  141. src/agents/idea_agent/utils/workflow/result_persistence.py +774 -0
  142. src/agents/idea_agent/utils/workflow/stage_contract.py +76 -0
  143. src/agents/idea_agent/utils/workflow/workflow_runtime.py +288 -0
  144. src/agents/research_plan_author/__init__.py +50 -0
  145. src/agents/research_plan_author/artifacts.py +270 -0
  146. src/agents/research_plan_author/authoring_blueprint.py +1246 -0
  147. src/agents/research_plan_author/bibtex_renderer.py +252 -0
  148. src/agents/research_plan_author/contract_repair.py +131 -0
  149. src/agents/research_plan_author/contracts.py +745 -0
  150. src/agents/research_plan_author/cross_section_editor.py +232 -0
  151. src/agents/research_plan_author/document_quality.py +987 -0
  152. src/agents/research_plan_author/idea_evolution.py +223 -0
  153. src/agents/research_plan_author/input_loader.py +76 -0
  154. src/agents/research_plan_author/latex_compiler.py +260 -0
  155. src/agents/research_plan_author/latex_safety.py +159 -0
  156. src/agents/research_plan_author/llm_json.py +74 -0
  157. src/agents/research_plan_author/markdown_renderer.py +275 -0
  158. src/agents/research_plan_author/pdf_validator.py +149 -0
  159. src/agents/research_plan_author/render.py +166 -0
  160. src/agents/research_plan_author/render_artifacts.py +187 -0
  161. src/agents/research_plan_author/run.py +765 -0
  162. src/agents/research_plan_author/run_logging.py +209 -0
  163. src/agents/research_plan_author/section_cache.py +184 -0
  164. src/agents/research_plan_author/section_composer.py +1764 -0
  165. src/agents/research_plan_author/section_router.py +209 -0
  166. src/agents/research_plan_author/semantic_validator.py +254 -0
  167. src/agents/research_plan_author/source_bundle.py +46 -0
  168. src/agents/research_plan_author/source_registry.py +208 -0
  169. src/agents/research_plan_author/survey_source_loader.py +137 -0
  170. src/agents/research_plan_author/template_adapter.py +173 -0
  171. src/agents/research_plan_author/template_profile.py +204 -0
  172. src/agents/research_plan_author/tex_renderer.py +496 -0
  173. src/agents/research_plan_author/theory_presentation.py +134 -0
  174. src/agents/research_plan_author/theory_spine.py +703 -0
  175. src/agents/survey_agent/Dockerfile +54 -0
  176. src/agents/survey_agent/README.md +350 -0
  177. src/agents/survey_agent/config/deep_survey.yaml +217 -0
  178. src/agents/survey_agent/config/deep_survey_batch.yaml +176 -0
  179. src/agents/survey_agent/config/deep_survey_fast.yaml +183 -0
  180. src/agents/survey_agent/config/evaluate_baseline.yaml +197 -0
  181. src/agents/survey_agent/config/outcomeRAG.yaml +159 -0
  182. src/agents/survey_agent/env_report.md +348 -0
  183. src/agents/survey_agent/modules/__init__.py +0 -0
  184. src/agents/survey_agent/modules/code_collector.py +2194 -0
  185. src/agents/survey_agent/modules/code_report_generator.py +1282 -0
  186. src/agents/survey_agent/modules/data_manager.py +1713 -0
  187. src/agents/survey_agent/modules/database.py +167 -0
  188. src/agents/survey_agent/modules/fulltext_download_cache.py +462 -0
  189. src/agents/survey_agent/modules/fulltext_http.py +134 -0
  190. src/agents/survey_agent/modules/fulltext_resolution.py +749 -0
  191. src/agents/survey_agent/modules/judge.py +434 -0
  192. src/agents/survey_agent/modules/outcome_RAG.py +236 -0
  193. src/agents/survey_agent/modules/paper_graph_retriever.py +1075 -0
  194. src/agents/survey_agent/modules/pe.py +1729 -0
  195. src/agents/survey_agent/modules/pseudo_creator.py +782 -0
  196. src/agents/survey_agent/modules/pseudo_reviser.py +537 -0
  197. src/agents/survey_agent/modules/refine_agent.py +1952 -0
  198. src/agents/survey_agent/modules/survey_generator.py +5691 -0
  199. src/agents/survey_agent/modules/survey_visualizer.py +1817 -0
  200. src/agents/survey_agent/modules/visual_prompts.py +327 -0
  201. src/agents/survey_agent/modules/work_analyzer.py +2750 -0
  202. src/agents/survey_agent/modules/work_collector.py +5649 -0
  203. src/agents/survey_agent/scripts/baseline_evaluation.py +411 -0
  204. src/agents/survey_agent/scripts/run_deep_survey.py +224 -0
  205. src/agents/survey_agent/scripts/run_deep_survey_adapter.py +407 -0
  206. src/agents/survey_agent/scripts/run_deep_survey_adapter_with_input.py +409 -0
  207. src/agents/survey_agent/scripts/run_deep_survey_batch.py +228 -0
  208. src/agents/survey_agent/scripts/run_deep_survey_batch_arg.py +243 -0
  209. src/agents/survey_agent/scripts/run_deep_survey_batch_settings.py +218 -0
  210. src/agents/survey_agent/scripts/run_keynotes_gen.py +128 -0
  211. src/agents/survey_agent/scripts/run_work_clusters.py +140 -0
  212. src/agents/survey_agent/utils/__init__.py +0 -0
  213. src/agents/survey_agent/utils/ablation_utils.py +317 -0
  214. src/agents/survey_agent/utils/api_call.py +2518 -0
  215. src/agents/survey_agent/utils/chat_utils.py +82 -0
  216. src/agents/survey_agent/utils/config_utils.py +70 -0
  217. src/agents/survey_agent/utils/convert_to_md.py +29 -0
  218. src/agents/survey_agent/utils/err_info.py +24 -0
  219. src/agents/survey_agent/utils/file_utils.py +176 -0
  220. src/agents/survey_agent/utils/gpu_utils.py +145 -0
  221. src/agents/survey_agent/utils/graph_visualizer.py +279 -0
  222. src/agents/survey_agent/utils/html_utils.py +181 -0
  223. src/agents/survey_agent/utils/latex_generator_intra_cluster.py +529 -0
  224. src/agents/survey_agent/utils/latex_generator_relation_table.py +193 -0
  225. src/agents/survey_agent/utils/mineru_section_packer.py +334 -0
  226. src/agents/survey_agent/utils/mineru_utils.py +396 -0
  227. src/agents/survey_agent/utils/paper.py +144 -0
  228. src/agents/survey_agent/utils/read_yaml.py +15 -0
  229. src/agents/survey_agent/utils/repo_utils.py +167 -0
  230. src/agents/survey_agent/utils/rich_logger.py +77 -0
  231. src/agents/survey_agent/utils/step2v2.py +874 -0
  232. src/agents/survey_agent/utils/step2v2_extractor.py +856 -0
  233. src/agents/survey_agent/utils/topic_survey_storage.py +309 -0
  234. src/agents/survey_agent/utils/utils.py +118 -0
  235. src/agents/survey_agent/utils/work.py +2 -0
  236. src/cli.py +1611 -0
  237. src/config/__init__.py +213 -0
  238. src/config/default.yaml +1122 -0
  239. src/harness/LICENSE +21 -0
  240. src/harness/VENDORED.md +14 -0
  241. src/harness/src/__init__.py +0 -0
  242. src/harness/src/openharness/__init__.py +0 -0
  243. src/harness/src/openharness/__main__.py +6 -0
  244. src/harness/src/openharness/api/__init__.py +21 -0
  245. src/harness/src/openharness/api/client.py +281 -0
  246. src/harness/src/openharness/api/codex_client.py +407 -0
  247. src/harness/src/openharness/api/copilot_auth.py +240 -0
  248. src/harness/src/openharness/api/copilot_client.py +134 -0
  249. src/harness/src/openharness/api/errors.py +19 -0
  250. src/harness/src/openharness/api/openai_client.py +577 -0
  251. src/harness/src/openharness/api/provider.py +186 -0
  252. src/harness/src/openharness/api/registry.py +437 -0
  253. src/harness/src/openharness/api/usage.py +17 -0
  254. src/harness/src/openharness/auth/__init__.py +29 -0
  255. src/harness/src/openharness/auth/external.py +610 -0
  256. src/harness/src/openharness/auth/flows.py +189 -0
  257. src/harness/src/openharness/auth/manager.py +482 -0
  258. src/harness/src/openharness/auth/storage.py +269 -0
  259. src/harness/src/openharness/autopilot/__init__.py +23 -0
  260. src/harness/src/openharness/autopilot/service.py +2239 -0
  261. src/harness/src/openharness/autopilot/types.py +91 -0
  262. src/harness/src/openharness/bridge/__init__.py +20 -0
  263. src/harness/src/openharness/bridge/manager.py +106 -0
  264. src/harness/src/openharness/bridge/session_runner.py +46 -0
  265. src/harness/src/openharness/bridge/types.py +37 -0
  266. src/harness/src/openharness/bridge/work_secret.py +41 -0
  267. src/harness/src/openharness/channels/UPSTREAM +6 -0
  268. src/harness/src/openharness/channels/__init__.py +22 -0
  269. src/harness/src/openharness/channels/adapter.py +131 -0
  270. src/harness/src/openharness/channels/bus/__init__.py +6 -0
  271. src/harness/src/openharness/channels/bus/events.py +38 -0
  272. src/harness/src/openharness/channels/bus/queue.py +44 -0
  273. src/harness/src/openharness/channels/impl/__init__.py +6 -0
  274. src/harness/src/openharness/channels/impl/base.py +141 -0
  275. src/harness/src/openharness/channels/impl/dingtalk.py +445 -0
  276. src/harness/src/openharness/channels/impl/discord.py +311 -0
  277. src/harness/src/openharness/channels/impl/email.py +410 -0
  278. src/harness/src/openharness/channels/impl/feishu.py +1342 -0
  279. src/harness/src/openharness/channels/impl/manager.py +257 -0
  280. src/harness/src/openharness/channels/impl/matrix.py +700 -0
  281. src/harness/src/openharness/channels/impl/mochat.py +897 -0
  282. src/harness/src/openharness/channels/impl/qq.py +141 -0
  283. src/harness/src/openharness/channels/impl/slack.py +284 -0
  284. src/harness/src/openharness/channels/impl/telegram.py +525 -0
  285. src/harness/src/openharness/channels/impl/whatsapp.py +159 -0
  286. src/harness/src/openharness/cli.py +2551 -0
  287. src/harness/src/openharness/commands/__init__.py +21 -0
  288. src/harness/src/openharness/commands/registry.py +2783 -0
  289. src/harness/src/openharness/config/__init__.py +34 -0
  290. src/harness/src/openharness/config/paths.py +160 -0
  291. src/harness/src/openharness/config/schema.py +119 -0
  292. src/harness/src/openharness/config/settings.py +1104 -0
  293. src/harness/src/openharness/coordinator/__init__.py +12 -0
  294. src/harness/src/openharness/coordinator/agent_definitions.py +975 -0
  295. src/harness/src/openharness/coordinator/coordinator_mode.py +520 -0
  296. src/harness/src/openharness/engine/__init__.py +80 -0
  297. src/harness/src/openharness/engine/cost_tracker.py +24 -0
  298. src/harness/src/openharness/engine/messages.py +222 -0
  299. src/harness/src/openharness/engine/query.py +1188 -0
  300. src/harness/src/openharness/engine/query_engine.py +313 -0
  301. src/harness/src/openharness/engine/stream_events.py +90 -0
  302. src/harness/src/openharness/hooks/__init__.py +50 -0
  303. src/harness/src/openharness/hooks/events.py +20 -0
  304. src/harness/src/openharness/hooks/executor.py +242 -0
  305. src/harness/src/openharness/hooks/hot_reload.py +31 -0
  306. src/harness/src/openharness/hooks/loader.py +68 -0
  307. src/harness/src/openharness/hooks/schemas.py +66 -0
  308. src/harness/src/openharness/hooks/types.py +38 -0
  309. src/harness/src/openharness/keybindings/__init__.py +14 -0
  310. src/harness/src/openharness/keybindings/default_bindings.py +11 -0
  311. src/harness/src/openharness/keybindings/loader.py +22 -0
  312. src/harness/src/openharness/keybindings/parser.py +18 -0
  313. src/harness/src/openharness/keybindings/resolver.py +13 -0
  314. src/harness/src/openharness/mcp/__init__.py +79 -0
  315. src/harness/src/openharness/mcp/client.py +298 -0
  316. src/harness/src/openharness/mcp/config.py +16 -0
  317. src/harness/src/openharness/mcp/types.py +76 -0
  318. src/harness/src/openharness/memory/__init__.py +25 -0
  319. src/harness/src/openharness/memory/agent.py +91 -0
  320. src/harness/src/openharness/memory/manager.py +183 -0
  321. src/harness/src/openharness/memory/memdir.py +52 -0
  322. src/harness/src/openharness/memory/migrate.py +137 -0
  323. src/harness/src/openharness/memory/paths.py +22 -0
  324. src/harness/src/openharness/memory/relevance.py +145 -0
  325. src/harness/src/openharness/memory/scan.py +116 -0
  326. src/harness/src/openharness/memory/schema.py +443 -0
  327. src/harness/src/openharness/memory/search.py +71 -0
  328. src/harness/src/openharness/memory/team.py +90 -0
  329. src/harness/src/openharness/memory/types.py +33 -0
  330. src/harness/src/openharness/memory/usage.py +153 -0
  331. src/harness/src/openharness/output_styles/__init__.py +5 -0
  332. src/harness/src/openharness/output_styles/loader.py +42 -0
  333. src/harness/src/openharness/permissions/__init__.py +26 -0
  334. src/harness/src/openharness/permissions/checker.py +200 -0
  335. src/harness/src/openharness/permissions/modes.py +13 -0
  336. src/harness/src/openharness/personalization/__init__.py +6 -0
  337. src/harness/src/openharness/personalization/extractor.py +138 -0
  338. src/harness/src/openharness/personalization/rules.py +64 -0
  339. src/harness/src/openharness/personalization/session_hook.py +65 -0
  340. src/harness/src/openharness/platforms.py +86 -0
  341. src/harness/src/openharness/plugins/__init__.py +53 -0
  342. src/harness/src/openharness/plugins/bundled/__init__.py +0 -0
  343. src/harness/src/openharness/plugins/installer.py +39 -0
  344. src/harness/src/openharness/plugins/loader.py +730 -0
  345. src/harness/src/openharness/plugins/schemas.py +24 -0
  346. src/harness/src/openharness/plugins/types.py +59 -0
  347. src/harness/src/openharness/prompts/__init__.py +14 -0
  348. src/harness/src/openharness/prompts/claudemd.py +48 -0
  349. src/harness/src/openharness/prompts/context.py +187 -0
  350. src/harness/src/openharness/prompts/environment.py +135 -0
  351. src/harness/src/openharness/prompts/system_prompt.py +109 -0
  352. src/harness/src/openharness/sandbox/Dockerfile +6 -0
  353. src/harness/src/openharness/sandbox/__init__.py +33 -0
  354. src/harness/src/openharness/sandbox/adapter.py +148 -0
  355. src/harness/src/openharness/sandbox/docker_backend.py +232 -0
  356. src/harness/src/openharness/sandbox/docker_image.py +103 -0
  357. src/harness/src/openharness/sandbox/path_validator.py +37 -0
  358. src/harness/src/openharness/sandbox/session.py +63 -0
  359. src/harness/src/openharness/services/__init__.py +30 -0
  360. src/harness/src/openharness/services/autodream/__init__.py +34 -0
  361. src/harness/src/openharness/services/autodream/backup.py +104 -0
  362. src/harness/src/openharness/services/autodream/lock.py +138 -0
  363. src/harness/src/openharness/services/autodream/prompt.py +128 -0
  364. src/harness/src/openharness/services/autodream/service.py +313 -0
  365. src/harness/src/openharness/services/compact/__init__.py +1725 -0
  366. src/harness/src/openharness/services/cron.py +137 -0
  367. src/harness/src/openharness/services/cron_scheduler.py +595 -0
  368. src/harness/src/openharness/services/lsp/__init__.py +216 -0
  369. src/harness/src/openharness/services/memory_extract/__init__.py +261 -0
  370. src/harness/src/openharness/services/oauth/__init__.py +0 -0
  371. src/harness/src/openharness/services/session_backend.py +97 -0
  372. src/harness/src/openharness/services/session_memory/__init__.py +139 -0
  373. src/harness/src/openharness/services/session_storage.py +230 -0
  374. src/harness/src/openharness/services/token_estimation.py +15 -0
  375. src/harness/src/openharness/services/tool_outputs.py +55 -0
  376. src/harness/src/openharness/skills/__init__.py +44 -0
  377. src/harness/src/openharness/skills/_frontmatter.py +97 -0
  378. src/harness/src/openharness/skills/bundled/__init__.py +75 -0
  379. src/harness/src/openharness/skills/bundled/content/commit.md +25 -0
  380. src/harness/src/openharness/skills/bundled/content/debug.md +25 -0
  381. src/harness/src/openharness/skills/bundled/content/diagnose.md +35 -0
  382. src/harness/src/openharness/skills/bundled/content/plan.md +39 -0
  383. src/harness/src/openharness/skills/bundled/content/review.md +33 -0
  384. src/harness/src/openharness/skills/bundled/content/simplify.md +26 -0
  385. src/harness/src/openharness/skills/bundled/content/skill-creator.md +175 -0
  386. src/harness/src/openharness/skills/bundled/content/test.md +38 -0
  387. src/harness/src/openharness/skills/loader.py +229 -0
  388. src/harness/src/openharness/skills/registry.py +29 -0
  389. src/harness/src/openharness/skills/types.py +24 -0
  390. src/harness/src/openharness/state/__init__.py +6 -0
  391. src/harness/src/openharness/state/app_state.py +30 -0
  392. src/harness/src/openharness/state/store.py +40 -0
  393. src/harness/src/openharness/swarm/__init__.py +70 -0
  394. src/harness/src/openharness/swarm/in_process.py +693 -0
  395. src/harness/src/openharness/swarm/lockfile.py +24 -0
  396. src/harness/src/openharness/swarm/mailbox.py +522 -0
  397. src/harness/src/openharness/swarm/permission_sync.py +1168 -0
  398. src/harness/src/openharness/swarm/registry.py +410 -0
  399. src/harness/src/openharness/swarm/spawn_utils.py +229 -0
  400. src/harness/src/openharness/swarm/subprocess_backend.py +171 -0
  401. src/harness/src/openharness/swarm/team_lifecycle.py +910 -0
  402. src/harness/src/openharness/swarm/types.py +398 -0
  403. src/harness/src/openharness/swarm/worktree.py +315 -0
  404. src/harness/src/openharness/tasks/__init__.py +18 -0
  405. src/harness/src/openharness/tasks/local_agent_task.py +28 -0
  406. src/harness/src/openharness/tasks/local_shell_task.py +17 -0
  407. src/harness/src/openharness/tasks/manager.py +475 -0
  408. src/harness/src/openharness/tasks/stop_task.py +11 -0
  409. src/harness/src/openharness/tasks/types.py +32 -0
  410. src/harness/src/openharness/themes/__init__.py +21 -0
  411. src/harness/src/openharness/themes/builtin.py +89 -0
  412. src/harness/src/openharness/themes/loader.py +55 -0
  413. src/harness/src/openharness/themes/schema.py +54 -0
  414. src/harness/src/openharness/tools/__init__.py +107 -0
  415. src/harness/src/openharness/tools/agent_tool.py +141 -0
  416. src/harness/src/openharness/tools/ask_user_question_tool.py +46 -0
  417. src/harness/src/openharness/tools/base.py +80 -0
  418. src/harness/src/openharness/tools/bash_tool.py +259 -0
  419. src/harness/src/openharness/tools/brief_tool.py +33 -0
  420. src/harness/src/openharness/tools/config_tool.py +54 -0
  421. src/harness/src/openharness/tools/cron_create_tool.py +105 -0
  422. src/harness/src/openharness/tools/cron_delete_tool.py +32 -0
  423. src/harness/src/openharness/tools/cron_list_tool.py +69 -0
  424. src/harness/src/openharness/tools/cron_toggle_tool.py +37 -0
  425. src/harness/src/openharness/tools/enter_plan_mode_tool.py +28 -0
  426. src/harness/src/openharness/tools/enter_worktree_tool.py +80 -0
  427. src/harness/src/openharness/tools/exit_plan_mode_tool.py +28 -0
  428. src/harness/src/openharness/tools/exit_worktree_tool.py +42 -0
  429. src/harness/src/openharness/tools/file_edit_tool.py +95 -0
  430. src/harness/src/openharness/tools/file_read_tool.py +72 -0
  431. src/harness/src/openharness/tools/file_write_tool.py +87 -0
  432. src/harness/src/openharness/tools/glob_tool.py +175 -0
  433. src/harness/src/openharness/tools/grep_tool.py +374 -0
  434. src/harness/src/openharness/tools/image_generation_tool.py +447 -0
  435. src/harness/src/openharness/tools/image_to_text_tool.py +237 -0
  436. src/harness/src/openharness/tools/list_mcp_resources_tool.py +36 -0
  437. src/harness/src/openharness/tools/lsp_tool.py +154 -0
  438. src/harness/src/openharness/tools/mcp_auth_tool.py +71 -0
  439. src/harness/src/openharness/tools/mcp_tool.py +72 -0
  440. src/harness/src/openharness/tools/notebook_edit_tool.py +97 -0
  441. src/harness/src/openharness/tools/read_mcp_resource_tool.py +38 -0
  442. src/harness/src/openharness/tools/remote_trigger_tool.py +74 -0
  443. src/harness/src/openharness/tools/send_message_tool.py +58 -0
  444. src/harness/src/openharness/tools/skill_tool.py +43 -0
  445. src/harness/src/openharness/tools/sleep_tool.py +32 -0
  446. src/harness/src/openharness/tools/task_create_tool.py +56 -0
  447. src/harness/src/openharness/tools/task_get_tool.py +33 -0
  448. src/harness/src/openharness/tools/task_list_tool.py +35 -0
  449. src/harness/src/openharness/tools/task_output_tool.py +35 -0
  450. src/harness/src/openharness/tools/task_stop_tool.py +30 -0
  451. src/harness/src/openharness/tools/task_update_tool.py +50 -0
  452. src/harness/src/openharness/tools/team_create_tool.py +31 -0
  453. src/harness/src/openharness/tools/team_delete_tool.py +30 -0
  454. src/harness/src/openharness/tools/todo_write_tool.py +46 -0
  455. src/harness/src/openharness/tools/tool_search_tool.py +38 -0
  456. src/harness/src/openharness/tools/web_fetch_tool.py +117 -0
  457. src/harness/src/openharness/tools/web_search_tool.py +119 -0
  458. src/harness/src/openharness/ui/__init__.py +5 -0
  459. src/harness/src/openharness/ui/app.py +320 -0
  460. src/harness/src/openharness/ui/backend_host.py +941 -0
  461. src/harness/src/openharness/ui/coordinator_drain.py +198 -0
  462. src/harness/src/openharness/ui/input.py +32 -0
  463. src/harness/src/openharness/ui/output.py +265 -0
  464. src/harness/src/openharness/ui/permission_dialog.py +14 -0
  465. src/harness/src/openharness/ui/protocol.py +247 -0
  466. src/harness/src/openharness/ui/react_launcher.py +179 -0
  467. src/harness/src/openharness/ui/runtime.py +799 -0
  468. src/harness/src/openharness/ui/textual_app.py +495 -0
  469. src/harness/src/openharness/utils/__init__.py +0 -0
  470. src/harness/src/openharness/utils/file_lock.py +86 -0
  471. src/harness/src/openharness/utils/fs.py +98 -0
  472. src/harness/src/openharness/utils/helpers.py +77 -0
  473. src/harness/src/openharness/utils/network_guard.py +340 -0
  474. src/harness/src/openharness/utils/shell.py +147 -0
  475. src/harness/src/openharness/vim/__init__.py +5 -0
  476. src/harness/src/openharness/vim/transitions.py +8 -0
  477. src/harness/src/openharness/voice/__init__.py +7 -0
  478. src/harness/src/openharness/voice/keyterms.py +10 -0
  479. src/harness/src/openharness/voice/stream_stt.py +8 -0
  480. src/harness/src/openharness/voice/voice_mode.py +44 -0
  481. src/llm/__init__.py +29 -0
  482. src/llm/image_generation.py +402 -0
  483. src/llm/provider_registry.py +419 -0
  484. src/llm/runtime_env.py +64 -0
  485. src/llm/structured_output.py +131 -0
  486. src/llm/vision.py +198 -0
  487. src/memory/__init__.py +2 -0
  488. src/memory/api/__init__.py +1 -0
  489. src/memory/api/base_memory_system_api.py +98 -0
  490. src/memory/api/base_symbolic_memory_system_api.py +190 -0
  491. src/memory/api/base_vector_memory_system_api.py +116 -0
  492. src/memory/api/faiss_memory_system_api.py +228 -0
  493. src/memory/api/slot_process_api.py +827 -0
  494. src/memory/api/symbolic_memory_system_api.py +572 -0
  495. src/memory/memory_system/__init__.py +48 -0
  496. src/memory/memory_system/component_taxonomy.py +430 -0
  497. src/memory/memory_system/llm.py +437 -0
  498. src/memory/memory_system/models.py +168 -0
  499. src/memory/memory_system/user_prompt.py +418 -0
  500. src/memory/memory_system/utils.py +282 -0
  501. src/memory/memory_system/vectorstore.py +311 -0
  502. src/memory/memory_system/working_slot.py +99 -0
  503. src/pipeline/__init__.py +129 -0
  504. src/pipeline/contracts.py +531 -0
  505. src/pipeline/discipline_taxonomy.py +916 -0
  506. src/pipeline/evidence_coverage_ledger.py +1150 -0
  507. src/pipeline/evidence_refinement.py +620 -0
  508. src/pipeline/experiment_to_symbolic.py +137 -0
  509. src/pipeline/multimodal_evidence/__init__.py +28 -0
  510. src/pipeline/multimodal_evidence/capabilities.py +107 -0
  511. src/pipeline/multimodal_evidence/claims.py +135 -0
  512. src/pipeline/multimodal_evidence/contract.py +291 -0
  513. src/pipeline/multimodal_evidence/data_sh_compiler.py +505 -0
  514. src/pipeline/multimodal_evidence/handoff_binding.py +135 -0
  515. src/pipeline/multimodal_evidence/manifest.py +254 -0
  516. src/pipeline/multimodal_evidence/native_analysis.py +479 -0
  517. src/pipeline/multimodal_evidence/perception.py +277 -0
  518. src/pipeline/multimodal_evidence/query_binding.py +65 -0
  519. src/pipeline/multimodal_evidence/rendering.py +120 -0
  520. src/pipeline/multimodal_evidence/safety.py +42 -0
  521. src/pipeline/multimodal_evidence/sampling.py +69 -0
  522. src/pipeline/multimodal_evidence/service.py +148 -0
  523. src/pipeline/multimodal_evidence/survey_integration.py +460 -0
  524. src/pipeline/paper_identity.py +52 -0
  525. src/pipeline/research_design_inventory.py +338 -0
  526. src/pipeline/research_domain_resolution.py +669 -0
  527. src/pipeline/research_identity.py +548 -0
  528. src/pipeline/research_question_contract.py +646 -0
  529. src/pipeline/retrieval_lanes.py +889 -0
  530. src/pipeline/run_loop.py +862 -0
  531. src/pipeline/science_events.py +30 -0
  532. src/pipeline/science_manifests.py +602 -0
  533. src/pipeline/science_run.py +918 -0
  534. src/pipeline/science_stages.py +709 -0
  535. src/pipeline/science_workflow.py +807 -0
  536. src/pipeline/sh_cluster_projection.py +306 -0
  537. src/pipeline/sh_graph_provenance.py +648 -0
  538. src/pipeline/subhypothesis_decomposition.py +392 -0
  539. src/pipeline/subhypothesis_evidence.py +856 -0
  540. src/pipeline/survey_evidence_plan.py +858 -0
  541. src/pipeline/survey_gap_adjudication.py +647 -0
  542. src/pipeline/survey_gap_candidates.py +840 -0
  543. src/pipeline/survey_gap_ledger.py +683 -0
  544. src/pipeline/survey_gap_triage.py +401 -0
  545. src/pipeline/survey_handoff_persistence.py +481 -0
  546. src/pipeline/survey_handoff_projection.py +457 -0
  547. src/pipeline/survey_idea_handoff.py +1112 -0
  548. src/pipeline/survey_idea_loader.py +289 -0
  549. src/research_run_ids.py +11 -0
@@ -0,0 +1,1381 @@
1
+ """Survey-style retrieval, full-text acquisition, and traceable evidence adaptation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from copy import deepcopy
6
+ from concurrent.futures import ThreadPoolExecutor, as_completed
7
+ import re
8
+ from collections.abc import Callable, Mapping, Sequence
9
+ from typing import Any
10
+
11
+ import requests
12
+
13
+ from src.pipeline.paper_identity import canonical_paper_id
14
+
15
+ from .cache import ExperimentDesignCache, content_digest, text_digest
16
+ from .design_evidence_paper_screener import (
17
+ DESIGN_EVIDENCE_PAPER_SCREENER_PROMPT,
18
+ DesignEvidencePaperScreener,
19
+ )
20
+ from .evidence_cards import (
21
+ EVIDENCE_CARD_EXTRACTOR_PROMPT,
22
+ EvidenceCardExtractor,
23
+ build_traceable_evidence_bundle,
24
+ )
25
+ from .fulltext_acquisition import SurveyCompatibleFulltextAcquirer
26
+
27
+
28
+ SURVEY_EVIDENCE_COLLECTION_SCHEMA_VERSION = "experiment_design_survey_evidence_collection_v1"
29
+ SURVEY_EVIDENCE_ADAPTATION_SCHEMA_VERSION = "experiment_design_survey_evidence_adaptation_v1"
30
+ SURVEY_EVIDENCE_COLLECTION_CACHE_VERSION = "experiment_design_survey_evidence_cache_v1"
31
+ DEFAULT_MAX_SCREENING_CANDIDATES = 18
32
+ DEFAULT_EVIDENCE_CARD_PARALLEL_WORKERS = 3
33
+
34
+
35
+ class ProviderUnavailable(RuntimeError):
36
+ """Signal an unavailable discovery provider that may trigger its configured fallback."""
37
+
38
+
39
+ class ProviderQueryError(RuntimeError):
40
+ """Signal a query or authorization error that must not silently broaden retrieval."""
41
+
42
+
43
+ def _mapping(value: object) -> dict[str, Any]:
44
+ return dict(value) if isinstance(value, Mapping) else {}
45
+
46
+
47
+ def _setting(value: object, key: str, default: object = "") -> object:
48
+ if isinstance(value, Mapping):
49
+ return value.get(key, default)
50
+ return getattr(value, key, default)
51
+
52
+
53
+ def _cache_config(config: object | None) -> object:
54
+ experiment_design = _setting(config, "experiment_design", config)
55
+ retrieval = _setting(experiment_design, "retrieval", {})
56
+ return _setting(retrieval, "cache", {"enabled": False})
57
+
58
+
59
+ def _llm_cache_context(config: object | None) -> dict[str, str]:
60
+ experiment_design = _setting(config, "experiment_design", config)
61
+ return {
62
+ "provider": _text(_setting(experiment_design, "provider", ""), limit=160),
63
+ "model": _text(_setting(experiment_design, "model", ""), limit=160),
64
+ }
65
+
66
+
67
+ def _text(value: object, *, limit: int = 1200) -> str:
68
+ return re.sub(r"\s+", " ", str(value or "")).strip()[:limit]
69
+
70
+
71
+ def _provider_endpoint(client: object, suffix: str) -> str:
72
+ base_url = _text(getattr(client, "base_url", ""), limit=2000).rstrip("/")
73
+ return f"{base_url}{suffix}" if base_url else ""
74
+
75
+
76
+ def _paper_log_records(papers: Sequence[Mapping[str, Any]], *, limit: int = 50) -> list[dict[str, Any]]:
77
+ """Return traceable result metadata without logging abstracts or full text."""
78
+
79
+ records: list[dict[str, Any]] = []
80
+ for paper in papers[: max(0, limit)]:
81
+ records.append(
82
+ {
83
+ "canonical_paper_id": _text(paper.get("canonical_paper_id"), limit=200),
84
+ "title": _text(paper.get("title"), limit=500),
85
+ "doi": _text(paper.get("doi"), limit=300),
86
+ "year": _text(paper.get("year"), limit=20),
87
+ "content_availability": _text(paper.get("content_availability"), limit=40),
88
+ "fulltext_candidate_count": len(paper.get("fulltext_candidates") or []),
89
+ }
90
+ )
91
+ return records
92
+
93
+
94
+ def _emit_retrieval_log(
95
+ logger: Any | None,
96
+ event: str,
97
+ *,
98
+ level: str = "INFO",
99
+ status: str,
100
+ **fields: object,
101
+ ) -> None:
102
+ if logger is not None:
103
+ logger.event("evidence_retrieval", event, level=level, status=status, **fields)
104
+
105
+
106
+ def _texts(value: object, *, limit: int = 100) -> list[str]:
107
+ values = value if isinstance(value, Sequence) and not isinstance(value, (str, bytes)) else [value]
108
+ output: list[str] = []
109
+ for value in values:
110
+ item = _text(value, limit=600)
111
+ if item and item not in output:
112
+ output.append(item)
113
+ if len(output) >= limit:
114
+ break
115
+ return output
116
+
117
+
118
+ def _normalize_doi(value: object) -> str:
119
+ doi = re.sub(r"^https?://(?:dx\.)?doi\.org/", "", _text(value, limit=500), flags=re.IGNORECASE)
120
+ return doi.rstrip("/.,;:").casefold()
121
+
122
+
123
+ def _title_key(title: object, year: object) -> str:
124
+ normalized = re.sub(r"[^a-z0-9]+", "", _text(title, limit=1200).casefold())
125
+ return f"title:{normalized}:{_text(year, limit=12)}" if normalized else ""
126
+
127
+
128
+ def _reconstruct_abstract(value: object) -> str:
129
+ if isinstance(value, str):
130
+ return _text(value, limit=100000)
131
+ inverted = _mapping(value)
132
+ if not inverted:
133
+ return ""
134
+ positions: list[tuple[int, str]] = []
135
+ for term, raw_positions in inverted.items():
136
+ for position in raw_positions if isinstance(raw_positions, list) else []:
137
+ if isinstance(position, int):
138
+ positions.append((position, str(term)))
139
+ return " ".join(term for _, term in sorted(positions))
140
+
141
+
142
+ def _author_names(value: object) -> list[str]:
143
+ records = value if isinstance(value, Sequence) and not isinstance(value, (str, bytes)) else [value]
144
+ names: list[str] = []
145
+ for record in records:
146
+ item = _mapping(record)
147
+ author = _mapping(item.get("author"))
148
+ name = _text(
149
+ item.get("display_name")
150
+ or item.get("name")
151
+ or author.get("display_name")
152
+ or author.get("name")
153
+ or (record if isinstance(record, str) else ""),
154
+ limit=500,
155
+ )
156
+ if name and name not in names:
157
+ names.append(name)
158
+ return names
159
+
160
+
161
+ def _bibliographic_url(*values: object) -> str:
162
+ for value in values:
163
+ text = _text(value, limit=2000)
164
+ if not text:
165
+ continue
166
+ if text.startswith(("https://", "http://")):
167
+ if re.match(r"^https?://(?:dx\.)?doi\.org/", text, flags=re.IGNORECASE):
168
+ normalized_doi = _normalize_doi(text)
169
+ return f"https://doi.org/{normalized_doi}" if normalized_doi else ""
170
+ return text
171
+ normalized_doi = _normalize_doi(text)
172
+ if normalized_doi and "/" in normalized_doi:
173
+ return f"https://doi.org/{normalized_doi}"
174
+ return ""
175
+
176
+
177
+ def _openalex_venue(work: Mapping[str, Any]) -> str:
178
+ primary_location = _mapping(work.get("primary_location"))
179
+ source = _mapping(primary_location.get("source"))
180
+ host_venue = _mapping(work.get("host_venue"))
181
+ return _text(source.get("display_name") or host_venue.get("display_name"), limit=1000)
182
+
183
+
184
+ def _semantic_venue(work: Mapping[str, Any]) -> str:
185
+ publication_venue = _mapping(work.get("publicationVenue"))
186
+ return _text(work.get("venue") or publication_venue.get("name"), limit=1000)
187
+
188
+
189
+ def _content_rank(value: object) -> int:
190
+ return {"unavailable": 0, "metadata": 1, "abstract": 2, "user_supplied": 3, "fulltext": 4}.get(
191
+ _text(value, limit=40),
192
+ 0,
193
+ )
194
+
195
+
196
+ def _canonical_identifier(*, openalex_id: object = "", doi: object = "", semantic_id: object = "") -> str:
197
+ openalex = canonical_paper_id(openalex_id)
198
+ if re.fullmatch(r"W\d+", openalex, flags=re.IGNORECASE):
199
+ return openalex
200
+ normalized_doi = _normalize_doi(doi)
201
+ if normalized_doi:
202
+ return f"doi:{normalized_doi}"
203
+ semantic = _text(semantic_id, limit=200)
204
+ return f"S2:{semantic}" if semantic else ""
205
+
206
+
207
+ def _openalex_locations(work: Mapping[str, Any]) -> list[dict[str, str]]:
208
+ open_access = _mapping(work.get("open_access"))
209
+ locations = [_mapping(work.get("best_oa_location"))]
210
+ locations.extend(_mapping(item) for item in work.get("locations") or [] if isinstance(item, Mapping))
211
+ candidates: list[dict[str, str]] = []
212
+ for index, location in enumerate(locations, start=1):
213
+ if not location:
214
+ continue
215
+ is_oa = bool(location.get("is_oa")) or bool(open_access.get("is_oa"))
216
+ if not is_oa:
217
+ continue
218
+ pdf_url = _text(location.get("pdf_url"), limit=2000)
219
+ landing_url = _text(location.get("landing_page_url"), limit=2000)
220
+ source = "openalex.best_oa_location" if index == 1 else "openalex.oa_location"
221
+ for kind, url in (("pdf", pdf_url), ("landing", landing_url)):
222
+ if url and not any(existing["url"] == url for existing in candidates):
223
+ candidates.append({"kind": kind, "url": url, "source": source})
224
+ return candidates
225
+
226
+
227
+ def _normalize_openalex_work(work: Mapping[str, Any], task_id: str, slot: str = "") -> dict[str, Any]:
228
+ ids = _mapping(work.get("ids"))
229
+ openalex_id = _text(work.get("id") or ids.get("openalex"), limit=300)
230
+ doi = _normalize_doi(work.get("doi") or ids.get("doi"))
231
+ canonical_id = _canonical_identifier(openalex_id=openalex_id, doi=doi)
232
+ abstract = _reconstruct_abstract(work.get("abstract_inverted_index") or work.get("abstract"))
233
+ authors = _author_names(work.get("authorships"))
234
+ venue = _openalex_venue(work)
235
+ url = _bibliographic_url(work.get("doi"), _mapping(work.get("primary_location")).get("landing_page_url"))
236
+ return {
237
+ "canonical_paper_id": canonical_id,
238
+ "title": _text(work.get("title"), limit=1200),
239
+ "doi": doi,
240
+ "year": work.get("publication_year") or work.get("year") or "",
241
+ **({"authors": authors} if authors else {}),
242
+ **({"venue": venue} if venue else {}),
243
+ **({"url": url} if url else {}),
244
+ "provider_ids": {"openalex": openalex_id or canonical_id, **({"doi": doi} if doi else {})},
245
+ "providers": ["openalex"],
246
+ "query_task_ids": [task_id],
247
+ "query_slots": [slot] if slot else [],
248
+ "abstract": abstract,
249
+ "abstract_source_location": "abstract:openalex",
250
+ "fulltext_candidates": _openalex_locations(work),
251
+ "fulltext_source_location": "",
252
+ "content_availability": "abstract" if abstract else "metadata",
253
+ }
254
+
255
+
256
+ def _normalize_semantic_work(work: Mapping[str, Any], task_id: str, slot: str = "") -> dict[str, Any]:
257
+ external_ids = _mapping(work.get("externalIds"))
258
+ semantic_id = _text(work.get("paperId") or work.get("paper_id"), limit=300)
259
+ openalex_id = _text(external_ids.get("OpenAlex") or external_ids.get("openalex"), limit=300)
260
+ doi = _normalize_doi(external_ids.get("DOI") or external_ids.get("doi") or work.get("doi"))
261
+ canonical_id = _canonical_identifier(openalex_id=openalex_id, doi=doi, semantic_id=semantic_id)
262
+ open_pdf = _mapping(work.get("openAccessPdf"))
263
+ pdf_url = _text(open_pdf.get("url"), limit=2000)
264
+ candidates = [{"kind": "pdf", "url": pdf_url, "source": "semantic_scholar.open_access_pdf"}] if pdf_url else []
265
+ authors = _author_names(work.get("authors"))
266
+ venue = _semantic_venue(work)
267
+ url = _bibliographic_url(doi, work.get("url"))
268
+ return {
269
+ "canonical_paper_id": canonical_id,
270
+ "title": _text(work.get("title"), limit=1200),
271
+ "doi": doi,
272
+ "year": work.get("year") or "",
273
+ **({"authors": authors} if authors else {}),
274
+ **({"venue": venue} if venue else {}),
275
+ **({"url": url} if url else {}),
276
+ "provider_ids": {"semantic_scholar": semantic_id or canonical_id, **({"openalex": openalex_id} if openalex_id else {}), **({"doi": doi} if doi else {})},
277
+ "providers": ["semantic_scholar"],
278
+ "query_task_ids": [task_id],
279
+ "query_slots": [slot] if slot else [],
280
+ "abstract": _text(work.get("abstract"), limit=100000),
281
+ "abstract_source_location": "abstract:semantic_scholar",
282
+ "fulltext_candidates": candidates,
283
+ "fulltext_source_location": "",
284
+ "content_availability": "abstract" if _text(work.get("abstract"), limit=10) else "metadata",
285
+ }
286
+
287
+
288
+ class OpenAlexWorksClient:
289
+ """Direct OpenAlex Works client without a hard discipline filter."""
290
+
291
+ def __init__(
292
+ self,
293
+ *,
294
+ api_key: str = "",
295
+ email: str = "",
296
+ session: requests.Session | None = None,
297
+ timeout_seconds: float = 30.0,
298
+ base_url: str = "https://api.openalex.org",
299
+ ) -> None:
300
+ self.api_key = _text(api_key, limit=300)
301
+ self.email = _text(email, limit=300)
302
+ self.session = session or requests.Session()
303
+ self.timeout_seconds = max(1.0, float(timeout_seconds))
304
+ self.base_url = base_url.rstrip("/")
305
+
306
+ def search(self, query_task: Mapping[str, Any], *, limit: int) -> list[dict[str, Any]]:
307
+ task = _mapping(query_task)
308
+ params: dict[str, Any] = {
309
+ "search": _text(task.get("query"), limit=2000),
310
+ "per-page": max(1, min(200, int(limit))),
311
+ }
312
+ if self.api_key:
313
+ params["api_key"] = self.api_key
314
+ if self.email:
315
+ params["mailto"] = self.email
316
+ try:
317
+ response = self.session.get(f"{self.base_url}/works", params=params, timeout=self.timeout_seconds)
318
+ except requests.RequestException as exc:
319
+ raise ProviderUnavailable("OpenAlex request failed") from exc
320
+ if response.status_code in {408, 425, 429} or response.status_code >= 500:
321
+ raise ProviderUnavailable(f"OpenAlex unavailable: HTTP {response.status_code}")
322
+ if response.status_code != 200:
323
+ raise ProviderQueryError(f"OpenAlex rejected query: HTTP {response.status_code}")
324
+ payload = _mapping(response.json())
325
+ task_id = _text(task.get("task_id"), limit=120)
326
+ slot = _text(task.get("slot"), limit=120)
327
+ return [
328
+ _normalize_openalex_work(work, task_id, slot)
329
+ for work in payload.get("results") or []
330
+ if isinstance(work, Mapping)
331
+ ]
332
+
333
+
334
+ class SemanticScholarWorksClient:
335
+ """Semantic Scholar fallback client without pretending to apply OpenAlex fields."""
336
+
337
+ def __init__(
338
+ self,
339
+ *,
340
+ api_key: str = "",
341
+ session: requests.Session | None = None,
342
+ timeout_seconds: float = 30.0,
343
+ base_url: str = "https://api.semanticscholar.org/graph/v1",
344
+ ) -> None:
345
+ self.api_key = _text(api_key, limit=300)
346
+ self.session = session or requests.Session()
347
+ self.timeout_seconds = max(1.0, float(timeout_seconds))
348
+ self.base_url = base_url.rstrip("/")
349
+
350
+ def search(self, query_task: Mapping[str, Any], *, limit: int) -> list[dict[str, Any]]:
351
+ task = _mapping(query_task)
352
+ headers = {"x-api-key": self.api_key} if self.api_key else {}
353
+ params = {
354
+ "query": _text(task.get("query"), limit=2000),
355
+ "limit": max(1, min(100, int(limit))),
356
+ "fields": "paperId,title,abstract,year,authors,venue,publicationVenue,url,externalIds,openAccessPdf",
357
+ }
358
+ try:
359
+ response = self.session.get(f"{self.base_url}/paper/search", params=params, headers=headers, timeout=self.timeout_seconds)
360
+ except requests.RequestException as exc:
361
+ raise ProviderUnavailable("Semantic Scholar request failed") from exc
362
+ if response.status_code in {408, 425, 429} or response.status_code >= 500:
363
+ raise ProviderUnavailable(f"Semantic Scholar unavailable: HTTP {response.status_code}")
364
+ if response.status_code != 200:
365
+ raise ProviderQueryError(f"Semantic Scholar rejected query: HTTP {response.status_code}")
366
+ payload = _mapping(response.json())
367
+ task_id = _text(task.get("task_id"), limit=120)
368
+ slot = _text(task.get("slot"), limit=120)
369
+ return [
370
+ _normalize_semantic_work(work, task_id, slot)
371
+ for work in payload.get("data") or []
372
+ if isinstance(work, Mapping)
373
+ ]
374
+
375
+
376
+ class SurveyArtifactAdapter:
377
+ """Apply already-collected Survey fulltext and keynote artifacts to candidate papers."""
378
+
379
+ def enrich(
380
+ self,
381
+ papers: Sequence[Mapping[str, Any]],
382
+ survey_artifacts: Mapping[str, Any] | Sequence[Mapping[str, Any]] | None,
383
+ ) -> list[dict[str, Any]]:
384
+ if not survey_artifacts:
385
+ return [deepcopy(_mapping(paper)) for paper in papers]
386
+ raw_records: object = survey_artifacts
387
+ if isinstance(survey_artifacts, Mapping):
388
+ raw_records = survey_artifacts.get("papers") or survey_artifacts.get("paper_registry") or survey_artifacts
389
+ artifact_index: dict[str, dict[str, Any]] = {}
390
+ if isinstance(raw_records, Mapping):
391
+ iterable = [
392
+ {"canonical_paper_id": identifier, **_mapping(value)}
393
+ for identifier, value in raw_records.items()
394
+ if isinstance(value, Mapping)
395
+ ]
396
+ else:
397
+ iterable = raw_records if isinstance(raw_records, Sequence) and not isinstance(raw_records, (str, bytes)) else []
398
+ for raw in iterable:
399
+ artifact = _mapping(raw)
400
+ identifiers = [
401
+ artifact.get("canonical_paper_id"),
402
+ artifact.get("paper_id"),
403
+ artifact.get("openalex_id"),
404
+ _mapping(artifact.get("provider_ids")).get("openalex"),
405
+ ]
406
+ for identifier in identifiers:
407
+ canonical = canonical_paper_id(identifier)
408
+ if canonical:
409
+ artifact_index[canonical] = artifact
410
+ enriched: list[dict[str, Any]] = []
411
+ for raw_paper in papers:
412
+ paper = deepcopy(_mapping(raw_paper))
413
+ artifact = artifact_index.get(_text(paper.get("canonical_paper_id"), limit=160), {})
414
+ fulltext = _text(artifact.get("fulltext") or artifact.get("full_text") or artifact.get("content"), limit=100000)
415
+ abstract = _text(artifact.get("abstract"), limit=100000)
416
+ if fulltext:
417
+ paper["fulltext"] = fulltext
418
+ paper["fulltext_source_location"] = _text(artifact.get("source_location"), limit=300) or "fulltext:survey_artifact"
419
+ paper["content_availability"] = "fulltext"
420
+ elif abstract and not _text(paper.get("abstract"), limit=100):
421
+ paper["abstract"] = abstract
422
+ paper["abstract_source_location"] = _text(artifact.get("source_location"), limit=300) or "abstract:survey_artifact"
423
+ paper["content_availability"] = "abstract"
424
+ if _text(artifact.get("keynote"), limit=100000):
425
+ paper["survey_keynote"] = _text(artifact.get("keynote"), limit=100000)
426
+ enriched.append(paper)
427
+ return enriched
428
+
429
+
430
+ def _identity_keys(paper: Mapping[str, Any]) -> set[str]:
431
+ provider_ids = _mapping(paper.get("provider_ids"))
432
+ keys = {
433
+ f"canonical:{_text(paper.get('canonical_paper_id'), limit=200)}",
434
+ f"doi:{_normalize_doi(paper.get('doi') or provider_ids.get('doi'))}",
435
+ _title_key(paper.get("title"), paper.get("year")),
436
+ }
437
+ return {key for key in keys if key and not key.endswith(":")}
438
+
439
+
440
+ def _merge_papers(papers: Sequence[Mapping[str, Any]]) -> list[dict[str, Any]]:
441
+ ordered = sorted(
442
+ (_mapping(paper) for paper in papers),
443
+ key=lambda paper: ("openalex" not in _texts(paper.get("providers")), _text(paper.get("canonical_paper_id"), limit=200)),
444
+ )
445
+ merged: list[dict[str, Any]] = []
446
+ index: dict[str, int] = {}
447
+ for incoming in ordered:
448
+ matching_indexes = {index[key] for key in _identity_keys(incoming) if key in index}
449
+ if not matching_indexes:
450
+ record = deepcopy(incoming)
451
+ merged.append(record)
452
+ target_index = len(merged) - 1
453
+ else:
454
+ target_index = min(matching_indexes)
455
+ record = merged[target_index]
456
+ incoming_id = _text(incoming.get("canonical_paper_id"), limit=200)
457
+ if re.fullmatch(r"W\d+", incoming_id, flags=re.IGNORECASE):
458
+ record["canonical_paper_id"] = incoming_id
459
+ for key in (
460
+ "title",
461
+ "doi",
462
+ "year",
463
+ "venue",
464
+ "url",
465
+ "abstract",
466
+ "abstract_source_location",
467
+ "fulltext",
468
+ "fulltext_source_location",
469
+ "survey_keynote",
470
+ ):
471
+ if not _text(record.get(key), limit=100) and _text(incoming.get(key), limit=100):
472
+ record[key] = incoming[key]
473
+ if not _author_names(record.get("authors")) and _author_names(incoming.get("authors")):
474
+ record["authors"] = _author_names(incoming.get("authors"))
475
+ if _content_rank(incoming.get("content_availability")) > _content_rank(record.get("content_availability")):
476
+ record["content_availability"] = incoming.get("content_availability")
477
+ provider_ids = _mapping(record.get("provider_ids"))
478
+ provider_ids.update(_mapping(incoming.get("provider_ids")))
479
+ record["provider_ids"] = provider_ids
480
+ record["providers"] = _texts([*record.get("providers", []), *incoming.get("providers", [])], limit=12)
481
+ record["query_task_ids"] = _texts([*record.get("query_task_ids", []), *incoming.get("query_task_ids", [])], limit=200)
482
+ record["query_slots"] = _texts([*record.get("query_slots", []), *incoming.get("query_slots", [])], limit=32)
483
+ candidates = list(record.get("fulltext_candidates") or [])
484
+ for candidate in incoming.get("fulltext_candidates") or []:
485
+ normalized = _mapping(candidate)
486
+ if normalized and not any(item.get("url") == normalized.get("url") for item in candidates if isinstance(item, Mapping)):
487
+ candidates.append(normalized)
488
+ record["fulltext_candidates"] = candidates
489
+ for key in _identity_keys(record):
490
+ index[key] = target_index
491
+ return merged
492
+
493
+
494
+ def _candidate_priority(paper: Mapping[str, Any]) -> tuple[int, int, int, str]:
495
+ """Rank pre-screening records using only discovery metadata.
496
+
497
+ This is deliberately not an evidence or relevance assessment. It only
498
+ bounds the required LLM screening work while preserving papers that match
499
+ more design slots, provide an abstract, or already have traceable text.
500
+ """
501
+
502
+ slot_count = len(_texts(paper.get("query_slots"), limit=32))
503
+ content_rank = _content_rank(paper.get("content_availability"))
504
+ fulltext_candidate_count = len(paper.get("fulltext_candidates") or [])
505
+ return (
506
+ -slot_count,
507
+ -content_rank,
508
+ -min(fulltext_candidate_count, 20),
509
+ _text(paper.get("canonical_paper_id"), limit=200),
510
+ )
511
+
512
+
513
+ def _bound_screening_candidates(
514
+ papers: Sequence[Mapping[str, Any]],
515
+ *,
516
+ maximum: int,
517
+ planned_slots: Sequence[str],
518
+ ) -> tuple[list[dict[str, Any]], list[dict[str, Any]], dict[str, str]]:
519
+ """Keep an explicit bounded candidate set before expensive LLM screening."""
520
+
521
+ ordered = sorted((_mapping(paper) for paper in papers), key=_candidate_priority)
522
+ limit = max(0, int(maximum))
523
+ if len(ordered) <= limit:
524
+ return ordered, [], {}
525
+ selected: list[dict[str, Any]] = []
526
+ selected_ids: set[str] = set()
527
+ selected_by_slot: dict[str, str] = {}
528
+ for slot in _texts(planned_slots, limit=32):
529
+ if len(selected) >= limit:
530
+ break
531
+ candidate = next(
532
+ (paper for paper in ordered if slot in _texts(paper.get("query_slots"), limit=32)
533
+ and _text(paper.get("canonical_paper_id"), limit=200) not in selected_ids),
534
+ None,
535
+ )
536
+ if candidate is not None:
537
+ candidate_id = _text(candidate.get("canonical_paper_id"), limit=200)
538
+ selected.append(candidate)
539
+ selected_ids.add(candidate_id)
540
+ selected_by_slot[slot] = candidate_id
541
+ for paper in ordered:
542
+ if len(selected) >= limit:
543
+ break
544
+ candidate_id = _text(paper.get("canonical_paper_id"), limit=200)
545
+ if candidate_id not in selected_ids:
546
+ selected.append(paper)
547
+ selected_ids.add(candidate_id)
548
+ omitted = [paper for paper in ordered if _text(paper.get("canonical_paper_id"), limit=200) not in selected_ids]
549
+ return selected, omitted, selected_by_slot
550
+
551
+
552
+ def _expand_query_variants(evidence_plan: Mapping[str, Any]) -> list[dict[str, Any]]:
553
+ """Expand bounded planner variants into independent provider query tasks."""
554
+
555
+ expanded: list[dict[str, Any]] = []
556
+ for raw_task in _mapping(evidence_plan).get("queries") or []:
557
+ task = _mapping(raw_task)
558
+ parent_task_id = _text(task.get("task_id"), limit=120)
559
+ slot = _text(task.get("slot"), limit=120)
560
+ if not parent_task_id or not slot:
561
+ continue
562
+ raw_variants = task.get("query_variants")
563
+ variants = (
564
+ raw_variants
565
+ if isinstance(raw_variants, Sequence) and not isinstance(raw_variants, (str, bytes))
566
+ else [
567
+ {
568
+ "variant_id": "legacy",
569
+ "query": task.get("query"),
570
+ "purpose": "Legacy single-query task supplied directly to the collector.",
571
+ }
572
+ ]
573
+ )
574
+ is_legacy = not isinstance(raw_variants, Sequence) or isinstance(raw_variants, (str, bytes))
575
+ for position, raw_variant in enumerate(variants, start=1):
576
+ variant = _mapping(raw_variant)
577
+ query = _text(variant.get("query"), limit=2000)
578
+ variant_id = _text(variant.get("variant_id"), limit=80) or f"q{position}"
579
+ purpose = _text(variant.get("purpose"), limit=600)
580
+ if not query:
581
+ continue
582
+ expanded.append(
583
+ {
584
+ **task,
585
+ "task_id": parent_task_id if is_legacy else f"{parent_task_id}.{variant_id}",
586
+ "parent_task_id": parent_task_id,
587
+ "slot": slot,
588
+ "query": query,
589
+ "query_variant_id": variant_id,
590
+ "query_variant_purpose": purpose,
591
+ }
592
+ )
593
+ return expanded
594
+
595
+
596
+ class SurveyEvidenceCollector:
597
+ """Collect per-slot papers with OpenAlex-first, unavailable-only fallback semantics."""
598
+
599
+ def __init__(
600
+ self,
601
+ *,
602
+ openalex_client: Any | None = None,
603
+ semantic_scholar_client: Any | None = None,
604
+ fulltext_fetcher: Any | None = None,
605
+ paper_screener: DesignEvidencePaperScreener | None = None,
606
+ survey_artifact_adapter: SurveyArtifactAdapter | None = None,
607
+ max_screening_candidates: int = DEFAULT_MAX_SCREENING_CANDIDATES,
608
+ cache: ExperimentDesignCache | None = None,
609
+ cache_context: Mapping[str, Any] | None = None,
610
+ ) -> None:
611
+ self.cache = cache or ExperimentDesignCache({"enabled": False})
612
+ self.cache_context = _mapping(cache_context)
613
+ self.openalex_client = openalex_client or OpenAlexWorksClient()
614
+ self.semantic_scholar_client = semantic_scholar_client or SemanticScholarWorksClient()
615
+ self.fulltext_fetcher = fulltext_fetcher or SurveyCompatibleFulltextAcquirer(cache=self.cache)
616
+ self.paper_screener = paper_screener or DesignEvidencePaperScreener()
617
+ self.survey_artifact_adapter = survey_artifact_adapter or SurveyArtifactAdapter()
618
+ self.max_screening_candidates = max(1, int(max_screening_candidates))
619
+
620
+ @classmethod
621
+ def from_config(cls, config: object | None = None) -> "SurveyEvidenceCollector":
622
+ """Build retrieval clients from the ExperimentDesign runtime configuration."""
623
+
624
+ if config is None:
625
+ from src.config import get_experiment_design_config
626
+
627
+ config = get_experiment_design_config()
628
+ experiment_design_config = _setting(config, "experiment_design", config)
629
+ retrieval = _setting(experiment_design_config, "retrieval", {})
630
+ openalex = _setting(retrieval, "openalex", {})
631
+ semantic = _setting(retrieval, "semantic_scholar", {})
632
+ fulltext = _setting(retrieval, "fulltext", {})
633
+ screening = _setting(retrieval, "paper_screening", {})
634
+ cache = ExperimentDesignCache(_cache_config(config))
635
+ return cls(
636
+ openalex_client=OpenAlexWorksClient(
637
+ api_key=str(_setting(openalex, "api_key", "") or ""),
638
+ email=str(_setting(openalex, "email", "") or ""),
639
+ base_url=str(_setting(openalex, "base_url", "https://api.openalex.org") or "https://api.openalex.org"),
640
+ ),
641
+ semantic_scholar_client=SemanticScholarWorksClient(
642
+ api_key=str(_setting(semantic, "api_key", "") or ""),
643
+ base_url=str(_setting(semantic, "base_url", "https://api.semanticscholar.org/graph/v1") or "https://api.semanticscholar.org/graph/v1"),
644
+ ),
645
+ fulltext_fetcher=SurveyCompatibleFulltextAcquirer(fulltext, cache=cache),
646
+ paper_screener=DesignEvidencePaperScreener(
647
+ fulltext_budget=max(
648
+ 0,
649
+ int(_setting(screening, "fulltext_budget", _setting(fulltext, "max_papers", 15)) or 0),
650
+ ),
651
+ parallel_workers=max(
652
+ 1,
653
+ int(_setting(screening, "parallel_workers", 8) or 1),
654
+ ),
655
+ ),
656
+ max_screening_candidates=max(
657
+ 1,
658
+ int(_setting(screening, "max_candidates_before_llm", DEFAULT_MAX_SCREENING_CANDIDATES) or 1),
659
+ ),
660
+ cache=cache,
661
+ cache_context=_llm_cache_context(config),
662
+ )
663
+
664
+ def _fetch_fulltext(
665
+ self,
666
+ paper: Mapping[str, Any],
667
+ *,
668
+ logger: Any | None = None,
669
+ cache_run_id: str = "",
670
+ ) -> dict[str, Any]:
671
+ acquire = getattr(self.fulltext_fetcher, "acquire", None)
672
+ fetch = acquire if callable(acquire) else getattr(self.fulltext_fetcher, "fetch", self.fulltext_fetcher)
673
+ try:
674
+ if callable(acquire):
675
+ try:
676
+ result = fetch(paper, logger=logger, cache_run_id=cache_run_id)
677
+ except TypeError:
678
+ result = fetch(paper, logger=logger)
679
+ else:
680
+ result = fetch(paper)
681
+ except Exception as exc:
682
+ return {
683
+ "fulltext_acquisition": {
684
+ "schema_version": "experiment_design_fulltext_acquisition_v1",
685
+ "status": "acquisition_error",
686
+ "selected_candidate": {},
687
+ "attempts": [],
688
+ "parser": {"backend": "survey_mineru", "status": "not_started"},
689
+ "error_type": type(exc).__name__,
690
+ }
691
+ }
692
+ return _mapping(result)
693
+
694
+ def collect(
695
+ self,
696
+ evidence_plan: Mapping[str, Any],
697
+ *,
698
+ max_results_per_query: int = 10,
699
+ max_fulltext_papers: int = 15,
700
+ survey_artifacts: Mapping[str, Any] | Sequence[Mapping[str, Any]] | None = None,
701
+ screener_llm_call: Callable[..., object] | None = None,
702
+ logger: Any | None = None,
703
+ cache_run_id: str = "",
704
+ ) -> dict[str, Any]:
705
+ plan = _mapping(evidence_plan)
706
+ collection_cache_identity = {
707
+ "evidence_plan": plan,
708
+ "max_results_per_query": max(1, int(max_results_per_query)),
709
+ "max_fulltext_papers": max(0, int(max_fulltext_papers)),
710
+ "survey_artifacts_sha256": content_digest(survey_artifacts or {}),
711
+ "collection_schema_version": SURVEY_EVIDENCE_COLLECTION_SCHEMA_VERSION,
712
+ "collection_cache_version": SURVEY_EVIDENCE_COLLECTION_CACHE_VERSION,
713
+ "paper_screener_prompt_sha256": text_digest(DESIGN_EVIDENCE_PAPER_SCREENER_PROMPT),
714
+ "cache_context": self.cache_context,
715
+ }
716
+ cached_collection = self.cache.read(
717
+ "retrieval_collections",
718
+ collection_cache_identity,
719
+ run_id=cache_run_id,
720
+ )
721
+ if cached_collection is not None:
722
+ _emit_retrieval_log(
723
+ logger,
724
+ "collection_cache_hit",
725
+ status="CACHED",
726
+ paper_count=len(cached_collection.get("papers") or []),
727
+ )
728
+ return cached_collection
729
+ expanded_tasks = _expand_query_variants(plan)
730
+ if self.cache.offline:
731
+ _emit_retrieval_log(
732
+ logger,
733
+ "collection_cache_miss",
734
+ level="WARNING",
735
+ status="OFFLINE_DEGRADED",
736
+ query_variant_count=len(expanded_tasks),
737
+ )
738
+ return {
739
+ "schema_version": SURVEY_EVIDENCE_COLLECTION_SCHEMA_VERSION,
740
+ "collection_policy": "read_only_cache_miss_no_external_retrieval",
741
+ "provider_runs": [
742
+ {
743
+ "task_id": _text(task.get("task_id"), limit=120),
744
+ "provider": "cache",
745
+ "status": "CACHE_MISS",
746
+ "native_field_filter": [],
747
+ "native_field_filter_applied": False,
748
+ "detail": "No matching retrieval snapshot is available; no provider was contacted.",
749
+ }
750
+ for task in expanded_tasks
751
+ ],
752
+ "papers": [],
753
+ "paper_count": 0,
754
+ "paper_screening": {
755
+ "schema_version": "experiment_design_paper_screening_audit_v1",
756
+ "screening_policy": "not_run_read_only_cache_miss",
757
+ "requested_slots": _texts([_mapping(task).get("slot") for task in expanded_tasks], limit=32),
758
+ "fulltext_budget": 0,
759
+ "screening_candidate_budget": self.max_screening_candidates,
760
+ "discovered_unique_paper_count": 0,
761
+ "screened_paper_count": 0,
762
+ "omitted_before_screening_count": 0,
763
+ "omitted_before_screening_paper_ids": [],
764
+ "pre_screen_selected_by_slot": {},
765
+ "eligible_for_fulltext_count": 0,
766
+ "selected_paper_ids": [],
767
+ "selected_by_slot": {},
768
+ "screens_by_paper": {},
769
+ },
770
+ "fulltext_acquisition_by_paper": {},
771
+ }
772
+ records: list[dict[str, Any]] = []
773
+ provider_runs: list[dict[str, Any]] = []
774
+ for task in expanded_tasks:
775
+ task_id = _text(task.get("task_id"), limit=120)
776
+ if not task_id:
777
+ continue
778
+ field_filter: list[str] = []
779
+ query_fields = {
780
+ "task_id": task_id,
781
+ "parent_task_id": _text(task.get("parent_task_id"), limit=120),
782
+ "query_variant_id": _text(task.get("query_variant_id"), limit=80),
783
+ "slot": _text(task.get("slot"), limit=120),
784
+ "query": _text(task.get("query"), limit=2000),
785
+ "requested_limit": max(1, int(max_results_per_query)),
786
+ "native_field_filter": field_filter,
787
+ "endpoint": _provider_endpoint(self.openalex_client, "/works"),
788
+ }
789
+ _emit_retrieval_log(
790
+ logger,
791
+ "openalex_query",
792
+ status="RUNNING",
793
+ provider="openalex",
794
+ **query_fields,
795
+ )
796
+ try:
797
+ papers = self.openalex_client.search(task, limit=max_results_per_query)
798
+ except ProviderUnavailable as exc:
799
+ _emit_retrieval_log(
800
+ logger,
801
+ "openalex_query",
802
+ level="WARNING",
803
+ status="UNAVAILABLE",
804
+ provider="openalex",
805
+ error=_text(exc, limit=400),
806
+ **query_fields,
807
+ )
808
+ provider_runs.append(
809
+ {
810
+ "task_id": task_id,
811
+ "provider": "openalex",
812
+ "status": "UNAVAILABLE",
813
+ "native_field_filter": field_filter,
814
+ "native_field_filter_applied": False,
815
+ "detail": _text(exc, limit=400),
816
+ }
817
+ )
818
+ _emit_retrieval_log(
819
+ logger,
820
+ "semantic_scholar_query",
821
+ status="RUNNING",
822
+ provider="semantic_scholar",
823
+ fallback_reason="openalex_unavailable",
824
+ endpoint=_provider_endpoint(self.semantic_scholar_client, "/paper/search"),
825
+ **{key: value for key, value in query_fields.items() if key != "endpoint"},
826
+ )
827
+ try:
828
+ papers = self.semantic_scholar_client.search(task, limit=max_results_per_query)
829
+ except (ProviderUnavailable, ProviderQueryError) as fallback_exc:
830
+ _emit_retrieval_log(
831
+ logger,
832
+ "semantic_scholar_query",
833
+ level="WARNING",
834
+ status="UNAVAILABLE",
835
+ provider="semantic_scholar",
836
+ fallback_reason="openalex_unavailable",
837
+ error=_text(fallback_exc, limit=400),
838
+ endpoint=_provider_endpoint(self.semantic_scholar_client, "/paper/search"),
839
+ **{key: value for key, value in query_fields.items() if key != "endpoint"},
840
+ )
841
+ provider_runs.append(
842
+ {
843
+ "task_id": task_id,
844
+ "provider": "semantic_scholar",
845
+ "status": "UNAVAILABLE",
846
+ "native_field_filter": field_filter,
847
+ "native_field_filter_applied": False,
848
+ "detail": _text(fallback_exc, limit=400),
849
+ }
850
+ )
851
+ continue
852
+ _emit_retrieval_log(
853
+ logger,
854
+ "semantic_scholar_results",
855
+ status="FALLBACK_SUCCESS" if papers else "FALLBACK_EMPTY",
856
+ provider="semantic_scholar",
857
+ fallback_reason="openalex_unavailable",
858
+ paper_count=len(papers),
859
+ papers=_paper_log_records(papers),
860
+ endpoint=_provider_endpoint(self.semantic_scholar_client, "/paper/search"),
861
+ **{key: value for key, value in query_fields.items() if key != "endpoint"},
862
+ )
863
+ provider_runs.append(
864
+ {
865
+ "task_id": task_id,
866
+ "provider": "semantic_scholar",
867
+ "status": "FALLBACK_SUCCESS" if papers else "FALLBACK_EMPTY",
868
+ "native_field_filter": field_filter,
869
+ "native_field_filter_applied": False,
870
+ "detail": "Semantic Scholar was used only because OpenAlex was unavailable.",
871
+ }
872
+ )
873
+ records.extend(_mapping(paper) for paper in papers)
874
+ continue
875
+ except ProviderQueryError as exc:
876
+ _emit_retrieval_log(
877
+ logger,
878
+ "openalex_query",
879
+ level="WARNING",
880
+ status="QUERY_ERROR",
881
+ provider="openalex",
882
+ error=_text(exc, limit=400),
883
+ **query_fields,
884
+ )
885
+ provider_runs.append(
886
+ {
887
+ "task_id": task_id,
888
+ "provider": "openalex",
889
+ "status": "QUERY_ERROR",
890
+ "native_field_filter": field_filter,
891
+ "native_field_filter_applied": False,
892
+ "detail": _text(exc, limit=400),
893
+ }
894
+ )
895
+ continue
896
+ _emit_retrieval_log(
897
+ logger,
898
+ "openalex_results",
899
+ status="SUCCESS" if papers else "EMPTY",
900
+ provider="openalex",
901
+ paper_count=len(papers),
902
+ papers=_paper_log_records(papers),
903
+ **query_fields,
904
+ )
905
+ provider_runs.append(
906
+ {
907
+ "task_id": task_id,
908
+ "provider": "openalex",
909
+ "status": "SUCCESS" if papers else "EMPTY",
910
+ "native_field_filter": field_filter,
911
+ "native_field_filter_applied": bool(field_filter),
912
+ "detail": "OpenAlex returned a valid response; a valid empty result does not trigger fallback.",
913
+ }
914
+ )
915
+ records.extend(_mapping(paper) for paper in papers)
916
+ merged = _merge_papers(records)
917
+ enriched = self.survey_artifact_adapter.enrich(merged, survey_artifacts)
918
+ configured_fulltext_limit = getattr(self.fulltext_fetcher, "max_papers", max_fulltext_papers)
919
+ fulltext_limit = min(
920
+ max(0, int(max_fulltext_papers)),
921
+ max(0, int(configured_fulltext_limit)),
922
+ max(0, int(getattr(self.paper_screener, "fulltext_budget", 15))),
923
+ )
924
+ requested_slots = _texts(
925
+ [_mapping(task).get("slot") for task in expanded_tasks],
926
+ limit=32,
927
+ )
928
+ screening_candidates, omitted_candidates, pre_screen_selected_by_slot = _bound_screening_candidates(
929
+ enriched,
930
+ maximum=self.max_screening_candidates,
931
+ planned_slots=requested_slots,
932
+ )
933
+ _emit_retrieval_log(
934
+ logger,
935
+ "screening_candidates_bounded",
936
+ status="COMPLETED",
937
+ discovered_unique_paper_count=len(enriched),
938
+ screening_candidate_budget=self.max_screening_candidates,
939
+ selected_candidate_count=len(screening_candidates),
940
+ omitted_before_screening_count=len(omitted_candidates),
941
+ pre_screen_selected_by_slot=pre_screen_selected_by_slot,
942
+ selected_candidate_ids=[
943
+ _text(paper.get("canonical_paper_id"), limit=200) for paper in screening_candidates
944
+ ],
945
+ )
946
+ enriched = screening_candidates
947
+ screening_audit: dict[str, Any] = {
948
+ "schema_version": "experiment_design_paper_screening_audit_v1",
949
+ "screening_policy": "bounded_candidate_set_before_required_json_llm_screening",
950
+ "requested_slots": requested_slots,
951
+ "fulltext_budget": fulltext_limit,
952
+ "screening_candidate_budget": self.max_screening_candidates,
953
+ "discovered_unique_paper_count": len(enriched) + len(omitted_candidates),
954
+ "screened_paper_count": 0,
955
+ "omitted_before_screening_count": len(omitted_candidates),
956
+ "omitted_before_screening_paper_ids": [
957
+ _text(paper.get("canonical_paper_id"), limit=200) for paper in omitted_candidates
958
+ ],
959
+ "pre_screen_selected_by_slot": pre_screen_selected_by_slot,
960
+ "eligible_for_fulltext_count": 0,
961
+ "selected_paper_ids": [],
962
+ "selected_by_slot": {},
963
+ "screens_by_paper": {},
964
+ }
965
+ if screening_candidates and fulltext_limit > 0:
966
+ screened_candidates, screening_audit = self.paper_screener.screen_and_select(
967
+ screening_candidates,
968
+ requested_slots=requested_slots,
969
+ llm_call=screener_llm_call,
970
+ max_fulltext_papers=fulltext_limit,
971
+ logger=logger,
972
+ )
973
+ screened_by_id = {
974
+ _text(paper.get("canonical_paper_id"), limit=200): paper for paper in screened_candidates
975
+ }
976
+ enriched = [
977
+ screened_by_id.get(_text(paper.get("canonical_paper_id"), limit=200), paper)
978
+ for paper in enriched
979
+ ]
980
+ screening_audit["screening_candidate_budget"] = self.max_screening_candidates
981
+ screening_audit["discovered_unique_paper_count"] = len(enriched) + len(omitted_candidates)
982
+ screening_audit["omitted_before_screening_count"] = len(omitted_candidates)
983
+ screening_audit["omitted_before_screening_paper_ids"] = [
984
+ _text(paper.get("canonical_paper_id"), limit=200) for paper in omitted_candidates
985
+ ]
986
+ screening_audit["pre_screen_selected_by_slot"] = pre_screen_selected_by_slot
987
+ selected_for_fulltext = set(screening_audit.get("selected_paper_ids") or [])
988
+ for index, paper in enumerate(enriched):
989
+ if _text(paper.get("fulltext"), limit=100):
990
+ continue
991
+ if _text(paper.get("canonical_paper_id"), limit=160) not in selected_for_fulltext:
992
+ continue
993
+ fetched = self._fetch_fulltext(paper, logger=logger, cache_run_id=cache_run_id)
994
+ if fetched:
995
+ enriched[index] = {**paper, **fetched}
996
+ for paper in enriched:
997
+ if _text(paper.get("fulltext"), limit=100):
998
+ paper["content_availability"] = "fulltext"
999
+ elif _text(paper.get("user_supplied_text"), limit=100):
1000
+ paper["content_availability"] = "user_supplied"
1001
+ elif _text(paper.get("abstract"), limit=100):
1002
+ paper["content_availability"] = "abstract"
1003
+ else:
1004
+ paper["content_availability"] = "metadata"
1005
+ collection = {
1006
+ "schema_version": SURVEY_EVIDENCE_COLLECTION_SCHEMA_VERSION,
1007
+ "collection_policy": "openalex_primary_semantic_scholar_fallback_only_when_openalex_unavailable",
1008
+ "provider_runs": provider_runs,
1009
+ "papers": enriched,
1010
+ "paper_count": len(enriched),
1011
+ "paper_screening": screening_audit,
1012
+ "fulltext_acquisition_by_paper": {
1013
+ _text(paper.get("canonical_paper_id"), limit=160): _mapping(paper.get("fulltext_acquisition"))
1014
+ for paper in enriched
1015
+ if _text(paper.get("canonical_paper_id"), limit=160)
1016
+ and _mapping(paper.get("fulltext_acquisition"))
1017
+ },
1018
+ }
1019
+ self.cache.write(
1020
+ "retrieval_collections",
1021
+ collection_cache_identity,
1022
+ collection,
1023
+ metadata={"paper_count": len(enriched)},
1024
+ run_id=cache_run_id,
1025
+ )
1026
+ return collection
1027
+
1028
+
1029
+ class SurveyEvidenceAdapter:
1030
+ """Turn per-slot collection records into a validated EvidenceBundle v1."""
1031
+
1032
+ def __init__(
1033
+ self,
1034
+ *,
1035
+ collector: SurveyEvidenceCollector | None = None,
1036
+ card_extractor: EvidenceCardExtractor | None = None,
1037
+ card_llm_call: Callable[[str], object] | None = None,
1038
+ screener_llm_call: Callable[..., object] | None = None,
1039
+ card_parallel_workers: int = DEFAULT_EVIDENCE_CARD_PARALLEL_WORKERS,
1040
+ cache: ExperimentDesignCache | None = None,
1041
+ cache_context: Mapping[str, Any] | None = None,
1042
+ ) -> None:
1043
+ self.collector = collector or SurveyEvidenceCollector()
1044
+ collector_cache = getattr(self.collector, "cache", None)
1045
+ self.cache = cache or collector_cache or ExperimentDesignCache({"enabled": False})
1046
+ self.cache_context = _mapping(cache_context) or _mapping(getattr(self.collector, "cache_context", {}))
1047
+ self.card_extractor = card_extractor or EvidenceCardExtractor()
1048
+ self.card_llm_call = card_llm_call
1049
+ self.screener_llm_call = screener_llm_call or card_llm_call
1050
+ self.card_parallel_workers = max(1, int(card_parallel_workers))
1051
+
1052
+ @classmethod
1053
+ def from_config(
1054
+ cls,
1055
+ *,
1056
+ card_llm_call: Callable[[str], object] | None = None,
1057
+ screener_llm_call: Callable[..., object] | None = None,
1058
+ config: object | None = None,
1059
+ ) -> "SurveyEvidenceAdapter":
1060
+ """Build a Survey-style evidence adapter using the active agent configuration."""
1061
+
1062
+ if config is None:
1063
+ from src.config import get_experiment_design_config
1064
+
1065
+ config = get_experiment_design_config()
1066
+ experiment_design_config = _setting(config, "experiment_design", config)
1067
+ retrieval = _setting(experiment_design_config, "retrieval", {})
1068
+ card_extraction = _setting(retrieval, "evidence_card_extraction", {})
1069
+ collector = SurveyEvidenceCollector.from_config(config)
1070
+
1071
+ return cls(
1072
+ collector=collector,
1073
+ card_llm_call=card_llm_call,
1074
+ screener_llm_call=screener_llm_call or card_llm_call,
1075
+ card_parallel_workers=max(
1076
+ 1,
1077
+ int(
1078
+ _setting(
1079
+ card_extraction,
1080
+ "parallel_workers",
1081
+ DEFAULT_EVIDENCE_CARD_PARALLEL_WORKERS,
1082
+ )
1083
+ or 1
1084
+ ),
1085
+ ),
1086
+ cache=collector.cache,
1087
+ cache_context=_llm_cache_context(config),
1088
+ )
1089
+
1090
+ def _extract_cards_for_paper(
1091
+ self,
1092
+ *,
1093
+ paper_index: int,
1094
+ paper: Mapping[str, Any],
1095
+ planned_slots: Sequence[str],
1096
+ logger: Any | None,
1097
+ cache_run_id: str,
1098
+ ) -> dict[str, Any]:
1099
+ paper_id = _text(paper.get("canonical_paper_id"), limit=160) or "<missing>"
1100
+ if _text(paper.get("fulltext"), limit=100):
1101
+ source_level = "fulltext"
1102
+ source_location = _text(paper.get("fulltext_source_location"), limit=300)
1103
+ elif _text(paper.get("user_supplied_text"), limit=100):
1104
+ source_level = "user_supplied"
1105
+ source_location = _text(paper.get("user_supplied_text_source_location"), limit=300)
1106
+ elif _text(paper.get("abstract"), limit=100):
1107
+ source_level = "abstract"
1108
+ source_location = _text(paper.get("abstract_source_location"), limit=300)
1109
+ else:
1110
+ source_level = "metadata"
1111
+ source_location = "metadata"
1112
+ source_text = (
1113
+ paper.get("fulltext")
1114
+ or paper.get("user_supplied_text")
1115
+ or paper.get("abstract")
1116
+ or ""
1117
+ )
1118
+ card_cache_identity = {
1119
+ "canonical_paper_id": paper_id,
1120
+ "source_level": source_level,
1121
+ "source_text_sha256": text_digest(source_text),
1122
+ "requested_slots": list(planned_slots),
1123
+ "card_prompt_sha256": text_digest(EVIDENCE_CARD_EXTRACTOR_PROMPT),
1124
+ "cache_context": self.cache_context,
1125
+ }
1126
+ if logger is not None:
1127
+ logger.event(
1128
+ "evidence_card_extraction",
1129
+ "started",
1130
+ status="RUNNING",
1131
+ canonical_paper_id=paper_id,
1132
+ evidence_level=source_level,
1133
+ source_location=source_location,
1134
+ requested_slot_count=len(planned_slots),
1135
+ parallel_workers=self.card_parallel_workers,
1136
+ )
1137
+ cached_cards = self.cache.read(
1138
+ "evidence_cards",
1139
+ card_cache_identity,
1140
+ run_id=cache_run_id,
1141
+ )
1142
+ if cached_cards is not None:
1143
+ extracted = list(cached_cards.get("cards") or [])
1144
+ extraction_warnings = _texts(cached_cards.get("warnings"), limit=1000)
1145
+ if logger is not None:
1146
+ logger.event(
1147
+ "evidence_card_extraction",
1148
+ "cache_hit",
1149
+ status="CACHED",
1150
+ canonical_paper_id=paper_id,
1151
+ card_count=len(extracted),
1152
+ parallel_workers=self.card_parallel_workers,
1153
+ )
1154
+ return {
1155
+ "paper_index": paper_index,
1156
+ "cards": extracted,
1157
+ "warnings": extraction_warnings,
1158
+ }
1159
+ if self.cache.offline:
1160
+ warning = f"evidence_card_cache_miss:{paper_id}:no_llm_call"
1161
+ if logger is not None:
1162
+ logger.event(
1163
+ "evidence_card_extraction",
1164
+ "cache_miss",
1165
+ level="WARNING",
1166
+ status="OFFLINE_DEGRADED",
1167
+ canonical_paper_id=paper_id,
1168
+ parallel_workers=self.card_parallel_workers,
1169
+ )
1170
+ return {"paper_index": paper_index, "cards": [], "warnings": [warning]}
1171
+ try:
1172
+ extracted, extraction_warnings = self.card_extractor.extract(
1173
+ paper,
1174
+ requested_slots=planned_slots,
1175
+ llm_call=self.card_llm_call,
1176
+ )
1177
+ except Exception as exc:
1178
+ if logger is not None:
1179
+ logger.exception(
1180
+ "evidence_card_extraction",
1181
+ exc,
1182
+ canonical_paper_id=paper_id,
1183
+ evidence_level=source_level,
1184
+ source_location=source_location,
1185
+ parallel_workers=self.card_parallel_workers,
1186
+ )
1187
+ return {
1188
+ "paper_index": paper_index,
1189
+ "error": exc,
1190
+ "failure": {
1191
+ "canonical_paper_id": paper_id,
1192
+ "status": "FAILED",
1193
+ "error_type": type(exc).__name__,
1194
+ "error": _text(str(exc), limit=1200),
1195
+ "evidence_level": source_level,
1196
+ "source_location": source_location,
1197
+ "continue_on_failure": True,
1198
+ },
1199
+ }
1200
+ if logger is not None:
1201
+ for warning in extraction_warnings:
1202
+ logger.event(
1203
+ "evidence_card_extraction",
1204
+ "card_rejected",
1205
+ level="WARNING",
1206
+ status="SKIPPED",
1207
+ canonical_paper_id=paper_id,
1208
+ warning=_text(warning, limit=1200),
1209
+ parallel_workers=self.card_parallel_workers,
1210
+ )
1211
+ for card in extracted:
1212
+ logger.event(
1213
+ "evidence_card_extraction",
1214
+ "validated",
1215
+ status="COMPLETED",
1216
+ canonical_paper_id=paper_id,
1217
+ card_id=_text(card.get("card_id"), limit=200),
1218
+ claim_slot=_text(card.get("claim_slot"), limit=120),
1219
+ source_id=_text(card.get("source_id"), limit=160),
1220
+ source_location=_text(card.get("source_location"), limit=300),
1221
+ evidence_level=_text(card.get("evidence_level"), limit=40),
1222
+ parallel_workers=self.card_parallel_workers,
1223
+ )
1224
+ logger.event(
1225
+ "evidence_card_extraction",
1226
+ "completed",
1227
+ status=(
1228
+ "COMPLETED_WITH_WARNINGS"
1229
+ if extracted and extraction_warnings
1230
+ else "COMPLETED"
1231
+ if extracted
1232
+ else "SKIPPED"
1233
+ ),
1234
+ canonical_paper_id=paper_id,
1235
+ evidence_level=source_level,
1236
+ source_location=source_location,
1237
+ card_count=len(extracted),
1238
+ warning_count=len(extraction_warnings),
1239
+ parallel_workers=self.card_parallel_workers,
1240
+ )
1241
+ self.cache.write(
1242
+ "evidence_cards",
1243
+ card_cache_identity,
1244
+ {"cards": extracted, "warnings": extraction_warnings},
1245
+ metadata={"canonical_paper_id": paper_id, "source_level": source_level},
1246
+ run_id=cache_run_id,
1247
+ )
1248
+ return {
1249
+ "paper_index": paper_index,
1250
+ "cards": extracted,
1251
+ "warnings": extraction_warnings,
1252
+ }
1253
+
1254
+ def collect_and_extract(
1255
+ self,
1256
+ *,
1257
+ brief_id: str,
1258
+ evidence_plan: Mapping[str, Any],
1259
+ survey_artifacts: Mapping[str, Any] | Sequence[Mapping[str, Any]] | None = None,
1260
+ max_results_per_query: int = 10,
1261
+ max_fulltext_papers: int = 15,
1262
+ logger: Any | None = None,
1263
+ cache_run_id: str = "",
1264
+ ) -> dict[str, Any]:
1265
+ cache_run_id = cache_run_id or self.cache.begin_run(brief_id)
1266
+ collection = self.collector.collect(
1267
+ evidence_plan,
1268
+ max_results_per_query=max_results_per_query,
1269
+ max_fulltext_papers=max_fulltext_papers,
1270
+ survey_artifacts=survey_artifacts,
1271
+ screener_llm_call=self.screener_llm_call,
1272
+ logger=logger,
1273
+ cache_run_id=cache_run_id,
1274
+ )
1275
+ planned_slots = _texts(
1276
+ [
1277
+ _mapping(task).get("slot")
1278
+ for task in _mapping(evidence_plan).get("queries") or []
1279
+ ],
1280
+ limit=32,
1281
+ )
1282
+ cards: list[dict[str, Any]] = []
1283
+ warnings: list[str] = []
1284
+ extraction_failures: list[dict[str, Any]] = []
1285
+ papers = list(collection["papers"])
1286
+ extraction_results: list[dict[str, Any] | None] = [None] * len(papers)
1287
+ if papers:
1288
+ worker_count = min(self.card_parallel_workers, len(papers))
1289
+ with ThreadPoolExecutor(max_workers=worker_count) as executor:
1290
+ futures = {
1291
+ executor.submit(
1292
+ self._extract_cards_for_paper,
1293
+ paper_index=paper_index,
1294
+ paper=paper,
1295
+ planned_slots=planned_slots,
1296
+ logger=logger,
1297
+ cache_run_id=cache_run_id,
1298
+ ): paper_index
1299
+ for paper_index, paper in enumerate(papers)
1300
+ }
1301
+ for future in as_completed(futures):
1302
+ result = future.result()
1303
+ extraction_results[result["paper_index"]] = result
1304
+
1305
+ for result in extraction_results:
1306
+ if result is None:
1307
+ continue
1308
+ error = result.get("error")
1309
+ if isinstance(error, Exception):
1310
+ failure = _mapping(result.get("failure"))
1311
+ if failure:
1312
+ extraction_failures.append(failure)
1313
+ warnings.append(
1314
+ "evidence_card_extraction_failed:"
1315
+ f"{_text(failure.get('canonical_paper_id'), limit=160)}:"
1316
+ f"{_text(failure.get('error_type'), limit=80)}"
1317
+ )
1318
+ continue
1319
+ cards.extend(result.get("cards") or [])
1320
+ warnings.extend(_texts(result.get("warnings"), limit=1000))
1321
+ retrieval_audit = {
1322
+ "collection_policy": collection["collection_policy"],
1323
+ "provider_runs": collection["provider_runs"],
1324
+ "paper_screening": collection.get("paper_screening", {}),
1325
+ "fulltext_acquisition_by_paper": collection.get("fulltext_acquisition_by_paper", {}),
1326
+ "card_extraction_warnings": warnings,
1327
+ "card_extraction_failures": extraction_failures,
1328
+ "failed_card_extraction_paper_count": len(extraction_failures),
1329
+ "failed_card_extraction_paper_ids": [
1330
+ _text(failure.get("canonical_paper_id"), limit=160)
1331
+ for failure in extraction_failures
1332
+ ],
1333
+ }
1334
+ if logger is not None:
1335
+ logger.event(
1336
+ "evidence_bundle",
1337
+ "started",
1338
+ status="RUNNING",
1339
+ brief_id=brief_id,
1340
+ paper_count=len(collection["papers"]),
1341
+ evidence_card_count=len(cards),
1342
+ planned_slot_count=len(planned_slots),
1343
+ )
1344
+ try:
1345
+ bundle = build_traceable_evidence_bundle(
1346
+ brief_id=brief_id,
1347
+ planned_slots=planned_slots,
1348
+ papers=collection["papers"],
1349
+ evidence_cards=cards,
1350
+ retrieval_audit=retrieval_audit,
1351
+ )
1352
+ except Exception as exc:
1353
+ if logger is not None:
1354
+ logger.exception(
1355
+ "evidence_bundle",
1356
+ exc,
1357
+ brief_id=brief_id,
1358
+ paper_count=len(collection["papers"]),
1359
+ evidence_card_count=len(cards),
1360
+ )
1361
+ raise
1362
+ if logger is not None:
1363
+ coverage = _mapping(bundle.get("coverage"))
1364
+ logger.event(
1365
+ "evidence_bundle",
1366
+ "completed",
1367
+ status="COMPLETED",
1368
+ brief_id=brief_id,
1369
+ paper_count=len(bundle.get("paper_registry") or []),
1370
+ evidence_card_count=len(bundle.get("evidence_cards") or []),
1371
+ required_slot_count=len(coverage.get("required_slots") or []),
1372
+ covered_slot_count=len(coverage.get("covered_slots") or []),
1373
+ uncovered_slot_count=len(coverage.get("uncovered_slots") or []),
1374
+ )
1375
+ return {
1376
+ "schema_version": SURVEY_EVIDENCE_ADAPTATION_SCHEMA_VERSION,
1377
+ "collection": collection,
1378
+ "evidence_bundle": bundle,
1379
+ "warnings": warnings,
1380
+ "cache_manifest": self.cache.run_manifest(cache_run_id),
1381
+ }