briefloop 0.11.12__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 (424) hide show
  1. briefloop-0.11.12.dist-info/METADATA +473 -0
  2. briefloop-0.11.12.dist-info/RECORD +424 -0
  3. briefloop-0.11.12.dist-info/WHEEL +5 -0
  4. briefloop-0.11.12.dist-info/entry_points.txt +3 -0
  5. briefloop-0.11.12.dist-info/licenses/LICENSE +22 -0
  6. briefloop-0.11.12.dist-info/top_level.txt +1 -0
  7. multi_agent_brief/__init__.py +36 -0
  8. multi_agent_brief/analysis_blocks/__init__.py +11 -0
  9. multi_agent_brief/analysis_blocks/builder.py +206 -0
  10. multi_agent_brief/analysis_blocks/renderer.py +237 -0
  11. multi_agent_brief/analysis_blocks/schemas.py +52 -0
  12. multi_agent_brief/analysis_modules/__init__.py +8 -0
  13. multi_agent_brief/analysis_modules/base.py +87 -0
  14. multi_agent_brief/analysis_modules/market_competitor/__init__.py +68 -0
  15. multi_agent_brief/analysis_modules/market_competitor/auditor.py +290 -0
  16. multi_agent_brief/analysis_modules/market_competitor/config.py +187 -0
  17. multi_agent_brief/analysis_modules/market_competitor/event_builder.py +226 -0
  18. multi_agent_brief/analysis_modules/market_competitor/renderer.py +199 -0
  19. multi_agent_brief/analysis_modules/market_competitor/schemas.py +518 -0
  20. multi_agent_brief/analysis_modules/policy_regulatory/__init__.py +7 -0
  21. multi_agent_brief/analysis_modules/policy_regulatory/audit.py +195 -0
  22. multi_agent_brief/analysis_modules/policy_regulatory/module.py +387 -0
  23. multi_agent_brief/analysis_modules/policy_regulatory/schemas.py +129 -0
  24. multi_agent_brief/analysis_modules/registry.py +73 -0
  25. multi_agent_brief/audience/__init__.py +19 -0
  26. multi_agent_brief/audience/profiles.py +246 -0
  27. multi_agent_brief/audience_memory/__init__.py +23 -0
  28. multi_agent_brief/audience_memory/profile.py +358 -0
  29. multi_agent_brief/audit/__init__.py +36 -0
  30. multi_agent_brief/audit/case_applicability.py +181 -0
  31. multi_agent_brief/audit/deterministic.py +471 -0
  32. multi_agent_brief/audit/editorial_governance.py +404 -0
  33. multi_agent_brief/audit/final_quality.py +764 -0
  34. multi_agent_brief/audit/harness.py +242 -0
  35. multi_agent_brief/audit/interfaces.py +96 -0
  36. multi_agent_brief/audit/limitation_hygiene.py +238 -0
  37. multi_agent_brief/audit/proposal_boundary.py +34 -0
  38. multi_agent_brief/audit/redaction.py +27 -0
  39. multi_agent_brief/audit/rule_packs.py +96 -0
  40. multi_agent_brief/audit/semantic.py +435 -0
  41. multi_agent_brief/capabilities/__init__.py +22 -0
  42. multi_agent_brief/capabilities/catalog.py +215 -0
  43. multi_agent_brief/capabilities/detect.py +199 -0
  44. multi_agent_brief/capabilities/models.py +60 -0
  45. multi_agent_brief/capabilities/recommend.py +206 -0
  46. multi_agent_brief/cli/__init__.py +2 -0
  47. multi_agent_brief/cli/analysis_commands.py +140 -0
  48. multi_agent_brief/cli/approval_commands.py +107 -0
  49. multi_agent_brief/cli/audit_commands.py +59 -0
  50. multi_agent_brief/cli/capability_commands.py +548 -0
  51. multi_agent_brief/cli/claude_commands.py +159 -0
  52. multi_agent_brief/cli/competitors_commands.py +182 -0
  53. multi_agent_brief/cli/controls_commands.py +137 -0
  54. multi_agent_brief/cli/deliver_commands.py +942 -0
  55. multi_agent_brief/cli/eval_cases_commands.py +99 -0
  56. multi_agent_brief/cli/experiments_commands.py +395 -0
  57. multi_agent_brief/cli/feedback_commands.py +192 -0
  58. multi_agent_brief/cli/finalize_commands.py +153 -0
  59. multi_agent_brief/cli/gates_commands.py +174 -0
  60. multi_agent_brief/cli/hermes_commands.py +356 -0
  61. multi_agent_brief/cli/improve_commands.py +224 -0
  62. multi_agent_brief/cli/init_commands.py +564 -0
  63. multi_agent_brief/cli/init_wizard.py +1473 -0
  64. multi_agent_brief/cli/input_commands.py +237 -0
  65. multi_agent_brief/cli/main.py +288 -0
  66. multi_agent_brief/cli/onboard_commands.py +193 -0
  67. multi_agent_brief/cli/product_commands.py +1449 -0
  68. multi_agent_brief/cli/provenance_commands.py +100 -0
  69. multi_agent_brief/cli/release_commands.py +68 -0
  70. multi_agent_brief/cli/repair_commands.py +169 -0
  71. multi_agent_brief/cli/run_commands.py +292 -0
  72. multi_agent_brief/cli/runtime_commands.py +81 -0
  73. multi_agent_brief/cli/secrets_commands.py +232 -0
  74. multi_agent_brief/cli/semantic_support_commands.py +80 -0
  75. multi_agent_brief/cli/sources_commands.py +647 -0
  76. multi_agent_brief/cli/start_commands.py +8 -0
  77. multi_agent_brief/cli/state_commands.py +446 -0
  78. multi_agent_brief/cli/status_commands.py +26 -0
  79. multi_agent_brief/cli/workbuddy_commands.py +103 -0
  80. multi_agent_brief/configs/artifact_contracts.yaml +514 -0
  81. multi_agent_brief/configs/orchestrator_contract.yaml +181 -0
  82. multi_agent_brief/configs/policy_packs/default.yaml +65 -0
  83. multi_agent_brief/configs/policy_profiles/evidence_extract_default.yaml +58 -0
  84. multi_agent_brief/configs/policy_profiles/finance_default.yaml +44 -0
  85. multi_agent_brief/configs/policy_profiles/internet_default.yaml +44 -0
  86. multi_agent_brief/configs/policy_profiles/manufacturing_default.yaml +33 -0
  87. multi_agent_brief/configs/policy_profiles/solar_manufacturing_default.yaml +64 -0
  88. multi_agent_brief/configs/report_packs/evidence_extract.yaml +48 -0
  89. multi_agent_brief/configs/report_packs/management_monthly.yaml +36 -0
  90. multi_agent_brief/configs/report_packs/market_weekly.yaml +36 -0
  91. multi_agent_brief/configs/report_packs/solar_industry_periodic.yaml +50 -0
  92. multi_agent_brief/configs/report_templates/evidence_extract.yaml +55 -0
  93. multi_agent_brief/configs/report_templates/management_monthly.yaml +48 -0
  94. multi_agent_brief/configs/report_templates/market_weekly.yaml +49 -0
  95. multi_agent_brief/configs/report_templates/solar_industry_periodic.yaml +75 -0
  96. multi_agent_brief/configs/stage_specs.yaml +180 -0
  97. multi_agent_brief/contracts/__init__.py +41 -0
  98. multi_agent_brief/contracts/base.py +99 -0
  99. multi_agent_brief/contracts/errors.py +41 -0
  100. multi_agent_brief/contracts/migrations/__init__.py +5 -0
  101. multi_agent_brief/contracts/migrations/claim_v1_to_v2.py +33 -0
  102. multi_agent_brief/contracts/registry.py +159 -0
  103. multi_agent_brief/contracts/role_topology.py +25 -0
  104. multi_agent_brief/contracts/schemas/__init__.py +35 -0
  105. multi_agent_brief/contracts/schemas/analysis_pack.py +135 -0
  106. multi_agent_brief/contracts/schemas/atomic_claim_graph.py +304 -0
  107. multi_agent_brief/contracts/schemas/audit_report.py +80 -0
  108. multi_agent_brief/contracts/schemas/candidate_item.py +51 -0
  109. multi_agent_brief/contracts/schemas/claim.py +197 -0
  110. multi_agent_brief/contracts/schemas/claim_draft.py +386 -0
  111. multi_agent_brief/contracts/schemas/claim_support_matrix.py +334 -0
  112. multi_agent_brief/contracts/schemas/evidence_span_registry.py +270 -0
  113. multi_agent_brief/contracts/schemas/policy_profile.py +247 -0
  114. multi_agent_brief/contracts/schemas/report_spec.py +257 -0
  115. multi_agent_brief/contracts/schemas/semantic_assessment_report.py +480 -0
  116. multi_agent_brief/contracts/schemas/source_evidence_pack_manifest.py +233 -0
  117. multi_agent_brief/contracts/schemas/source_item.py +96 -0
  118. multi_agent_brief/contracts/semantic_assessment_status.py +12 -0
  119. multi_agent_brief/contracts/source_metadata.py +252 -0
  120. multi_agent_brief/contracts/target_contract.py +460 -0
  121. multi_agent_brief/contracts/validator.py +225 -0
  122. multi_agent_brief/controls/__init__.py +23 -0
  123. multi_agent_brief/controls/contract.py +106 -0
  124. multi_agent_brief/controls/switchboard.py +1076 -0
  125. multi_agent_brief/core/__init__.py +2 -0
  126. multi_agent_brief/core/citations.py +14 -0
  127. multi_agent_brief/core/claim_ledger.py +94 -0
  128. multi_agent_brief/core/config.py +191 -0
  129. multi_agent_brief/core/env.py +69 -0
  130. multi_agent_brief/core/previous.py +83 -0
  131. multi_agent_brief/core/schemas.py +181 -0
  132. multi_agent_brief/core/selection.py +189 -0
  133. multi_agent_brief/delivery/__init__.py +6 -0
  134. multi_agent_brief/delivery/base.py +36 -0
  135. multi_agent_brief/delivery/feishu.py +204 -0
  136. multi_agent_brief/delivery/gws.py +237 -0
  137. multi_agent_brief/evaluation_cases/__init__.py +15 -0
  138. multi_agent_brief/evaluation_cases/contract.py +429 -0
  139. multi_agent_brief/evaluation_cases/fixtures/cases/approved_guidance_materialized/workspace/config.yaml +18 -0
  140. multi_agent_brief/evaluation_cases/fixtures/cases/approved_guidance_materialized/workspace/improvement/ledger.jsonl +2 -0
  141. multi_agent_brief/evaluation_cases/fixtures/cases/approved_guidance_materialized/workspace/sources.yaml +2 -0
  142. multi_agent_brief/evaluation_cases/fixtures/cases/approved_guidance_materialized/workspace/user.md +4 -0
  143. multi_agent_brief/evaluation_cases/fixtures/cases/company_event_missing_latest_official_check/workspace/config.yaml +13 -0
  144. multi_agent_brief/evaluation_cases/fixtures/cases/company_event_missing_latest_official_check/workspace/sources.yaml +9 -0
  145. multi_agent_brief/evaluation_cases/fixtures/cases/company_event_missing_latest_official_check/workspace/user.md +4 -0
  146. multi_agent_brief/evaluation_cases/fixtures/cases/control_switchboard_selection_is_not_execution/workspace/config.yaml +12 -0
  147. multi_agent_brief/evaluation_cases/fixtures/cases/control_switchboard_selection_is_not_execution/workspace/sources.yaml +6 -0
  148. multi_agent_brief/evaluation_cases/fixtures/cases/control_switchboard_selection_is_not_execution/workspace/user.md +4 -0
  149. multi_agent_brief/evaluation_cases/fixtures/cases/feedback_triage_required/workspace/config.yaml +6 -0
  150. multi_agent_brief/evaluation_cases/fixtures/cases/feedback_triage_required/workspace/input/human_feedback.md +1 -0
  151. multi_agent_brief/evaluation_cases/fixtures/cases/feedback_triage_required/workspace/sources.yaml +2 -0
  152. multi_agent_brief/evaluation_cases/fixtures/cases/feedback_triage_required/workspace/user.md +3 -0
  153. multi_agent_brief/evaluation_cases/fixtures/cases/final_abstract_quality_warning_surface/workspace/config.yaml +8 -0
  154. multi_agent_brief/evaluation_cases/fixtures/cases/final_abstract_quality_warning_surface/workspace/output/brief.md +14 -0
  155. multi_agent_brief/evaluation_cases/fixtures/cases/final_abstract_quality_warning_surface/workspace/output/intermediate/audit_report.json +1 -0
  156. multi_agent_brief/evaluation_cases/fixtures/cases/final_abstract_quality_warning_surface/workspace/output/intermediate/audited_brief.md +5 -0
  157. multi_agent_brief/evaluation_cases/fixtures/cases/final_abstract_quality_warning_surface/workspace/output/intermediate/candidate_claims.json +1 -0
  158. multi_agent_brief/evaluation_cases/fixtures/cases/final_abstract_quality_warning_surface/workspace/output/intermediate/claim_ledger.json +1 -0
  159. multi_agent_brief/evaluation_cases/fixtures/cases/final_abstract_quality_warning_surface/workspace/output/intermediate/screened_candidates.json +1 -0
  160. multi_agent_brief/evaluation_cases/fixtures/cases/final_abstract_quality_warning_surface/workspace/sources.yaml +2 -0
  161. multi_agent_brief/evaluation_cases/fixtures/cases/final_abstract_quality_warning_surface/workspace/user.md +3 -0
  162. multi_agent_brief/evaluation_cases/fixtures/cases/formal_release_missing_human_approval/workspace/config.yaml +13 -0
  163. multi_agent_brief/evaluation_cases/fixtures/cases/formal_release_missing_human_approval/workspace/sources.yaml +9 -0
  164. multi_agent_brief/evaluation_cases/fixtures/cases/formal_release_missing_human_approval/workspace/user.md +4 -0
  165. multi_agent_brief/evaluation_cases/fixtures/cases/guidance_manifestation_not_observable/workspace/config.yaml +4 -0
  166. multi_agent_brief/evaluation_cases/fixtures/cases/guidance_manifestation_not_observable/workspace/sources.yaml +2 -0
  167. multi_agent_brief/evaluation_cases/fixtures/cases/guidance_manifestation_not_observable/workspace/user.md +3 -0
  168. multi_agent_brief/evaluation_cases/fixtures/cases/media_only_legal_policy_blocks_research_review/workspace/config.yaml +13 -0
  169. multi_agent_brief/evaluation_cases/fixtures/cases/media_only_legal_policy_blocks_research_review/workspace/sources.yaml +9 -0
  170. multi_agent_brief/evaluation_cases/fixtures/cases/media_only_legal_policy_blocks_research_review/workspace/user.md +4 -0
  171. multi_agent_brief/evaluation_cases/fixtures/cases/mixed_metric_scope_support_blocker/workspace/config.yaml +13 -0
  172. multi_agent_brief/evaluation_cases/fixtures/cases/mixed_metric_scope_support_blocker/workspace/sources.yaml +9 -0
  173. multi_agent_brief/evaluation_cases/fixtures/cases/mixed_metric_scope_support_blocker/workspace/user.md +5 -0
  174. multi_agent_brief/evaluation_cases/fixtures/cases/planned_blocking_issue_cannot_continue/workspace/config.yaml +6 -0
  175. multi_agent_brief/evaluation_cases/fixtures/cases/planned_blocking_issue_cannot_continue/workspace/output/intermediate/audited_brief.md +3 -0
  176. multi_agent_brief/evaluation_cases/fixtures/cases/planned_blocking_issue_cannot_continue/workspace/output/intermediate/candidate_claims.json +1 -0
  177. multi_agent_brief/evaluation_cases/fixtures/cases/planned_blocking_issue_cannot_continue/workspace/output/intermediate/claim_ledger.json +1 -0
  178. multi_agent_brief/evaluation_cases/fixtures/cases/planned_blocking_issue_cannot_continue/workspace/output/intermediate/feedback_issues.json +25 -0
  179. multi_agent_brief/evaluation_cases/fixtures/cases/planned_blocking_issue_cannot_continue/workspace/output/intermediate/repair_plan.json +27 -0
  180. multi_agent_brief/evaluation_cases/fixtures/cases/planned_blocking_issue_cannot_continue/workspace/output/intermediate/screened_candidates.json +1 -0
  181. multi_agent_brief/evaluation_cases/fixtures/cases/planned_blocking_issue_cannot_continue/workspace/sources.yaml +2 -0
  182. multi_agent_brief/evaluation_cases/fixtures/cases/planned_blocking_issue_cannot_continue/workspace/user.md +3 -0
  183. multi_agent_brief/evaluation_cases/fixtures/cases/provenance_projection_minimal/workspace/config.yaml +8 -0
  184. multi_agent_brief/evaluation_cases/fixtures/cases/provenance_projection_minimal/workspace/output/intermediate/audit_report.json +1 -0
  185. multi_agent_brief/evaluation_cases/fixtures/cases/provenance_projection_minimal/workspace/output/intermediate/audited_brief.md +3 -0
  186. multi_agent_brief/evaluation_cases/fixtures/cases/provenance_projection_minimal/workspace/output/intermediate/candidate_claims.json +1 -0
  187. multi_agent_brief/evaluation_cases/fixtures/cases/provenance_projection_minimal/workspace/output/intermediate/claim_ledger.json +11 -0
  188. multi_agent_brief/evaluation_cases/fixtures/cases/provenance_projection_minimal/workspace/output/intermediate/quality_gate_report.json +22 -0
  189. multi_agent_brief/evaluation_cases/fixtures/cases/provenance_projection_minimal/workspace/output/intermediate/screened_candidates.json +1 -0
  190. multi_agent_brief/evaluation_cases/fixtures/cases/provenance_projection_minimal/workspace/sources.yaml +2 -0
  191. multi_agent_brief/evaluation_cases/fixtures/cases/provenance_projection_minimal/workspace/user.md +3 -0
  192. multi_agent_brief/evaluation_cases/fixtures/cases/reader_facing_source_appendix/workspace/config.yaml +13 -0
  193. multi_agent_brief/evaluation_cases/fixtures/cases/reader_facing_source_appendix/workspace/output/intermediate/audit_report.json +1 -0
  194. multi_agent_brief/evaluation_cases/fixtures/cases/reader_facing_source_appendix/workspace/output/intermediate/audited_brief.md +5 -0
  195. multi_agent_brief/evaluation_cases/fixtures/cases/reader_facing_source_appendix/workspace/output/intermediate/candidate_claims.json +1 -0
  196. multi_agent_brief/evaluation_cases/fixtures/cases/reader_facing_source_appendix/workspace/output/intermediate/claim_ledger.json +40 -0
  197. multi_agent_brief/evaluation_cases/fixtures/cases/reader_facing_source_appendix/workspace/output/intermediate/screened_candidates.json +1 -0
  198. multi_agent_brief/evaluation_cases/fixtures/cases/reader_facing_source_appendix/workspace/sources.yaml +3 -0
  199. multi_agent_brief/evaluation_cases/fixtures/cases/reader_facing_source_appendix/workspace/user.md +3 -0
  200. multi_agent_brief/evaluation_cases/fixtures/cases/reader_facing_target_relevance/workspace/config.yaml +8 -0
  201. multi_agent_brief/evaluation_cases/fixtures/cases/reader_facing_target_relevance/workspace/output/brief.md +3 -0
  202. multi_agent_brief/evaluation_cases/fixtures/cases/reader_facing_target_relevance/workspace/output/intermediate/audit_report.json +1 -0
  203. multi_agent_brief/evaluation_cases/fixtures/cases/reader_facing_target_relevance/workspace/output/intermediate/audited_brief.md +3 -0
  204. multi_agent_brief/evaluation_cases/fixtures/cases/reader_facing_target_relevance/workspace/output/intermediate/candidate_claims.json +1 -0
  205. multi_agent_brief/evaluation_cases/fixtures/cases/reader_facing_target_relevance/workspace/output/intermediate/claim_ledger.json +13 -0
  206. multi_agent_brief/evaluation_cases/fixtures/cases/reader_facing_target_relevance/workspace/output/intermediate/screened_candidates.json +1 -0
  207. multi_agent_brief/evaluation_cases/fixtures/cases/reader_facing_target_relevance/workspace/sources.yaml +2 -0
  208. multi_agent_brief/evaluation_cases/fixtures/cases/reader_facing_target_relevance/workspace/user.md +3 -0
  209. multi_agent_brief/evaluation_cases/fixtures/cases/release_readiness_forged_event_blocker/workspace/config.yaml +13 -0
  210. multi_agent_brief/evaluation_cases/fixtures/cases/release_readiness_forged_event_blocker/workspace/output/intermediate/release_readiness_report.json +31 -0
  211. multi_agent_brief/evaluation_cases/fixtures/cases/release_readiness_forged_event_blocker/workspace/sources.yaml +9 -0
  212. multi_agent_brief/evaluation_cases/fixtures/cases/release_readiness_forged_event_blocker/workspace/user.md +4 -0
  213. multi_agent_brief/evaluation_cases/fixtures/cases/reverted_entry_removed_from_next_snapshot/workspace/config.yaml +18 -0
  214. multi_agent_brief/evaluation_cases/fixtures/cases/reverted_entry_removed_from_next_snapshot/workspace/improvement/ledger.jsonl +3 -0
  215. multi_agent_brief/evaluation_cases/fixtures/cases/reverted_entry_removed_from_next_snapshot/workspace/improvement/memory.md +3 -0
  216. multi_agent_brief/evaluation_cases/fixtures/cases/reverted_entry_removed_from_next_snapshot/workspace/output/intermediate/improvement_memory_snapshot.md +3 -0
  217. multi_agent_brief/evaluation_cases/fixtures/cases/reverted_entry_removed_from_next_snapshot/workspace/sources.yaml +2 -0
  218. multi_agent_brief/evaluation_cases/fixtures/cases/reverted_entry_removed_from_next_snapshot/workspace/user.md +4 -0
  219. multi_agent_brief/evaluation_cases/fixtures/cases/same_evidence_reader_quality_regression/workspace/config.yaml +12 -0
  220. multi_agent_brief/evaluation_cases/fixtures/cases/same_evidence_reader_quality_regression/workspace/input/sources/source-001.txt +1 -0
  221. multi_agent_brief/evaluation_cases/fixtures/cases/same_evidence_reader_quality_regression/workspace/output/brief.md +37 -0
  222. multi_agent_brief/evaluation_cases/fixtures/cases/same_evidence_reader_quality_regression/workspace/output/delivery/brief.md +37 -0
  223. multi_agent_brief/evaluation_cases/fixtures/cases/same_evidence_reader_quality_regression/workspace/output/intermediate/atomic_claim_graph.json +17 -0
  224. multi_agent_brief/evaluation_cases/fixtures/cases/same_evidence_reader_quality_regression/workspace/output/intermediate/audit_report.json +5 -0
  225. multi_agent_brief/evaluation_cases/fixtures/cases/same_evidence_reader_quality_regression/workspace/output/intermediate/audited_brief.md +37 -0
  226. multi_agent_brief/evaluation_cases/fixtures/cases/same_evidence_reader_quality_regression/workspace/output/intermediate/claim_ledger.json +20 -0
  227. multi_agent_brief/evaluation_cases/fixtures/cases/same_evidence_reader_quality_regression/workspace/output/intermediate/evidence_span_registry.json +20 -0
  228. multi_agent_brief/evaluation_cases/fixtures/cases/same_evidence_reader_quality_regression/workspace/output/intermediate/finalize_report.json +40 -0
  229. multi_agent_brief/evaluation_cases/fixtures/cases/same_evidence_reader_quality_regression/workspace/output/intermediate/gates/auditor_quality_gate_report.json +42 -0
  230. multi_agent_brief/evaluation_cases/fixtures/cases/same_evidence_reader_quality_regression/workspace/output/intermediate/gates/finalize_quality_gate_report.json +42 -0
  231. multi_agent_brief/evaluation_cases/fixtures/cases/same_evidence_reader_quality_regression/workspace/output/intermediate/screened_candidates.json +33 -0
  232. multi_agent_brief/evaluation_cases/fixtures/cases/same_evidence_reader_quality_regression/workspace/output/source_appendix.md +12 -0
  233. multi_agent_brief/evaluation_cases/fixtures/cases/same_evidence_reader_quality_regression/workspace/output/source_appendix_trace.md +10 -0
  234. multi_agent_brief/evaluation_cases/fixtures/cases/same_evidence_reader_quality_regression/workspace/report_spec.yaml +24 -0
  235. multi_agent_brief/evaluation_cases/fixtures/cases/same_evidence_reader_quality_regression/workspace/sources.yaml +4 -0
  236. multi_agent_brief/evaluation_cases/fixtures/cases/same_evidence_reader_quality_regression/workspace/user.md +3 -0
  237. multi_agent_brief/evaluation_cases/fixtures/cases/source_evidence_pack_blocks_non_evidence_file/workspace/config.yaml +13 -0
  238. multi_agent_brief/evaluation_cases/fixtures/cases/source_evidence_pack_blocks_non_evidence_file/workspace/input/sources/README.md +4 -0
  239. multi_agent_brief/evaluation_cases/fixtures/cases/source_evidence_pack_blocks_non_evidence_file/workspace/output/intermediate/source_evidence_pack_manifest.json +26 -0
  240. multi_agent_brief/evaluation_cases/fixtures/cases/source_evidence_pack_blocks_non_evidence_file/workspace/sources.yaml +9 -0
  241. multi_agent_brief/evaluation_cases/fixtures/cases/source_evidence_pack_blocks_non_evidence_file/workspace/user.md +4 -0
  242. multi_agent_brief/evaluation_cases/fixtures/cases/stale_current_claim/workspace/config.yaml +9 -0
  243. multi_agent_brief/evaluation_cases/fixtures/cases/stale_current_claim/workspace/output/intermediate/audit_report.json +1 -0
  244. multi_agent_brief/evaluation_cases/fixtures/cases/stale_current_claim/workspace/output/intermediate/audited_brief.md +3 -0
  245. multi_agent_brief/evaluation_cases/fixtures/cases/stale_current_claim/workspace/output/intermediate/candidate_claims.json +1 -0
  246. multi_agent_brief/evaluation_cases/fixtures/cases/stale_current_claim/workspace/output/intermediate/claim_ledger.json +13 -0
  247. multi_agent_brief/evaluation_cases/fixtures/cases/stale_current_claim/workspace/output/intermediate/screened_candidates.json +1 -0
  248. multi_agent_brief/evaluation_cases/fixtures/cases/stale_current_claim/workspace/sources.yaml +2 -0
  249. multi_agent_brief/evaluation_cases/fixtures/cases/stale_current_claim/workspace/user.md +3 -0
  250. multi_agent_brief/evaluation_cases/fixtures/cases/third_party_price_snapshot_formal_block/workspace/config.yaml +13 -0
  251. multi_agent_brief/evaluation_cases/fixtures/cases/third_party_price_snapshot_formal_block/workspace/sources.yaml +9 -0
  252. multi_agent_brief/evaluation_cases/fixtures/cases/third_party_price_snapshot_formal_block/workspace/user.md +4 -0
  253. multi_agent_brief/evaluation_cases/fixtures/cases/trajectory_retry_budget_exhausted/workspace/config.yaml +4 -0
  254. multi_agent_brief/evaluation_cases/fixtures/cases/trajectory_retry_budget_exhausted/workspace/sources.yaml +2 -0
  255. multi_agent_brief/evaluation_cases/fixtures/cases/trajectory_retry_budget_exhausted/workspace/user.md +3 -0
  256. multi_agent_brief/evaluation_cases/fixtures/cases/unapproved_entry_not_materialized/workspace/config.yaml +18 -0
  257. multi_agent_brief/evaluation_cases/fixtures/cases/unapproved_entry_not_materialized/workspace/improvement/ledger.jsonl +1 -0
  258. multi_agent_brief/evaluation_cases/fixtures/cases/unapproved_entry_not_materialized/workspace/sources.yaml +2 -0
  259. multi_agent_brief/evaluation_cases/fixtures/cases/unapproved_entry_not_materialized/workspace/user.md +4 -0
  260. multi_agent_brief/evaluation_cases/fixtures/cases/unauthorized_institution_branding_blocks_release/workspace/config.yaml +18 -0
  261. multi_agent_brief/evaluation_cases/fixtures/cases/unauthorized_institution_branding_blocks_release/workspace/sources.yaml +9 -0
  262. multi_agent_brief/evaluation_cases/fixtures/cases/unauthorized_institution_branding_blocks_release/workspace/user.md +5 -0
  263. multi_agent_brief/evaluation_cases/fixtures/cases/unsupported_material_fact/workspace/config.yaml +8 -0
  264. multi_agent_brief/evaluation_cases/fixtures/cases/unsupported_material_fact/workspace/output/intermediate/audit_report.json +1 -0
  265. multi_agent_brief/evaluation_cases/fixtures/cases/unsupported_material_fact/workspace/output/intermediate/audited_brief.md +8 -0
  266. multi_agent_brief/evaluation_cases/fixtures/cases/unsupported_material_fact/workspace/output/intermediate/candidate_claims.json +1 -0
  267. multi_agent_brief/evaluation_cases/fixtures/cases/unsupported_material_fact/workspace/output/intermediate/claim_ledger.json +1 -0
  268. multi_agent_brief/evaluation_cases/fixtures/cases/unsupported_material_fact/workspace/output/intermediate/screened_candidates.json +1 -0
  269. multi_agent_brief/evaluation_cases/fixtures/cases/unsupported_material_fact/workspace/sources.yaml +2 -0
  270. multi_agent_brief/evaluation_cases/fixtures/cases/unsupported_material_fact/workspace/user.md +3 -0
  271. multi_agent_brief/evaluation_cases/fixtures/manifest.yaml +861 -0
  272. multi_agent_brief/evaluation_cases/fixtures.py +20 -0
  273. multi_agent_brief/evaluation_cases/runner.py +1603 -0
  274. multi_agent_brief/experiments/__init__.py +45 -0
  275. multi_agent_brief/experiments/experiment_080.py +5835 -0
  276. multi_agent_brief/experiments/schemas.py +63 -0
  277. multi_agent_brief/experiments/target_contract.py +10 -0
  278. multi_agent_brief/feedback/__init__.py +17 -0
  279. multi_agent_brief/feedback/feedback_contract.py +482 -0
  280. multi_agent_brief/feedback/feedback_state.py +898 -0
  281. multi_agent_brief/hermes/__init__.py +25 -0
  282. multi_agent_brief/hermes/adapter.py +832 -0
  283. multi_agent_brief/improvement/__init__.py +83 -0
  284. multi_agent_brief/improvement/contract.py +1114 -0
  285. multi_agent_brief/improvement/memory.py +451 -0
  286. multi_agent_brief/improvement/product_definition.py +228 -0
  287. multi_agent_brief/improvement/state.py +961 -0
  288. multi_agent_brief/inputs/__init__.py +2 -0
  289. multi_agent_brief/inputs/classifier.py +322 -0
  290. multi_agent_brief/inputs/contracts.py +59 -0
  291. multi_agent_brief/inputs/extractor.py +310 -0
  292. multi_agent_brief/install/__init__.py +2 -0
  293. multi_agent_brief/install/writer.py +97 -0
  294. multi_agent_brief/onboarding/__init__.py +11 -0
  295. multi_agent_brief/onboarding/io.py +103 -0
  296. multi_agent_brief/onboarding/mapper.py +484 -0
  297. multi_agent_brief/onboarding/schema.py +46 -0
  298. multi_agent_brief/orchestrator/__init__.py +2 -0
  299. multi_agent_brief/orchestrator/fact_layer_import.py +352 -0
  300. multi_agent_brief/orchestrator/handoff.py +2209 -0
  301. multi_agent_brief/orchestrator/role_topology.py +42 -0
  302. multi_agent_brief/orchestrator/run_archive.py +888 -0
  303. multi_agent_brief/orchestrator/run_integrity.py +346 -0
  304. multi_agent_brief/orchestrator/runtime_state/__init__.py +70 -0
  305. multi_agent_brief/orchestrator/runtime_state/_io.py +167 -0
  306. multi_agent_brief/orchestrator/runtime_state/_transactions.py +298 -0
  307. multi_agent_brief/orchestrator/runtime_state/artifact_registry.py +1825 -0
  308. multi_agent_brief/orchestrator/runtime_state/atomic_claim_graph.py +96 -0
  309. multi_agent_brief/orchestrator/runtime_state/claim_ledger_freeze.py +510 -0
  310. multi_agent_brief/orchestrator/runtime_state/claim_metadata_enrichment.py +836 -0
  311. multi_agent_brief/orchestrator/runtime_state/claim_support_matrix.py +582 -0
  312. multi_agent_brief/orchestrator/runtime_state/completion_gates.py +672 -0
  313. multi_agent_brief/orchestrator/runtime_state/contracts_loader.py +66 -0
  314. multi_agent_brief/orchestrator/runtime_state/decisions.py +239 -0
  315. multi_agent_brief/orchestrator/runtime_state/errors.py +61 -0
  316. multi_agent_brief/orchestrator/runtime_state/event_log.py +256 -0
  317. multi_agent_brief/orchestrator/runtime_state/evidence_span_registry.py +233 -0
  318. multi_agent_brief/orchestrator/runtime_state/fact_layer.py +755 -0
  319. multi_agent_brief/orchestrator/runtime_state/identity.py +90 -0
  320. multi_agent_brief/orchestrator/runtime_state/lifecycle.py +675 -0
  321. multi_agent_brief/orchestrator/runtime_state/manifest.py +82 -0
  322. multi_agent_brief/orchestrator/runtime_state/operations.py +224 -0
  323. multi_agent_brief/orchestrator/runtime_state/paths.py +38 -0
  324. multi_agent_brief/orchestrator/runtime_state/repair.py +984 -0
  325. multi_agent_brief/orchestrator/runtime_state/safety_surfaces.py +147 -0
  326. multi_agent_brief/orchestrator/runtime_state/semantic_assessment_report.py +692 -0
  327. multi_agent_brief/orchestrator/runtime_state/semantic_support_acceptance.py +683 -0
  328. multi_agent_brief/orchestrator/runtime_state/source_evidence_pack.py +131 -0
  329. multi_agent_brief/orchestrator/runtime_state/stage_completion.py +1320 -0
  330. multi_agent_brief/orchestrator/runtime_state/trajectory.py +200 -0
  331. multi_agent_brief/orchestrator/runtime_state/workflow.py +350 -0
  332. multi_agent_brief/orchestrator/source_evidence.py +43 -0
  333. multi_agent_brief/orchestrator/timing.py +410 -0
  334. multi_agent_brief/orchestrator_contract.py +96 -0
  335. multi_agent_brief/outputs/__init__.py +2 -0
  336. multi_agent_brief/outputs/atomic_reader_projection.py +288 -0
  337. multi_agent_brief/outputs/docx.py +32 -0
  338. multi_agent_brief/outputs/finalize.py +1036 -0
  339. multi_agent_brief/outputs/ib_docx.py +983 -0
  340. multi_agent_brief/outputs/naming.py +38 -0
  341. multi_agent_brief/outputs/pdf.py +20 -0
  342. multi_agent_brief/outputs/reader_final_gate.py +509 -0
  343. multi_agent_brief/outputs/reader_projection.py +397 -0
  344. multi_agent_brief/outputs/source_appendix.py +753 -0
  345. multi_agent_brief/outputs/templates/__init__.py +112 -0
  346. multi_agent_brief/product/__init__.py +49 -0
  347. multi_agent_brief/product/bundle_projection.py +686 -0
  348. multi_agent_brief/product/citation_profile.py +145 -0
  349. multi_agent_brief/product/guidance_manifestation.py +421 -0
  350. multi_agent_brief/product/materiality_selection.py +472 -0
  351. multi_agent_brief/product/policy_gate_adapter.py +116 -0
  352. multi_agent_brief/product/policy_profile.py +39 -0
  353. multi_agent_brief/product/policy_projection.py +161 -0
  354. multi_agent_brief/product/policy_registry.py +83 -0
  355. multi_agent_brief/product/policy_resolver.py +225 -0
  356. multi_agent_brief/product/quality_closeout.py +188 -0
  357. multi_agent_brief/product/quality_panel.py +2217 -0
  358. multi_agent_brief/product/release_approval.py +1034 -0
  359. multi_agent_brief/product/report_pack.py +130 -0
  360. multi_agent_brief/product/report_pack_aliases.py +68 -0
  361. multi_agent_brief/product/report_registry.py +101 -0
  362. multi_agent_brief/product/report_spec.py +181 -0
  363. multi_agent_brief/product/support_wording.py +525 -0
  364. multi_agent_brief/product/template_conformance.py +516 -0
  365. multi_agent_brief/product/template_projection.py +123 -0
  366. multi_agent_brief/product/template_registry.py +244 -0
  367. multi_agent_brief/product/template_render_plan.py +315 -0
  368. multi_agent_brief/product/template_renderer.py +224 -0
  369. multi_agent_brief/product/trajectory_regulation.py +441 -0
  370. multi_agent_brief/provenance/__init__.py +5 -0
  371. multi_agent_brief/provenance/builder.py +841 -0
  372. multi_agent_brief/provenance/contract.py +21 -0
  373. multi_agent_brief/provenance/io.py +144 -0
  374. multi_agent_brief/provenance/model.py +110 -0
  375. multi_agent_brief/provenance/references.py +43 -0
  376. multi_agent_brief/provenance/validator.py +135 -0
  377. multi_agent_brief/quality_gates/__init__.py +19 -0
  378. multi_agent_brief/quality_gates/contract.py +581 -0
  379. multi_agent_brief/quality_gates/state.py +2498 -0
  380. multi_agent_brief/repair/__init__.py +5 -0
  381. multi_agent_brief/repair/router.py +842 -0
  382. multi_agent_brief/runtime_assets.py +431 -0
  383. multi_agent_brief/sources/__init__.py +16 -0
  384. multi_agent_brief/sources/api_filings.py +236 -0
  385. multi_agent_brief/sources/api_news.py +174 -0
  386. multi_agent_brief/sources/base.py +142 -0
  387. multi_agent_brief/sources/cached_package.py +119 -0
  388. multi_agent_brief/sources/cli_provider.py +263 -0
  389. multi_agent_brief/sources/coverage.py +336 -0
  390. multi_agent_brief/sources/decider.py +756 -0
  391. multi_agent_brief/sources/doctor.py +373 -0
  392. multi_agent_brief/sources/evidence_pack.py +364 -0
  393. multi_agent_brief/sources/feishu_provider.py +326 -0
  394. multi_agent_brief/sources/filing_resolver.py +400 -0
  395. multi_agent_brief/sources/industry_packs.py +130 -0
  396. multi_agent_brief/sources/join.py +206 -0
  397. multi_agent_brief/sources/local_signal.py +81 -0
  398. multi_agent_brief/sources/local_signal_planner.py +636 -0
  399. multi_agent_brief/sources/manual.py +259 -0
  400. multi_agent_brief/sources/mcp_provider.py +309 -0
  401. multi_agent_brief/sources/mineru_provider.py +601 -0
  402. multi_agent_brief/sources/normalizer.py +95 -0
  403. multi_agent_brief/sources/opencli_provider.py +282 -0
  404. multi_agent_brief/sources/planner.py +178 -0
  405. multi_agent_brief/sources/registry.py +367 -0
  406. multi_agent_brief/sources/rss.py +190 -0
  407. multi_agent_brief/sources/search_backends/__init__.py +31 -0
  408. multi_agent_brief/sources/search_backends/base.py +51 -0
  409. multi_agent_brief/sources/search_backends/brave.py +192 -0
  410. multi_agent_brief/sources/search_backends/capabilities.py +94 -0
  411. multi_agent_brief/sources/search_backends/exa.py +180 -0
  412. multi_agent_brief/sources/search_backends/firecrawl.py +164 -0
  413. multi_agent_brief/sources/search_backends/serper.py +241 -0
  414. multi_agent_brief/sources/search_backends/tavily.py +124 -0
  415. multi_agent_brief/sources/sourcehub.py +505 -0
  416. multi_agent_brief/sources/web_search.py +267 -0
  417. multi_agent_brief/status.py +966 -0
  418. multi_agent_brief/tools/__init__.py +3 -0
  419. multi_agent_brief/tools/draft_cleanup.py +198 -0
  420. multi_agent_brief/workbuddy/__init__.py +1 -0
  421. multi_agent_brief/workbuddy/diagnose.py +569 -0
  422. multi_agent_brief/workbuddy/skill_pack.py +309 -0
  423. multi_agent_brief/workspace/__init__.py +1 -0
  424. multi_agent_brief/workspace/init_profile.py +45 -0
@@ -0,0 +1,1473 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import os
5
+ from pathlib import Path
6
+ from typing import Any, Callable
7
+
8
+ from multi_agent_brief.audience_memory import (
9
+ build_default_audience_profile,
10
+ profile_data_from_object,
11
+ )
12
+ from multi_agent_brief.workspace.init_profile import InitProfile
13
+
14
+ try:
15
+ from dotenv import load_dotenv
16
+ except ImportError:
17
+ # dotenv is optional; fall back to os.environ only
18
+ def load_dotenv(*args: Any, **kwargs: Any) -> None:
19
+ pass
20
+
21
+
22
+ # Search backend configuration
23
+ _SEARCH_BACKENDS = {
24
+ "tavily": {"env_key": "TAVILY_API_KEY", "name": "Tavily", "desc": "AI-powered web search"},
25
+ "exa": {"env_key": "EXA_API_KEY", "name": "Exa", "desc": "Deep research, papers, filings"},
26
+ "brave": {"env_key": "BRAVE_SEARCH_API_KEY", "name": "Brave", "desc": "Independent web index"},
27
+ "firecrawl": {"env_key": "FIRECRAWL_API_KEY", "name": "Firecrawl", "desc": "Search + full-text crawl"},
28
+ "serper": {"env_key": "SERPER_API_KEY", "name": "Serper", "desc": "Google SERP"},
29
+ }
30
+
31
+
32
+ def _get_configured_backends(workspace_path: Path | None = None) -> list[str]:
33
+ """Check .env and environment for configured search backend keys."""
34
+ # Try to load .env from workspace or current directory
35
+ if workspace_path:
36
+ env_file = workspace_path / ".env"
37
+ if env_file.exists():
38
+ load_dotenv(env_file)
39
+ else:
40
+ load_dotenv()
41
+
42
+ configured = []
43
+ for backend_key, info in _SEARCH_BACKENDS.items():
44
+ if os.environ.get(info["env_key"]):
45
+ configured.append(backend_key)
46
+ return configured
47
+
48
+
49
+ def _build_search_backend_choices(
50
+ language: str, workspace_path: Path | None = None
51
+ ) -> tuple[dict[str, str], str]:
52
+ """Build search backend choices and return (choices_dict, default_key).
53
+
54
+ Returns:
55
+ choices: mapping of choice_key -> backend_value
56
+ default_key: the key to use as default (semantic, not positional)
57
+ """
58
+ configured = _get_configured_backends(workspace_path)
59
+ choices: dict[str, str] = {}
60
+ idx = 1
61
+
62
+ # Add all supported external backends. Mark configured ones, but do not hide
63
+ # alternatives; otherwise users think Tavily is the only supported choice.
64
+ configured_set = set(configured)
65
+ for backend_key, info in _SEARCH_BACKENDS.items():
66
+ status = "configured" if backend_key in configured_set else "needs API key"
67
+ if language == "zh-CN":
68
+ choices[str(idx)] = f"{backend_key} ({info['name']} - {info['desc']};{status})"
69
+ else:
70
+ choices[str(idx)] = f"{backend_key} ({info['desc']}; {status})"
71
+ idx += 1
72
+
73
+ # Add runtime-provided websearch
74
+ runtime_key = str(idx)
75
+ if language == "zh-CN":
76
+ choices[runtime_key] = "runtime_websearch (运行时提供的网络搜索工具)"
77
+ else:
78
+ choices[runtime_key] = "runtime_websearch (Runtime-provided web search tool)"
79
+ idx += 1
80
+
81
+ # Add "add API key later" option
82
+ later_key = str(idx)
83
+ if language == "zh-CN":
84
+ choices[later_key] = "configure_later (稍后配置 API key)"
85
+ else:
86
+ choices[later_key] = "configure_later (Add API key later)"
87
+
88
+ # Default to "configure_later" (semantic default, not positional)
89
+ return choices, later_key
90
+
91
+
92
+ def _demo_published_at() -> str:
93
+ """Return a dynamic date 1 day before today for demo source freshness."""
94
+ from datetime import date, timedelta
95
+ return (date.today() - timedelta(days=1)).isoformat()
96
+
97
+
98
+ def _build_demo_news() -> dict:
99
+ return {
100
+ "source_url": "https://example.com/synthetic-market-news",
101
+ "published_at": _demo_published_at(),
102
+ "items": [
103
+ "A public market tracker reported that manufacturing output continued to expand in selected regions, with production indices rising 3.2% month-over-month.",
104
+ "A policy update indicated that new trade regulations may affect import timelines for selected industrial products, with tariff adjustments expected next quarter.",
105
+ "A competitor announced a major manufacturing capacity expansion plan, with commercial production expected next year. The expansion represents a $350 million capital investment.",
106
+ "Industry analysts noted that supply chain constraints for key raw materials have eased compared to the prior quarter, with spot prices declining 6% month-over-month.",
107
+ "A regional utility signed a long-term supply agreement with a preferred vendor, marking the largest single procurement in the sector this quarter.",
108
+ "The Department of Commerce released updated guidance on domestic content requirements for manufactured goods, effective next quarter.",
109
+ "Automation adoption in manufacturing facilities reached a record 42% penetration rate, driven by labor cost pressures and quality requirements.",
110
+ "A major logistics provider announced plans to add 15 new distribution centers across North America by 2029, with priority given to industrial zones.",
111
+ "A leading manufacturer reported a 18% year-over-year increase in order backlog, citing strong demand from construction and infrastructure sectors.",
112
+ "Cross-border trade volumes increased 12% compared to the prior year, reflecting improved supply chain normalization.",
113
+ ],
114
+ }
115
+
116
+
117
+ def _build_demo_market_data() -> dict:
118
+ return {
119
+ "source_url": "https://example.com/synthetic-market-data",
120
+ "published_at": _demo_published_at(),
121
+ "items": [
122
+ "Synthetic commodity price checks showed a 3.5% week-over-week decline in selected spot-market channels, bringing benchmark prices to $1.42 per unit.",
123
+ "Synthetic industrial supply quotes remained broadly stable at benchmark levels for project assumptions, with steel plate at $890 per ton.",
124
+ "Copper futures traded at $4.15/lb, up 1.8% week-over-week, reflecting tight mine supply and strong industrial demand.",
125
+ "Industrial equipment lead times averaged 14 weeks, down from 18 weeks earlier, indicating improving supply conditions.",
126
+ "Freight index for domestic trucking rose 2.3% month-over-month to 142.5, driven by seasonal demand and fuel cost pass-through.",
127
+ ],
128
+ }
129
+
130
+ DEMO_SOURCES = """source_strategy:
131
+ profile: "conservative"
132
+ enabled_providers:
133
+ - "manual"
134
+
135
+ manual:
136
+ enabled: true
137
+ sources: []
138
+ """
139
+
140
+ DEMO_USER_MD = """# User Context
141
+
142
+ ## Company
143
+
144
+ Synthetic Corp
145
+
146
+ ## Industry
147
+
148
+ Manufacturing & Industrial
149
+
150
+ ## Role
151
+
152
+ Strategy Office
153
+
154
+ ## Focus Areas
155
+
156
+ - Manufacturing output and capacity trends
157
+ - Trade regulation and policy impacts
158
+ - Competitor capacity announcements
159
+ - Commodity pricing and supply chain conditions
160
+
161
+ ## Cadence
162
+
163
+ Weekly
164
+
165
+ ## Notes
166
+
167
+ This is a synthetic demo workspace for validating the reference workflow.
168
+ All data is public-safe and fabricated for testing purposes.
169
+ """
170
+
171
+ DEMO_CONFIG = """project:
172
+ name: "Synthetic Market Brief Demo"
173
+ language: "en-US"
174
+ audience: "management"
175
+
176
+ report:
177
+ date: "auto"
178
+ max_source_age_days: 14
179
+ fail_on_stale_source: true
180
+
181
+ input:
182
+ path: "input"
183
+
184
+ output:
185
+ path: "output"
186
+ formats:
187
+ - "markdown"
188
+ - "docx"
189
+ filename_template: "{project_name}_{report_date}"
190
+ named_outputs: true
191
+
192
+ # Relaxed quality thresholds for synthetic demo workspace.
193
+ # Production weekly briefs should NOT set these overrides.
194
+ brief_quality:
195
+ quiet_week: true
196
+ allow_quiet_week_exception: true
197
+ expected_summary_bullets: null
198
+ required_metadata_labels: []
199
+ """
200
+
201
+ WORKSPACE_GITIGNORE = """.env
202
+ .env.*
203
+ output/
204
+ .rag/
205
+ private_inputs/
206
+ private_outputs/
207
+ logs/
208
+ user.md
209
+ audience_profile.md
210
+ *.docx
211
+ *.pdf
212
+ *.xlsx
213
+ .DS_Store
214
+ """
215
+
216
+ INPUT_README_EN = """# Input Folder
217
+
218
+ Use the subfolders below to keep evidence, instructions, feedback, and
219
+ background references separate.
220
+
221
+ | Folder | Use for | Enters Claim Ledger? |
222
+ |---|---|---|
223
+ | `sources/` | Current-period factual evidence: news, filings, market data, reports, RSS exports | Yes |
224
+ | `context/` | Background reference: prior briefs, example report style, company background, historical notes | No |
225
+ | `instructions/` | Task requirements, structure requirements, prompt drafts, writing rules | No |
226
+ | `feedback/` | Human comments, revision notes, previous-version feedback | No |
227
+
228
+ For prior weekly reports or example briefs, place a Markdown version in
229
+ `input/context/`. These files are style and structure references only; they are
230
+ not current-period evidence.
231
+
232
+ PDF, DOCX, PPTX, XLSX, and image inputs are supported through MinerU extraction.
233
+ Place the original file in the correct subfolder first, then run:
234
+
235
+ ```bash
236
+ multi-agent-brief inputs extract --config config.yaml
237
+ multi-agent-brief inputs classify --config config.yaml
238
+ ```
239
+
240
+ The extraction command writes an adjacent `.mineru.md` file. Directory role is
241
+ preserved: extracted Markdown under `input/sources/` may enter the Claim Ledger;
242
+ extracted Markdown under `input/context/`, `input/instructions/`, or
243
+ `input/feedback/` remains non-evidence.
244
+
245
+ Do not place confidential company documents, internal reports, private messages,
246
+ credentials, raw logs, or material non-public information in this folder unless
247
+ the workspace is local-only and excluded from Git.
248
+
249
+ Backward compatibility: files placed directly in `input/` may be treated as
250
+ evidence. Prefer using the subfolders above.
251
+
252
+ Recommended JSON format for `input/sources/`:
253
+
254
+ ```json
255
+ {
256
+ "source_url": "https://example.com/source",
257
+ "published_at": "2026-06-02",
258
+ "source_tier": "industry_media",
259
+ "items": [
260
+ "Example source-backed statement."
261
+ ]
262
+ }
263
+ ```
264
+ """
265
+
266
+ INPUT_README_ZH = """# 输入文件夹
267
+
268
+ 请使用下面的子目录区分事实来源、任务要求、修改反馈和背景参考。
269
+
270
+ | 目录 | 用途 | 是否进入 Claim Ledger |
271
+ |---|---|---|
272
+ | `sources/` | 本期事实证据:新闻、公告、市场数据、行业报告、RSS 导出等 | 是 |
273
+ | `context/` | 背景参考:往期简报、简报示例、公司背景、历史资料 | 否 |
274
+ | `instructions/` | 任务要求、结构要求、prompt 草稿、写作规则 | 否 |
275
+ | `feedback/` | 人类批注、修改意见、上一版反馈 | 否 |
276
+
277
+ 请在 `input/context/` 里加入你的简报示例 Markdown 文件,例如往期周报。
278
+ 这些文件只作为结构、口吻和表格风格参考,不作为本期事实来源。
279
+
280
+ PDF、DOCX、PPTX、XLSX 和图片输入通过 MinerU 抽取支持。请先把原始文件放到正确子目录,再运行:
281
+
282
+ ```bash
283
+ multi-agent-brief inputs extract --config config.yaml
284
+ multi-agent-brief inputs classify --config config.yaml
285
+ ```
286
+
287
+ 抽取命令会在原文件旁边写入 `.mineru.md`。目录角色保持不变:
288
+ `input/sources/` 下抽取出的 Markdown 可以进入 Claim Ledger;`input/context/`、
289
+ `input/instructions/`、`input/feedback/` 下抽取出的 Markdown 仍然是非证据材料。
290
+
291
+ 不要把机密公司文件、内部报告、私有消息、凭据、原始日志或重大非公开信息放入此文件夹,除非该工作区只保存在本地且已从 Git 中排除。
292
+
293
+ 向后兼容:直接放在 `input/` 根目录下的文件可能被视为 evidence。
294
+ 新项目请优先使用上面的子目录。
295
+
296
+ `input/sources/` 推荐 JSON 格式:
297
+
298
+ ```json
299
+ {
300
+ "source_url": "https://example.com/source",
301
+ "published_at": "2026-06-02",
302
+ "source_tier": "industry_media",
303
+ "items": [
304
+ "Example source-backed statement."
305
+ ]
306
+ }
307
+ ```
308
+ """
309
+
310
+
311
+ class InitOnboardingRequired(RuntimeError):
312
+ """Raised when init would otherwise create a workspace from hidden defaults."""
313
+
314
+
315
+ _REQUIRED_DIRECT_INIT_ARGS: dict[str, str] = {
316
+ "language": "--language",
317
+ "company": "--company",
318
+ "industry": "--industry",
319
+ "title": "--title",
320
+ "audience": "--audience",
321
+ "cadence": "--cadence",
322
+ "source_profile": "--source-profile",
323
+ }
324
+
325
+
326
+ def missing_required_direct_init_args(args: Any) -> list[str]:
327
+ """Return required business fields missing from direct CLI init."""
328
+ missing: list[str] = []
329
+ for attr, flag in _REQUIRED_DIRECT_INIT_ARGS.items():
330
+ if not getattr(args, attr, None):
331
+ missing.append(flag)
332
+ return missing
333
+
334
+
335
+ def create_demo_workspace(target: Path, *, force: bool = False) -> None:
336
+ input_dir = target / "input"
337
+ sources_dir = input_dir / "sources"
338
+ output_dir = target / "output"
339
+ output_dir.mkdir(parents=True, exist_ok=True)
340
+ sources_dir.mkdir(parents=True, exist_ok=True)
341
+ # Create non-evidence subdirectories (empty, for user organization)
342
+ for subdir in ("feedback", "instructions", "context"):
343
+ (input_dir / subdir).mkdir(parents=True, exist_ok=True)
344
+ files = {
345
+ target / "config.yaml": DEMO_CONFIG,
346
+ target / "sources.yaml": DEMO_SOURCES,
347
+ target / "user.md": DEMO_USER_MD,
348
+ target / "audience_profile.md": build_default_audience_profile(
349
+ {
350
+ "company": "Synthetic Corp",
351
+ "industry_text": "Manufacturing & Industrial",
352
+ "role": "strategy_office",
353
+ "audience": "management",
354
+ "audience_profile": "management",
355
+ "brief_title": "Synthetic Market Brief Demo",
356
+ "task_objective": "Validate the public-safe reference workflow with synthetic data.",
357
+ "interface_language": "en-US",
358
+ "output_language": "en-US",
359
+ "cadence": "weekly",
360
+ "source_profile": "conservative",
361
+ "focus_areas": [
362
+ "Manufacturing output and capacity trends",
363
+ "Trade regulation and policy impacts",
364
+ "Competitor capacity announcements",
365
+ "Commodity pricing and supply chain conditions",
366
+ ],
367
+ "forbidden_sources": [
368
+ "confidential company documents",
369
+ "private messages",
370
+ "credentials",
371
+ "material non-public information",
372
+ ],
373
+ "output_formats": ["markdown", "docx"],
374
+ }
375
+ ),
376
+ target / ".gitignore": WORKSPACE_GITIGNORE,
377
+ target / ".env.example": _build_env_example(),
378
+ input_dir / "README.md": build_input_readme("en-US"),
379
+ sources_dir / "README.md": _build_sources_readme("en-US"),
380
+ input_dir / "feedback" / "README.md": _build_feedback_readme("en-US"),
381
+ input_dir / "instructions" / "README.md": _build_instructions_readme("en-US"),
382
+ input_dir / "context" / "README.md": _build_context_readme("en-US"),
383
+ sources_dir / "news.json": json.dumps(_build_demo_news(), indent=2),
384
+ sources_dir / "market_data.json": json.dumps(_build_demo_market_data(), indent=2),
385
+ }
386
+ _write_files(files, force=force)
387
+
388
+
389
+ def create_workspace(target: Path, profile: InitProfile, *, force: bool = False) -> None:
390
+ # Set decision mode based on source profile
391
+ if profile.source_profile == "llm_decide":
392
+ profile.source_decision_mode = "agent_decide"
393
+
394
+ input_dir = target / "input"
395
+ sources_dir = input_dir / "sources"
396
+ output_dir = target / "output"
397
+ output_dir.mkdir(parents=True, exist_ok=True)
398
+ sources_dir.mkdir(parents=True, exist_ok=True)
399
+ # Create non-evidence subdirectories with README
400
+ for subdir in ("feedback", "instructions", "context"):
401
+ (input_dir / subdir).mkdir(parents=True, exist_ok=True)
402
+
403
+ lang = profile.interface_language
404
+ files = {
405
+ target / "config.yaml": to_yaml(build_config(profile)),
406
+ target / "profile.yaml": to_yaml(build_profile(profile)),
407
+ target / "sources.yaml": to_yaml(build_sources(profile)),
408
+ target / "competitor_universe.yaml": to_yaml(_build_competitor_universe(profile)),
409
+ target / "user.md": build_user_md(profile),
410
+ target / "audience_profile.md": build_default_audience_profile(
411
+ profile_data_from_object(profile)
412
+ ),
413
+ target / ".gitignore": WORKSPACE_GITIGNORE,
414
+ target / ".env.example": _build_env_example(),
415
+ input_dir / "README.md": build_input_readme(lang),
416
+ sources_dir / "README.md": _build_sources_readme(lang),
417
+ input_dir / "feedback" / "README.md": _build_feedback_readme(lang),
418
+ input_dir / "instructions" / "README.md": _build_instructions_readme(lang),
419
+ input_dir / "context" / "README.md": _build_context_readme(lang),
420
+ }
421
+ _write_files(files, force=force)
422
+
423
+ # Create state directory for cross-period tracking (runtime, not committed)
424
+ state_dir = target / "state" / "market_competitor"
425
+ state_dir.mkdir(parents=True, exist_ok=True)
426
+
427
+
428
+ def _is_interactive() -> bool:
429
+ """Check if stdin is connected to a real terminal (not a pipe or agent Bash tool)."""
430
+ import sys
431
+ return sys.stdin.isatty() if hasattr(sys.stdin, "isatty") else False
432
+
433
+
434
+ def build_profile_from_args(args: Any, *, input_func: Callable[[str], str] | None = None) -> InitProfile:
435
+ input_func = input if input_func is None else input_func
436
+ profile = InitProfile()
437
+ if has_direct_init_args(args):
438
+ profile.interface_language = normalize_language(args.language or profile.interface_language)
439
+ profile.output_language = normalize_language(args.output_language or args.language or profile.output_language)
440
+ profile.company = args.company or profile.company
441
+ profile.role = args.role or profile.role
442
+ profile.industry = args.industry or profile.industry
443
+ profile.brief_title = args.title or profile.brief_title
444
+ profile.audience = args.audience or profile.audience
445
+ profile.focus_areas = parse_list_arg(args.focus_areas) or profile.focus_areas
446
+ profile.cadence = args.cadence or profile.cadence
447
+ if args.selector_max_items is not None:
448
+ profile.selector_max_items = args.selector_max_items
449
+ apply_rag_args(profile, args.rag, args.retrieval_provider)
450
+ profile.output_formats = parse_list_arg(args.output_formats) or profile.output_formats
451
+ profile.source_profile = getattr(args, "source_profile", None) or profile.source_profile
452
+ if getattr(args, "web_search_mode", None):
453
+ profile.web_search_mode = args.web_search_mode
454
+ profile.web_search_enabled = args.web_search_mode != "disabled"
455
+ if getattr(args, "search_backend", None):
456
+ profile.search_backend = args.search_backend
457
+ profile.web_search_mode = "external_api"
458
+ profile.web_search_enabled = True
459
+ profile.tavily_enabled = args.search_backend == "tavily"
460
+ if getattr(args, "tavily", False):
461
+ profile.tavily_enabled = True
462
+ profile.web_search_enabled = True
463
+ profile.web_search_mode = "external_api"
464
+ profile.search_backend = "tavily"
465
+ if getattr(args, "initial_news_backfill", False):
466
+ profile.initial_news_backfill_enabled = True
467
+ if getattr(args, "initial_news_backfill_days", None):
468
+ profile.initial_news_backfill_days = parse_int(
469
+ str(args.initial_news_backfill_days),
470
+ profile.initial_news_backfill_days,
471
+ )
472
+ if getattr(args, "initial_news_backfill_daily_max_results", None):
473
+ profile.initial_news_backfill_daily_max_results = parse_int(
474
+ str(args.initial_news_backfill_daily_max_results),
475
+ profile.initial_news_backfill_daily_max_results,
476
+ )
477
+ preferred_domains = parse_list_arg(getattr(args, "preferred_news_domains", None))
478
+ if preferred_domains:
479
+ profile.preferred_news_domains = preferred_domains
480
+ excluded_domains = parse_list_arg(getattr(args, "excluded_news_domains", None))
481
+ if excluded_domains:
482
+ profile.excluded_news_domains = excluded_domains
483
+ return profile
484
+ # No CLI args → try interactive prompt
485
+ if _is_interactive():
486
+ try:
487
+ return prompt_for_profile(input_func=input_func)
488
+ except (EOFError, KeyboardInterrupt):
489
+ raise InitOnboardingRequired(
490
+ "Interactive init was interrupted before onboarding completed."
491
+ )
492
+ raise InitOnboardingRequired(
493
+ "Non-interactive init without onboarding answers is not allowed."
494
+ )
495
+
496
+
497
+ def has_direct_init_args(args: Any) -> bool:
498
+ fields = [
499
+ "language",
500
+ "output_language",
501
+ "company",
502
+ "role",
503
+ "industry",
504
+ "title",
505
+ "audience",
506
+ "focus_areas",
507
+ "cadence",
508
+ "rag",
509
+ "retrieval_provider",
510
+ "selector_max_items",
511
+ "output_formats",
512
+ "source_profile",
513
+ "web_search_mode",
514
+ "search_backend",
515
+ "initial_news_backfill",
516
+ "initial_news_backfill_days",
517
+ "initial_news_backfill_daily_max_results",
518
+ "preferred_news_domains",
519
+ "excluded_news_domains",
520
+ ]
521
+ # Check string/list fields for non-None
522
+ if any(getattr(args, field, None) is not None for field in fields):
523
+ return True
524
+ # Check boolean flags — tavily is store_true, default False
525
+ if getattr(args, "tavily", False):
526
+ return True
527
+ return False
528
+
529
+
530
+ def prompt_for_profile(*, input_func: Callable[[str], str] | None = None) -> InitProfile:
531
+ input_func = input if input_func is None else input_func
532
+ language_choice = ask_choice(
533
+ input_func,
534
+ "Select language / 选择语言:\n1. English\n2. 简体中文\n3. Bilingual / 双语\nDefault [2]: ",
535
+ {"1": "en-US", "2": "zh-CN", "3": "bilingual"},
536
+ "2",
537
+ )
538
+ profile = InitProfile(interface_language=language_choice, output_language=language_choice)
539
+ prompts = prompt_labels(language_choice)
540
+
541
+ profile.company = ask_text(input_func, prompts["company"], profile.company)
542
+ profile.role = ask_text(input_func, prompts["role"], profile.role)
543
+ profile.industry = ask_text(input_func, prompts["industry"], profile.industry)
544
+ profile.brief_title = ask_text(input_func, prompts["title"], profile.brief_title)
545
+ profile.audience = ask_text(input_func, prompts["audience"], profile.audience)
546
+ profile.focus_areas = parse_list_arg(ask_text(input_func, prompts["focus"], ",".join(profile.focus_areas)))
547
+ profile.cadence = ask_text(input_func, prompts["cadence"], profile.cadence)
548
+ max_items = ask_text(input_func, prompts["selector_max_items"], str(profile.selector_max_items))
549
+ profile.selector_max_items = parse_int(max_items, profile.selector_max_items)
550
+ rag_enabled = ask_yes_no(input_func, prompts["rag"], default=False)
551
+ profile.retrieval_enabled = rag_enabled
552
+ if rag_enabled:
553
+ profile.retrieval_provider = ask_choice(input_func, prompts["retrieval_provider"], {"1": "ollama", "2": "gemini"}, "1")
554
+ profile.retrieval_model = retrieval_model_for_provider(profile.retrieval_provider)
555
+ profile.output_formats = parse_list_arg(ask_text(input_func, prompts["outputs"], ",".join(profile.output_formats)))
556
+ profile.max_source_age_days = parse_int(ask_text(input_func, prompts["max_age"], str(profile.max_source_age_days)), 14)
557
+ profile.source_profile = ask_choice(input_func, prompts["source_profile"], prompts["source_profile_options"], "2")
558
+
559
+ # Web search backend selection
560
+ web_search_enabled = ask_yes_no(input_func, prompts["web_search"], default=False)
561
+ if web_search_enabled:
562
+ search_choices, default_key = _build_search_backend_choices(language_choice)
563
+ selected_display = ask_choice(
564
+ input_func, prompts["search_backend"], search_choices, default_key
565
+ )
566
+
567
+ # Parse the backend value from the display string
568
+ # Format: "backend_key (description)" or "backend_key (中文描述)"
569
+ if "(" in selected_display:
570
+ selected_backend = selected_display.split("(")[0].strip()
571
+ else:
572
+ selected_backend = selected_display.strip()
573
+
574
+ # Map backend value to mode and set profile fields
575
+ if selected_backend == "runtime_websearch":
576
+ profile.web_search_enabled = True
577
+ profile.web_search_mode = "runtime_tool"
578
+ profile.search_backend = ""
579
+ profile.tavily_enabled = False
580
+ elif selected_backend == "configure_later":
581
+ profile.web_search_enabled = True
582
+ profile.web_search_mode = "configure_later"
583
+ profile.search_backend = ""
584
+ profile.tavily_enabled = False
585
+ elif selected_backend in _SEARCH_BACKENDS:
586
+ profile.web_search_enabled = True
587
+ profile.web_search_mode = "external_api"
588
+ profile.search_backend = selected_backend
589
+ profile.tavily_enabled = selected_backend == "tavily"
590
+ else:
591
+ # Unknown backend, treat as configure_later
592
+ profile.web_search_enabled = True
593
+ profile.web_search_mode = "configure_later"
594
+ profile.search_backend = ""
595
+ profile.tavily_enabled = False
596
+ else:
597
+ profile.web_search_enabled = False
598
+ profile.web_search_mode = "disabled"
599
+ profile.search_backend = ""
600
+ profile.tavily_enabled = False
601
+
602
+ if profile.web_search_enabled and profile.source_profile == "llm_decide":
603
+ profile.initial_news_backfill_enabled = ask_yes_no(
604
+ input_func,
605
+ prompts["initial_news_backfill"],
606
+ default=False,
607
+ )
608
+ if profile.web_search_enabled:
609
+ profile.preferred_news_domains = parse_list_arg(
610
+ ask_text(input_func, prompts["preferred_news_domains"], "")
611
+ )
612
+ profile.excluded_news_domains = parse_list_arg(
613
+ ask_text(input_func, prompts["excluded_news_domains"], "")
614
+ )
615
+
616
+ # Competitor monitoring
617
+ competitor_enabled = ask_yes_no(input_func, prompts["competitor_module"], default=False)
618
+ profile.competitor_module_enabled = competitor_enabled
619
+ if competitor_enabled:
620
+ names_raw = ask_text(input_func, prompts["competitor_names"], "")
621
+ if names_raw.strip():
622
+ profile.competitor_names = [n.strip() for n in names_raw.split(",") if n.strip()]
623
+
624
+ return profile
625
+
626
+
627
+ def prompt_labels(language: str) -> dict[str, Any]:
628
+ if language == "en-US":
629
+ return {
630
+ "company": "Company name: ",
631
+ "role": "Select your role:\n1. Strategy / President Office\n2. Investor Relations\n3. Research Analyst\n4. Policy Analyst\n5. Management Support\n6. Other\nDefault [1]: ",
632
+ "role_options": {
633
+ "1": "strategy_office",
634
+ "2": "investor_relations",
635
+ "3": "research_analyst",
636
+ "4": "policy_analyst",
637
+ "5": "management_support",
638
+ "6": "other",
639
+ },
640
+ "industry": "Select industry:\n1. Manufacturing\n2. Banking\n3. Fund / Asset Management\n4. Internet / Technology\n5. General Research\nDefault [1]: ",
641
+ "industry_options": {
642
+ "1": "manufacturing",
643
+ "2": "banking",
644
+ "3": "fund",
645
+ "4": "internet",
646
+ "5": "general",
647
+ },
648
+ "title": "Brief title: ",
649
+ "audience": "Audience (e.g. management, strategy, research, investor relations, marketing, etc.): ",
650
+ "focus": "Focus areas, comma-separated: ",
651
+ "cadence": "Reporting cadence:\n1. Weekly\n2. Biweekly\n3. Monthly\n4. Ad hoc\nDefault [1]: ",
652
+ "cadence_options": {"1": "weekly", "2": "biweekly", "3": "monthly", "4": "ad_hoc"},
653
+ "selector_max_items": "How many items should be selected for each brief? Default [20]: ",
654
+ "rag": "Enable historical retrieval / RAG? [y/N]: ",
655
+ "retrieval_provider": "Choose retrieval provider:\n1. Ollama local\n2. Gemini API\nDefault [1]: ",
656
+ "outputs": "Output formats, comma-separated: ",
657
+ "max_age": "Maximum source age in days: ",
658
+ "source_profile": "Source profile:\n1. Conservative: official and high-confidence sources only\n2. Research: balanced official, industry, market, and research sources\n3. Aggressive signal: broader signal discovery, more noise allowed\n4. Custom: user will manually edit sources.yaml\n5. Let LLM decide: generate an agent-readable source discovery policy\nDefault [2]: ",
659
+ "source_profile_options": {"1": "conservative", "2": "research", "3": "aggressive_signal", "4": "custom", "5": "llm_decide"},
660
+ "web_search": "Enable live web search? [y/N]: ",
661
+ "search_backend": "How should live web search be provided? ",
662
+ "initial_news_backfill": (
663
+ "Run initial last-7-days news discovery? This searches 20"
664
+ " relevant news items per day. [y/N]: "
665
+ ),
666
+ "preferred_news_domains": (
667
+ "Optional preferred news domains, comma-separated"
668
+ " (leave blank for user-need-based general search): "
669
+ ),
670
+ "excluded_news_domains": (
671
+ "Optional domains to exclude from discovered news, comma-separated: "
672
+ ),
673
+ "competitor_module": "Enable competitor monitoring? [y/N]: ",
674
+ "competitor_names": "Enter competitor names, comma-separated (e.g. Acme Corp, Globex Inc): ",
675
+ }
676
+ if language == "bilingual":
677
+ labels = prompt_labels("en-US")
678
+ labels.update(
679
+ {
680
+ "company": "Company name / 公司名称: ",
681
+ "role": "Select your role / 请选择岗位:\n1. Strategy / President Office / 总裁办・战略研究\n2. Investor Relations / 投资者关系\n3. Research Analyst / 行业研究\n4. Policy Analyst / 政策研究\n5. Management Support / 管理层支持\n6. Other / 其他\nDefault [1]: ",
682
+ "industry": "Select industry / 请选择行业:\n1. Manufacturing / 制造业\n2. Banking / 银行\n3. Fund / 基金\n4. Internet / 互联网\n5. General Research / 通用研究\nDefault [1]: ",
683
+ "title": "Brief title / 简报标题: ",
684
+ "audience": "Audience / 阅读对象 (e.g. management/管理层, strategy/战略, research/研究, IR/投关, marketing/市场, etc.): ",
685
+ "focus": "Focus areas / 关注领域,comma-separated / 逗号分隔: ",
686
+ "cadence": "Reporting cadence / 简报频率:\n1. Weekly / 每周\n2. Biweekly / 双周\n3. Monthly / 每月\n4. Ad hoc / 不定期\nDefault [1]: ",
687
+ "selector_max_items": "How many items / 每期筛选多少条?Default [20]: ",
688
+ "rag": "Enable historical retrieval / RAG? 是否启用历史检索?[y/N]: ",
689
+ "outputs": "Output formats / 输出格式,comma-separated / 逗号分隔: ",
690
+ "max_age": "Maximum source age in days / 最大来源天数: ",
691
+ "source_profile": "Source profile / 信息来源策略:\n1. Conservative / 保守:仅官方和高置信来源\n2. Research / 研究:官方、行业、市场、研究来源平衡\n3. Aggressive signal / 激进信号:扩大发现范围\n4. Custom / 自定义\n5. Let LLM decide / 让 LLM 自动决定来源\nDefault [2]: ",
692
+ "source_profile_options": {"1": "conservative", "2": "research", "3": "aggressive_signal", "4": "custom", "5": "llm_decide"},
693
+ "web_search": "Enable live web search? / 启用实时网络搜索?[y/N]: ",
694
+ "search_backend": "How should live web search be provided? / 如何提供实时网络搜索? ",
695
+ "initial_news_backfill": (
696
+ "Run initial last-7-days news discovery? / 是否运行过去七天新闻查找?"
697
+ " 将会搜索过去七天每日二十条相关新闻。[y/N]: "
698
+ ),
699
+ "preferred_news_domains": (
700
+ "Optional preferred news domains / 可选:偏好的新闻网站域名,"
701
+ "comma-separated / 逗号分隔(留空则按用户需求通用搜索): "
702
+ ),
703
+ "excluded_news_domains": (
704
+ "Optional excluded news domains / 可选:排除的新闻网站域名,"
705
+ "comma-separated / 逗号分隔: "
706
+ ),
707
+ "competitor_module": "Enable competitor monitoring? / 启用竞对监测?[y/N]: ",
708
+ "competitor_names": "Enter competitor names / 输入竞对公司名称,comma-separated / 逗号分隔: ",
709
+ }
710
+ )
711
+ return labels
712
+ return {
713
+ "company": "请输入公司名称:",
714
+ "role": "请选择你的岗位:\n1. 总裁办 / 战略研究\n2. 投资者关系\n3. 行业研究\n4. 政策研究\n5. 管理层支持\n6. 其他\n默认 [1]:",
715
+ "role_options": {
716
+ "1": "strategy_office",
717
+ "2": "investor_relations",
718
+ "3": "research_analyst",
719
+ "4": "policy_analyst",
720
+ "5": "management_support",
721
+ "6": "other",
722
+ },
723
+ "industry": "请选择行业:\n1. 制造业\n2. 银行\n3. 基金\n4. 互联网\n5. 通用研究\n默认 [1]:",
724
+ "industry_options": {
725
+ "1": "manufacturing",
726
+ "2": "banking",
727
+ "3": "fund",
728
+ "4": "internet",
729
+ "5": "general",
730
+ },
731
+ "title": "请输入简报标题:",
732
+ "audience": "请输入阅读对象(例如:管理层、战略团队、研究团队、投资者关系、市场团队 等):",
733
+ "focus": "请输入关注领域,逗号分隔:",
734
+ "cadence": "请选择简报频率:\n1. 每周\n2. 双周\n3. 每月\n4. 不定期\n默认 [1]:",
735
+ "cadence_options": {"1": "weekly", "2": "biweekly", "3": "monthly", "4": "ad_hoc"},
736
+ "selector_max_items": "每期筛选多少条?默认 [20]:",
737
+ "rag": "是否启用历史检索 / RAG?[y/N]:",
738
+ "retrieval_provider": "请选择检索 provider:\n1. Ollama 本地\n2. Gemini API\n默认 [1]:",
739
+ "outputs": "请输入输出格式,逗号分隔:",
740
+ "max_age": "请输入最大来源天数:",
741
+ "source_profile": "请选择信息来源策略:\n1. 保守:只使用官方和高置信来源\n2. 研究:官方、行业媒体、市场数据、研究来源平衡\n3. 激进信号:扩大信号发现范围,允许更多噪音\n4. 自定义:用户后续手动编辑 sources.yaml\n5. 让 LLM 自动决定:生成 agent 可读的来源发现策略\n默认 [2]:",
742
+ "source_profile_options": {"1": "conservative", "2": "research", "3": "aggressive_signal", "4": "custom", "5": "llm_decide"},
743
+ "web_search": "是否启用实时网络搜索?[y/N]:",
744
+ "search_backend": "如何提供实时网络搜索? ",
745
+ "initial_news_backfill": "是否运行过去七天新闻查找?将会搜索过去七天每日二十条相关新闻。[y/N]:",
746
+ "preferred_news_domains": "可选:偏好的新闻网站域名,逗号分隔(留空则按用户需求通用搜索):",
747
+ "excluded_news_domains": "可选:排除的新闻网站域名,逗号分隔:",
748
+ "competitor_module": "是否启用竞对监测?[y/N]:",
749
+ "competitor_names": "请输入竞对公司名称,逗号分隔(如:XX科技、YY集团):",
750
+ }
751
+
752
+
753
+ def build_config(profile: InitProfile) -> dict[str, Any]:
754
+ cfg: dict[str, Any] = {
755
+ "project": {
756
+ "name": profile.brief_title,
757
+ "company": profile.company,
758
+ "industry": profile.industry,
759
+ "role": profile.role,
760
+ "audience": profile.audience,
761
+ },
762
+ "audience_profile": {
763
+ "id": profile.audience_profile or "default",
764
+ },
765
+ "language": {
766
+ "interface": profile.interface_language,
767
+ "output": profile.output_language,
768
+ "source_handling": profile.source_handling,
769
+ },
770
+ "report": {
771
+ "cadence": profile.cadence,
772
+ "date": "auto",
773
+ "max_source_age_days": profile.max_source_age_days,
774
+ "fail_on_stale_source": True,
775
+ },
776
+ "input": {"path": "input"},
777
+ "output": {
778
+ "path": "output",
779
+ "formats": profile.output_formats,
780
+ "filename_template": "{project_name}_{report_date}",
781
+ "named_outputs": True,
782
+ "footer": "Confidential — Internal Use Only",
783
+ },
784
+ "source": {
785
+ "mode": profile.source_profile,
786
+ "optional_seed_pack": profile.optional_seed_pack or None,
787
+ },
788
+ "pipeline": {
789
+ "steps": [
790
+ "source_collection",
791
+ "scout",
792
+ "screener",
793
+ "analyst",
794
+ "editor",
795
+ "auditor",
796
+ "formatter",
797
+ ]
798
+ },
799
+ "brief_quality": {
800
+ "min_items": 20,
801
+ "min_zh_chars": 3000,
802
+ "require_dates": True,
803
+ "allow_quiet_week_exception": False,
804
+ },
805
+ "selector": {
806
+ "enabled": True,
807
+ "max_items": profile.selector_max_items,
808
+ "require_fresh_source": True,
809
+ "topic_diversity": True,
810
+ },
811
+ "retrieval": {
812
+ "enabled": profile.retrieval_enabled,
813
+ "provider": profile.retrieval_provider,
814
+ "model": profile.retrieval_model,
815
+ "chroma_dir": ".rag/chroma",
816
+ "top_k": 5,
817
+ "lookback_days": 365,
818
+ },
819
+ "audit": {
820
+ "fail_on_missing_source": True,
821
+ "fail_on_stale_source": True,
822
+ "redaction_scan": True,
823
+ "require_claim_citations": True,
824
+ },
825
+ "safety": {
826
+ "no_investment_advice": True,
827
+ "no_legal_advice": True,
828
+ "no_trading_signals": True,
829
+ "require_human_review": True,
830
+ },
831
+ }
832
+ if profile.competitor_module_enabled:
833
+ cfg["modules"] = {
834
+ "market_competitor": {
835
+ "enabled": True,
836
+ "mode": "weekly_monitor",
837
+ "max_events": 20,
838
+ "max_events_per_entity": 4,
839
+ "universe_path": "competitor_universe.yaml",
840
+ },
841
+ }
842
+ return cfg
843
+
844
+
845
+ def build_profile(profile: InitProfile) -> dict[str, Any]:
846
+ return {
847
+ "company": profile.company,
848
+ "industry": profile.industry,
849
+ "role": profile.role,
850
+ "audience": profile.audience,
851
+ "brief_title": profile.brief_title,
852
+ "language": {
853
+ "interface": profile.interface_language,
854
+ "output": profile.output_language,
855
+ "source_handling": profile.source_handling,
856
+ },
857
+ "focus": {"areas": profile.focus_areas},
858
+ }
859
+
860
+
861
+ def build_sources(profile: InitProfile) -> dict[str, Any]:
862
+ """Generate sources.yaml content based on the selected source profile."""
863
+ sp = profile.source_profile
864
+
865
+ if sp == "llm_decide":
866
+ return _build_llm_decide_sources(profile)
867
+
868
+ # Base: always include manual local inputs
869
+ manual_sources = [
870
+ {
871
+ "name": "Local Evidence Sources",
872
+ "path": "input/sources/",
873
+ "category": "local_files",
874
+ "language": profile.output_language.split("-")[0] if "-" in profile.output_language else profile.output_language,
875
+ "enabled": True,
876
+ }
877
+ ]
878
+
879
+ # Profile-specific provider enables
880
+ if sp == "conservative":
881
+ enabled = ["manual"]
882
+ rss_enabled = False
883
+ elif sp == "aggressive_signal":
884
+ enabled = ["manual", "rss"]
885
+ rss_enabled = True
886
+ else: # research or custom
887
+ enabled = ["manual", "rss"]
888
+ rss_enabled = True
889
+
890
+ # Seed pack: use optional_seed_pack if set and registered
891
+ from multi_agent_brief.sources.industry_packs import get_industry_pack
892
+ seed_tasks = []
893
+ if profile.optional_seed_pack:
894
+ pack = get_industry_pack(profile.optional_seed_pack)
895
+ if pack:
896
+ seed_tasks = pack.get("search_tasks", [])
897
+
898
+ # web_search: add to enabled_providers if web search is enabled
899
+ web_search_mode = getattr(profile, "web_search_mode", "disabled")
900
+ if web_search_mode != "disabled":
901
+ if "web_search" not in enabled:
902
+ enabled.append("web_search")
903
+
904
+ # Build web_search config using the unified function
905
+ web_search_config = _build_web_search_config(profile)
906
+
907
+ # Add seed_tasks if available and backend is configured
908
+ if seed_tasks and web_search_config.get("mode") == "external_api":
909
+ web_search_config["search_tasks"] = seed_tasks
910
+
911
+ return {
912
+ "source_strategy": {
913
+ "profile": sp,
914
+ "industry": profile.industry_text or profile.industry,
915
+ "enabled_providers": enabled,
916
+ },
917
+ "manual": {
918
+ "enabled": True,
919
+ "sources": manual_sources,
920
+ },
921
+ "rss": {
922
+ "enabled": rss_enabled,
923
+ "feeds": [],
924
+ },
925
+ "web_search": web_search_config,
926
+ "api": {
927
+ "enabled": False,
928
+ "providers": [],
929
+ },
930
+ "mcp": {
931
+ "enabled": False,
932
+ "servers": [],
933
+ },
934
+ "filing_resolver": {
935
+ "enabled": False,
936
+ "tickers": [],
937
+ "filing_types": ["10-K", "10-Q", "8-K"],
938
+ "xbrl": True,
939
+ "note": "Disabled by default. Set enabled: true and add tickers to activate SEC filing resolution.",
940
+ },
941
+ }
942
+
943
+
944
+ def _build_web_search_config(profile: InitProfile) -> dict[str, Any]:
945
+ """Build web_search config based on web_search_mode and backend.
946
+
947
+ Three distinct states:
948
+ - disabled: user chose not to enable web search
949
+ - runtime_tool: use runtime-provided search (e.g., Claude Code, Codex)
950
+ - external_api: use configured backend (tavily, exa, brave, etc.)
951
+ - configure_later: enabled but no backend configured yet
952
+ """
953
+ # Get mode and backend from profile, with fallback to legacy tavily_enabled
954
+ mode = getattr(profile, "web_search_mode", "disabled")
955
+ backend = getattr(profile, "search_backend", "")
956
+
957
+ # Legacy compatibility: if tavily_enabled is True but mode is still disabled,
958
+ # override to external_api with tavily backend
959
+ if mode == "disabled" and getattr(profile, "tavily_enabled", False):
960
+ mode = "external_api"
961
+ if not backend:
962
+ backend = "tavily"
963
+
964
+ if mode == "disabled":
965
+ return {
966
+ "enabled": False,
967
+ "mode": "disabled",
968
+ }
969
+ elif mode == "runtime_tool":
970
+ return {
971
+ "enabled": True,
972
+ "mode": "runtime_tool",
973
+ "required_capability": "web_search",
974
+ "max_results": 10,
975
+ "recency_days": 7,
976
+ "initial_news_backfill": _build_initial_news_backfill_config(profile),
977
+ "news_source_domains": _build_news_source_domain_config(profile),
978
+ "note": "Requires the execution runtime to provide a web search tool.",
979
+ }
980
+ elif mode == "external_api" and backend:
981
+ # Configured backend (tavily, exa, brave, firecrawl, serper)
982
+ backend_info = _SEARCH_BACKENDS.get(backend, {})
983
+ config: dict[str, Any] = {
984
+ "enabled": True,
985
+ "mode": "external_api",
986
+ "backend": backend,
987
+ "api_key_env": backend_info.get("env_key", ""),
988
+ "max_results": 5,
989
+ "recency_days": 7,
990
+ "initial_news_backfill": _build_initial_news_backfill_config(profile),
991
+ "news_source_domains": _build_news_source_domain_config(profile),
992
+ }
993
+ # Add backend-specific options (only Tavily supports these)
994
+ if backend == "tavily":
995
+ config["topic"] = "news"
996
+ config["search_depth"] = "basic"
997
+ return config
998
+ else:
999
+ # configure_later: enabled but no backend configured
1000
+ return {
1001
+ "enabled": True,
1002
+ "mode": "configure_later",
1003
+ "status": "unconfigured",
1004
+ "max_results": 20,
1005
+ "recency_days": 7,
1006
+ "initial_news_backfill": _build_initial_news_backfill_config(profile),
1007
+ "news_source_domains": _build_news_source_domain_config(profile),
1008
+ "note": "Configure a search backend before running live retrieval.",
1009
+ }
1010
+
1011
+
1012
+ def _build_initial_news_backfill_config(profile: InitProfile) -> dict[str, Any]:
1013
+ return {
1014
+ "enabled": bool(getattr(profile, "initial_news_backfill_enabled", False)),
1015
+ "days": int(getattr(profile, "initial_news_backfill_days", 7) or 7),
1016
+ "daily_max_results": int(
1017
+ getattr(profile, "initial_news_backfill_daily_max_results", 20) or 20
1018
+ ),
1019
+ "mode": "daily_news_windows",
1020
+ "note": (
1021
+ "When enabled, sources decide --search expands source discovery into"
1022
+ " one user-need-customized news query per day."
1023
+ ),
1024
+ }
1025
+
1026
+
1027
+ def _build_news_source_domain_config(profile: InitProfile) -> dict[str, Any]:
1028
+ return {
1029
+ "preferred_domains": list(getattr(profile, "preferred_news_domains", []) or []),
1030
+ "excluded_domains": list(getattr(profile, "excluded_news_domains", []) or []),
1031
+ "mode": "user_configured_domains",
1032
+ "note": (
1033
+ "Optional per-workspace news source preferences. Leave empty to let"
1034
+ " the search backend discover sources from company, industry,"
1035
+ " focus areas, task objective, and audience."
1036
+ ),
1037
+ }
1038
+
1039
+
1040
+ def _build_llm_decide_sources(profile: InitProfile) -> dict[str, Any]:
1041
+ """Generate sources.yaml for llm_decide profile: agent-readable discovery policy."""
1042
+ lang = profile.output_language.split("-")[0] if "-" in profile.output_language else profile.output_language
1043
+
1044
+ # Build enabled_providers: always include manual and web_search
1045
+ enabled_providers = ["manual", "web_search"]
1046
+ # filing_resolver is available but disabled by default; enable via sources decide --merge
1047
+
1048
+ return {
1049
+ "source_strategy": {
1050
+ "profile": "llm_decide",
1051
+ "decision_mode": "agent_decide",
1052
+ "requires_agent_resolution": True,
1053
+ "optional_seed_pack": profile.optional_seed_pack or None,
1054
+ "enabled_providers": enabled_providers,
1055
+ },
1056
+ "source_discovery": {
1057
+ "instruction": (
1058
+ "Read user.md first for full user context (company, industry, role, "
1059
+ "task objective, focus areas, forbidden sources). "
1060
+ "Propose search intents and candidate sources based on user.md. "
1061
+ "Write source_candidates.yaml for user review before first ingestion."
1062
+ ),
1063
+ "company": profile.company,
1064
+ "industry": profile.industry_text or profile.industry,
1065
+ "role": profile.role,
1066
+ "task_objective": profile.task_objective,
1067
+ "audience": profile.audience,
1068
+ "focus_areas": profile.focus_areas,
1069
+ "cadence": profile.cadence,
1070
+ "max_source_age_days": profile.max_source_age_days,
1071
+ "language": lang,
1072
+ "selection_goals": [
1073
+ "official company and peer company updates",
1074
+ "regulator and policy sources",
1075
+ "industry media",
1076
+ "market data",
1077
+ "customer or demand signals",
1078
+ "competitor movements",
1079
+ ],
1080
+ "source_requirements": [
1081
+ "prefer public, citable, timestamped sources",
1082
+ "prefer sources with stable URLs or RSS feeds",
1083
+ "avoid paywalled-only sources unless user provides access",
1084
+ "avoid private, confidential, internal, or material non-public information",
1085
+ "preserve source URL, source name, source tier, and published date",
1086
+ ],
1087
+ "search_customization": {
1088
+ "derive_queries_from": [
1089
+ "company",
1090
+ "industry",
1091
+ "task_objective",
1092
+ "focus_areas",
1093
+ "audience",
1094
+ "cadence",
1095
+ ],
1096
+ "avoid_fixed_personal_or_vendor_source_lists": True,
1097
+ "daily_backfill_uses_user_need_terms": True,
1098
+ },
1099
+ "news_source_selection": {
1100
+ "selection_mode": "user_need_customized",
1101
+ "preferred_domains": list(profile.preferred_news_domains),
1102
+ "excluded_domains": list(profile.excluded_news_domains),
1103
+ "allow_backend_general_search_when_empty": True,
1104
+ "derive_domains_from": [
1105
+ "user_provided_domains",
1106
+ "industry",
1107
+ "focus_areas",
1108
+ "source_profile",
1109
+ ],
1110
+ "do_not_use_fixed_personal_domain_list": True,
1111
+ },
1112
+ "forbidden_sources": [
1113
+ "credentials",
1114
+ "private emails",
1115
+ "private chat logs",
1116
+ "internal reports",
1117
+ "customer names",
1118
+ "confidential files",
1119
+ "material non-public information",
1120
+ ] + [s for s in profile.forbidden_sources if s],
1121
+ "review_policy": {
1122
+ "require_user_confirmation_before_first_live_ingestion": True,
1123
+ "write_candidate_sources_to": "source_candidates.yaml",
1124
+ },
1125
+ },
1126
+ "manual": {
1127
+ "enabled": True,
1128
+ "sources": [
1129
+ {
1130
+ "name": "Local Input Directory",
1131
+ "path": "input/",
1132
+ "category": "local_files",
1133
+ "language": lang,
1134
+ "enabled": True,
1135
+ }
1136
+ ],
1137
+ },
1138
+ "rss": {"enabled": False, "feeds": []},
1139
+ "web_search": _build_web_search_config(profile),
1140
+ "api": {"enabled": False, "providers": []},
1141
+ "mcp": {"enabled": False, "servers": []},
1142
+ "filing_resolver": {
1143
+ "enabled": False,
1144
+ "tickers": [],
1145
+ "filing_types": ["10-K", "10-Q", "8-K"],
1146
+ "xbrl": True,
1147
+ "note": "Disabled by default. Enable via 'multi-agent-brief sources decide --merge' after reviewing source_candidates.yaml filing_sources.",
1148
+ },
1149
+ }
1150
+
1151
+
1152
+ def build_input_readme(language: str) -> str:
1153
+ if language == "zh-CN":
1154
+ return INPUT_README_ZH
1155
+ if language == "bilingual":
1156
+ return INPUT_README_ZH + "\n---\n\n" + INPUT_README_EN
1157
+ return INPUT_README_EN
1158
+
1159
+
1160
+ def _build_sources_readme(language: str) -> str:
1161
+ if language == "zh-CN":
1162
+ return (
1163
+ "# 外部证据来源\n\n"
1164
+ "将外部事实来源文件放在此目录:新闻、行业报告、SEC 文件、RSS 导出等。\n\n"
1165
+ "支持格式:`.json`(推荐)、`.md`、`.txt`\n\n"
1166
+ "此目录中的文件会被 Scout 提取为 Claim Ledger 中的事实声明。\n"
1167
+ )
1168
+ return (
1169
+ "# External Evidence Sources\n\n"
1170
+ "Place external factual source files here: news, industry reports, SEC filings, RSS exports, etc.\n\n"
1171
+ "Supported formats: `.json` (recommended), `.md`, `.txt`\n\n"
1172
+ "Files in this directory are extracted by Scout into the Claim Ledger as factual claims.\n"
1173
+ )
1174
+
1175
+
1176
+ def _build_feedback_readme(language: str) -> str:
1177
+ if language == "zh-CN":
1178
+ return (
1179
+ "# 用户批注与反馈\n\n"
1180
+ "将批注、修改意见、上一版反馈放在此目录。\n\n"
1181
+ "此目录中的文件**不会**被当作事实来源进入 Claim Ledger,\n"
1182
+ "只会作为 Editor 修改方向的参考。\n"
1183
+ )
1184
+ return (
1185
+ "# User Feedback & Annotations\n\n"
1186
+ "Place annotations, revision notes, and previous-version feedback here.\n\n"
1187
+ "Files in this directory are **NOT** treated as factual evidence for the Claim Ledger.\n"
1188
+ "They are only used as editorial direction for the Editor.\n"
1189
+ )
1190
+
1191
+
1192
+ def _build_instructions_readme(language: str) -> str:
1193
+ if language == "zh-CN":
1194
+ return (
1195
+ "# 用户任务要求\n\n"
1196
+ "将任务说明、需求文档、prompt 草稿放在此目录。\n\n"
1197
+ "此目录中的文件**不会**被当作事实来源进入 Claim Ledger,\n"
1198
+ "只会影响任务配置和报告方向。\n"
1199
+ )
1200
+ return (
1201
+ "# User Instructions\n\n"
1202
+ "Place task requirements, briefing notes, and prompt drafts here.\n\n"
1203
+ "Files in this directory are **NOT** treated as factual evidence for the Claim Ledger.\n"
1204
+ "They only influence task configuration and report direction.\n"
1205
+ )
1206
+
1207
+
1208
+ def _build_context_readme(language: str) -> str:
1209
+ if language == "zh-CN":
1210
+ return (
1211
+ "# 背景资料\n\n"
1212
+ "将背景资料、参考材料、历史数据放在此目录。\n\n"
1213
+ "如果你有往期周报、简报样例或目标版式,请优先放入 Markdown 版本,\n"
1214
+ "例如:`input/context/previous_weekly_reference.md`。\n\n"
1215
+ "此目录中的文件**不会**被当作事实来源进入 Claim Ledger,\n"
1216
+ "可作为 Analyst / Editor 写作时的结构、口吻和背景参考。\n"
1217
+ )
1218
+ return (
1219
+ "# Background Context\n\n"
1220
+ "Place background materials, reference documents, and historical data here.\n\n"
1221
+ "If you have prior weekly reports, example briefs, or target layout references,\n"
1222
+ "prefer adding a Markdown version, for example:\n"
1223
+ "`input/context/previous_weekly_reference.md`.\n\n"
1224
+ "Files in this directory are **NOT** treated as factual evidence for the Claim Ledger.\n"
1225
+ "They serve as structure, tone, and background reference for the Analyst / Editor.\n"
1226
+ )
1227
+
1228
+
1229
+ def build_user_md(profile: InitProfile) -> str:
1230
+ """Generate user.md: agent-readable briefing context, NOT source evidence."""
1231
+ lang = profile.interface_language
1232
+ focus = "\n".join(f"- {f}" for f in profile.focus_areas)
1233
+
1234
+ if lang == "zh-CN":
1235
+ return _user_md_zh(profile, focus)
1236
+ if lang == "bilingual":
1237
+ return _user_md_en(profile, focus) + "\n---\n\n" + _user_md_zh(profile, focus)
1238
+ return _user_md_en(profile, focus)
1239
+
1240
+
1241
+ def _user_md_zh(profile: InitProfile, focus: str) -> str:
1242
+ forbidden = "\n".join(f"- {s}" for s in profile.forbidden_sources) if profile.forbidden_sources else ""
1243
+ forbidden_section = f"\n## 禁止来源\n\n{forbidden}\n" if forbidden else ""
1244
+ task_section = f"\n## 任务目标\n\n{profile.task_objective}\n" if profile.task_objective else ""
1245
+ industry_raw = profile.industry_text or profile.industry
1246
+ return (
1247
+ "# 用户简报画像\n\n"
1248
+ "本文件用于帮助 agent 理解用户的简报需求。\n"
1249
+ "它不是新闻来源、不是证据来源,不应被 Scout 当作 source ingestion 输入。\n\n"
1250
+ "## 基本信息\n\n"
1251
+ f"- 公司:{profile.company}\n"
1252
+ f"- 行业:{industry_raw}\n"
1253
+ f"- 岗位:{profile.role}\n"
1254
+ f"- 阅读对象:{profile.audience}\n"
1255
+ f"- 简报标题:{profile.brief_title}\n"
1256
+ f"- 简报频率:{profile.cadence}\n"
1257
+ f"- 最大来源天数:{profile.max_source_age_days}\n"
1258
+ f"- 每期筛选条数:{profile.selector_max_items}\n"
1259
+ f"- 来源模式:{profile.source_profile}\n"
1260
+ f"- 种子包:{profile.optional_seed_pack or '无'}\n"
1261
+ f"{task_section}\n"
1262
+ "## 关注领域\n\n"
1263
+ f"{focus}\n"
1264
+ f"{forbidden_section}\n"
1265
+ "## 来源发现策略\n\n"
1266
+ "如果 source mode = llm_decide,请根据以下原则发现来源:\n\n"
1267
+ "1. 先读取本文件(user.md)理解用户的行业、岗位、任务目标和关注领域。\n"
1268
+ "2. 根据用户描述的行业和关注领域,生成搜索意图和候选来源。\n"
1269
+ "3. 优先使用公开、可引用、有发布时间的来源。\n"
1270
+ "4. 不要使用私有邮件、内部聊天记录、机密报告、客户名称、凭据、token 或重大非公开信息。\n"
1271
+ "5. 对第一次自动发现的来源,应先写入 source_candidates.yaml,等待用户确认后再进入正式 sources.yaml。\n"
1272
+ "6. 所有进入简报的事实仍必须经过 Claim Ledger 和 Auditor。\n\n"
1273
+ "## Safety\n\n"
1274
+ "This project is not investment advice, legal advice, tax advice, trading signal generation, or a replacement for human review.\n"
1275
+ )
1276
+
1277
+
1278
+ def _user_md_en(profile: InitProfile, focus: str) -> str:
1279
+ forbidden = "\n".join(f"- {s}" for s in profile.forbidden_sources) if profile.forbidden_sources else ""
1280
+ forbidden_section = f"\n## Forbidden Sources\n\n{forbidden}\n" if forbidden else ""
1281
+ task_section = f"\n## Task Objective\n\n{profile.task_objective}\n" if profile.task_objective else ""
1282
+ industry_raw = profile.industry_text or profile.industry
1283
+ return (
1284
+ "# User Briefing Profile\n\n"
1285
+ "This file describes the user/workspace context for agents.\n"
1286
+ "It is not source evidence and must not be ingested as a report source.\n\n"
1287
+ "## Basic Information\n\n"
1288
+ f"- Company: {profile.company}\n"
1289
+ f"- Industry: {industry_raw}\n"
1290
+ f"- Role: {profile.role}\n"
1291
+ f"- Audience: {profile.audience}\n"
1292
+ f"- Brief title: {profile.brief_title}\n"
1293
+ f"- Cadence: {profile.cadence}\n"
1294
+ f"- Max source age: {profile.max_source_age_days} days\n"
1295
+ f"- Max items per brief: {profile.selector_max_items}\n"
1296
+ f"- Source mode: {profile.source_profile}\n"
1297
+ f"- Seed pack: {profile.optional_seed_pack or 'none'}\n"
1298
+ f"{task_section}\n"
1299
+ "## Focus Areas\n\n"
1300
+ f"{focus}\n"
1301
+ f"{forbidden_section}\n"
1302
+ "## Source Discovery Policy\n\n"
1303
+ "If source mode = llm_decide, use these principles:\n\n"
1304
+ "1. Read this file (user.md) first to understand the user's industry, role, task objective, and focus areas.\n"
1305
+ "2. Generate search intents and candidate sources based on the user's description.\n"
1306
+ "3. Prefer public, citable, timestamped sources.\n"
1307
+ "4. Do not use private emails, chat logs, internal reports, customer names, credentials, tokens, or MNPI.\n"
1308
+ "5. Write first-discovered sources to source_candidates.yaml for user confirmation before adding to sources.yaml.\n"
1309
+ "6. All facts entering the brief must pass through Claim Ledger and Auditor.\n\n"
1310
+ "## Safety\n\n"
1311
+ "This project is not investment advice, legal advice, tax advice, trading signal generation, or a replacement for human review.\n"
1312
+ )
1313
+
1314
+
1315
+ def apply_rag_args(profile: InitProfile, rag: str | None, retrieval_provider: str | None) -> None:
1316
+ if rag:
1317
+ profile.retrieval_enabled = rag.lower() in {"on", "true", "yes", "y", "1"}
1318
+ if retrieval_provider:
1319
+ profile.retrieval_provider = retrieval_provider
1320
+ profile.retrieval_enabled = True
1321
+ profile.retrieval_model = retrieval_model_for_provider(profile.retrieval_provider)
1322
+
1323
+
1324
+ def retrieval_model_for_provider(provider: str) -> str:
1325
+ if provider == "gemini":
1326
+ return "gemini-embedding-001"
1327
+ return "nomic-embed-text"
1328
+
1329
+
1330
+ def normalize_language(value: str) -> str:
1331
+ t = value.strip().lower()
1332
+ if not t or t in ("default", "unknown", "choose for me", "默认", "不知道", "帮我选"):
1333
+ return "en-US"
1334
+ aliases = {
1335
+ "en": "en-US", "en-us": "en-US", "en_us": "en-US", "english": "en-US",
1336
+ "zh": "zh-CN", "zh-cn": "zh-CN", "zh_cn": "zh-CN", "cn": "zh-CN", "chinese": "zh-CN",
1337
+ "bilingual": "bilingual", "dual language": "bilingual",
1338
+ }
1339
+ return aliases.get(t, t)
1340
+
1341
+
1342
+ def ask_choice(
1343
+ input_func: Callable[[str], str],
1344
+ prompt: str,
1345
+ choices: dict[str, str],
1346
+ default_key: str,
1347
+ ) -> str:
1348
+ answer = input_func(prompt).strip()
1349
+ return choices.get(answer or default_key, choices[default_key])
1350
+
1351
+
1352
+ def ask_text(input_func: Callable[[str], str], prompt: str, default: str) -> str:
1353
+ answer = input_func(prompt).strip()
1354
+ return answer or default
1355
+
1356
+
1357
+ def ask_yes_no(input_func: Callable[[str], str], prompt: str, *, default: bool) -> bool:
1358
+ answer = input_func(prompt).strip().lower()
1359
+ if not answer:
1360
+ return default
1361
+ return answer in {"y", "yes", "true", "1", "on"}
1362
+
1363
+
1364
+ def parse_list_arg(value: str | None) -> list[str]:
1365
+ if not value:
1366
+ return []
1367
+ return [item.strip() for item in value.split(",") if item.strip()]
1368
+
1369
+
1370
+ def parse_int(value: str | int | None, default: int) -> int:
1371
+ try:
1372
+ return int(value) if value is not None else default
1373
+ except (TypeError, ValueError):
1374
+ return default
1375
+
1376
+
1377
+ def to_yaml(data: Any, indent: int = 0) -> str:
1378
+ lines: list[str] = []
1379
+ if isinstance(data, dict):
1380
+ for key, value in data.items():
1381
+ if isinstance(value, (dict, list)):
1382
+ lines.append(" " * indent + f"{key}:")
1383
+ lines.append(to_yaml(value, indent + 2).rstrip())
1384
+ else:
1385
+ lines.append(" " * indent + f"{key}: {format_scalar(value)}")
1386
+ elif isinstance(data, list):
1387
+ for item in data:
1388
+ if isinstance(item, dict):
1389
+ lines.append(" " * indent + "-")
1390
+ lines.append(to_yaml(item, indent + 2).rstrip())
1391
+ else:
1392
+ lines.append(" " * indent + f"- {format_scalar(item)}")
1393
+ else:
1394
+ lines.append(" " * indent + format_scalar(data))
1395
+ return "\n".join(lines) + "\n"
1396
+
1397
+
1398
+ def format_scalar(value: Any) -> str:
1399
+ if value is None:
1400
+ return "null"
1401
+ if isinstance(value, bool):
1402
+ return "true" if value else "false"
1403
+ if isinstance(value, int):
1404
+ return str(value)
1405
+ text = str(value)
1406
+ if text == "auto" or not text or any(char in text for char in [":", "#", "[", "]", "{", "}", ","]):
1407
+ return json.dumps(text, ensure_ascii=False)
1408
+ return json.dumps(text, ensure_ascii=False)
1409
+
1410
+
1411
+ def _build_competitor_universe(profile: InitProfile) -> dict:
1412
+ """Generate default competitor_universe.yaml content."""
1413
+ entities = []
1414
+ for name in profile.competitor_names:
1415
+ entities.append({
1416
+ "entity_id": name.lower().replace(" ", "_"),
1417
+ "name": name,
1418
+ "aliases": [],
1419
+ "relation": "direct_competitor",
1420
+ "priority": "secondary",
1421
+ "geographies": [],
1422
+ "technologies": [],
1423
+ })
1424
+ return {
1425
+ "target": {
1426
+ "entity_id": "",
1427
+ "name": profile.company or "",
1428
+ "aliases": [],
1429
+ "relation": "direct_competitor",
1430
+ "priority": "primary",
1431
+ "geographies": [],
1432
+ "technologies": [],
1433
+ },
1434
+ "market_scope": {
1435
+ "geographies": [],
1436
+ "products": [],
1437
+ "customer_segments": [],
1438
+ "value_chain_positions": [],
1439
+ },
1440
+ "entities": entities,
1441
+ "mode": "weekly_monitor",
1442
+ "enabled": profile.competitor_module_enabled,
1443
+ }
1444
+
1445
+
1446
+ def _build_env_example() -> str:
1447
+ """Build a .env.example file listing all supported web search backend env vars."""
1448
+ return (
1449
+ "# Web search API keys\n"
1450
+ "# Copy this file to .env and fill in the key for your chosen backend.\n"
1451
+ "# Only the backend configured in sources.yaml requires its key.\n"
1452
+ "# Never commit .env to version control.\n"
1453
+ "\n"
1454
+ "# Tavily — fast AI search (default)\n"
1455
+ "TAVILY_API_KEY=\n"
1456
+ "# Exa — deep research, papers, filings\n"
1457
+ "EXA_API_KEY=\n"
1458
+ "# Brave — independent web index\n"
1459
+ "BRAVE_SEARCH_API_KEY=\n"
1460
+ "# Firecrawl — search + full-text crawl\n"
1461
+ "FIRECRAWL_API_KEY=\n"
1462
+ "# Serper — Google SERP\n"
1463
+ "SERPER_API_KEY=\n"
1464
+ )
1465
+
1466
+
1467
+ def _write_files(files: dict[Path, str], *, force: bool) -> None:
1468
+ for path in files:
1469
+ if path.exists() and not force:
1470
+ raise FileExistsError(f"Refusing to overwrite existing file: {path}. Use --force to overwrite.")
1471
+ for path, content in files.items():
1472
+ path.parent.mkdir(parents=True, exist_ok=True)
1473
+ path.write_text(content, encoding="utf-8")