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,983 @@
1
+ """Markdown-to-DOCX converter with professional styling.
2
+
3
+ Converts Markdown documents into styled Word documents with:
4
+ - Heading hierarchy (H1-H4) with professional color scheme
5
+ - Tables (pipe and tab-separated), with wide-table fallback
6
+ - Ordered/unordered lists with nesting
7
+ - Inline formatting (bold, italic, strikethrough, code, links)
8
+ - Blockquotes, code blocks, horizontal rules
9
+ - Automatic cover page and page-numbered footer
10
+
11
+ Based on the standalone ``scripts/md_to_ib_docx.py`` script.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import re
17
+ import warnings
18
+ from pathlib import Path
19
+
20
+ from docx import Document
21
+ from docx.shared import Pt, Cm, RGBColor
22
+ from docx.enum.text import WD_ALIGN_PARAGRAPH
23
+ from docx.enum.table import WD_TABLE_ALIGNMENT, WD_ALIGN_VERTICAL
24
+ from docx.oxml.ns import qn
25
+ from docx.oxml import OxmlElement
26
+
27
+
28
+ # ── Color scheme ────────────────────────────────────────────────
29
+ COLORS = {
30
+ "primary": "003A70", # deep blue — cover / table header / emphasis
31
+ "dark": "002147", # dark navy — section headings / footer / bold
32
+ "neutral": "58595B", # medium gray — body text
33
+ "light_bg": "F2F2F2", # ice gray — alternating table rows / code bg
34
+ "negative": "9B2743", # burgundy — inline code / risk highlights
35
+ "positive": "2D6A4F", # forest green — positive signals (reserved)
36
+ }
37
+
38
+ LATIN_FONT = "Arial"
39
+ EAST_ASIA_FONT = "宋体" # 宋体
40
+
41
+ DEFAULT_FOOTER = "Generated Brief"
42
+
43
+
44
+ # ── XML helpers ─────────────────────────────────────────────────
45
+
46
+ def _hex_to_rgb(hex_str: str) -> RGBColor:
47
+ return RGBColor(*bytes.fromhex(hex_str))
48
+
49
+
50
+ def _set_cell_shading(cell, hex_color: str):
51
+ tcPr = cell._element.get_or_add_tcPr()
52
+ shd = OxmlElement("w:shd")
53
+ shd.set(qn("w:val"), "clear")
54
+ shd.set(qn("w:color"), "auto")
55
+ shd.set(qn("w:fill"), hex_color)
56
+ tcPr.append(shd)
57
+
58
+
59
+ def _set_paragraph_shading(paragraph, hex_color: str):
60
+ pPr = paragraph._p.get_or_add_pPr()
61
+ shd = OxmlElement("w:shd")
62
+ shd.set(qn("w:val"), "clear")
63
+ shd.set(qn("w:color"), "auto")
64
+ shd.set(qn("w:fill"), hex_color)
65
+ pPr.append(shd)
66
+
67
+
68
+ def _set_paragraph_left_border(paragraph, hex_color: str, size_eighths: int = 16):
69
+ pPr = paragraph._p.get_or_add_pPr()
70
+ pBdr = OxmlElement("w:pBdr")
71
+ left = OxmlElement("w:left")
72
+ left.set(qn("w:val"), "single")
73
+ left.set(qn("w:sz"), str(size_eighths))
74
+ left.set(qn("w:space"), "8")
75
+ left.set(qn("w:color"), hex_color)
76
+ pBdr.append(left)
77
+ pPr.append(pBdr)
78
+
79
+
80
+ def _set_paragraph_bottom_border(paragraph, hex_color: str, size_eighths: int = 6):
81
+ pPr = paragraph._p.get_or_add_pPr()
82
+ pBdr = OxmlElement("w:pBdr")
83
+ bottom = OxmlElement("w:bottom")
84
+ bottom.set(qn("w:val"), "single")
85
+ bottom.set(qn("w:sz"), str(size_eighths))
86
+ bottom.set(qn("w:space"), "1")
87
+ bottom.set(qn("w:color"), hex_color)
88
+ pBdr.append(bottom)
89
+ pPr.append(pBdr)
90
+
91
+
92
+ def _set_run_eastasia_font(run, font_name: str):
93
+ rPr = run._element.get_or_add_rPr()
94
+ rFonts = rPr.find(qn("w:rFonts"))
95
+ if rFonts is None:
96
+ rFonts = OxmlElement("w:rFonts")
97
+ rPr.append(rFonts)
98
+ rFonts.set(qn("w:ascii"), LATIN_FONT)
99
+ rFonts.set(qn("w:hAnsi"), LATIN_FONT)
100
+ rFonts.set(qn("w:eastAsia"), font_name)
101
+
102
+
103
+ def _set_style_eastasia_font(style, font_name: str):
104
+ rPr = style.element.get_or_add_rPr()
105
+ rFonts = rPr.find(qn("w:rFonts"))
106
+ if rFonts is None:
107
+ rFonts = OxmlElement("w:rFonts")
108
+ rPr.append(rFonts)
109
+ rFonts.set(qn("w:ascii"), LATIN_FONT)
110
+ rFonts.set(qn("w:hAnsi"), LATIN_FONT)
111
+ rFonts.set(qn("w:eastAsia"), font_name)
112
+
113
+
114
+ def _append_hyperlink(paragraph, text: str, url: str, font_name: str):
115
+ part = paragraph.part
116
+ r_id = part.relate_to(
117
+ url,
118
+ "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink",
119
+ is_external=True,
120
+ )
121
+ hyperlink = OxmlElement("w:hyperlink")
122
+ hyperlink.set(qn("r:id"), r_id)
123
+
124
+ run = OxmlElement("w:r")
125
+ r_pr = OxmlElement("w:rPr")
126
+ r_fonts = OxmlElement("w:rFonts")
127
+ r_fonts.set(qn("w:ascii"), LATIN_FONT)
128
+ r_fonts.set(qn("w:hAnsi"), LATIN_FONT)
129
+ r_fonts.set(qn("w:eastAsia"), font_name)
130
+ color = OxmlElement("w:color")
131
+ color.set(qn("w:val"), COLORS["primary"])
132
+ underline = OxmlElement("w:u")
133
+ underline.set(qn("w:val"), "single")
134
+ r_pr.extend([r_fonts, color, underline])
135
+ run.append(r_pr)
136
+
137
+ text_node = OxmlElement("w:t")
138
+ text_node.text = text
139
+ run.append(text_node)
140
+ hyperlink.append(run)
141
+ paragraph._p.append(hyperlink)
142
+
143
+
144
+ # ── Document styles ─────────────────────────────────────────────
145
+
146
+ def _setup_document_styles(doc, font_name: str):
147
+ section = doc.sections[0]
148
+ section.page_width = Cm(21)
149
+ section.page_height = Cm(29.7)
150
+ section.left_margin = Cm(3.17)
151
+ section.right_margin = Cm(3.17)
152
+ section.top_margin = Cm(2.54)
153
+ section.bottom_margin = Cm(2.54)
154
+
155
+ normal = doc.styles["Normal"]
156
+ normal.font.name = LATIN_FONT
157
+ normal.font.size = Pt(10.5)
158
+ normal.font.color.rgb = _hex_to_rgb(COLORS["neutral"])
159
+ normal.paragraph_format.space_after = Pt(6)
160
+ normal.paragraph_format.line_spacing = 1.3
161
+ _set_style_eastasia_font(normal, font_name)
162
+
163
+ heading_specs = [
164
+ (1, 17, "dark", 14, 8),
165
+ (2, 14, "primary", 12, 6),
166
+ (3, 12, "primary", 10, 4),
167
+ (4, 11, "dark", 8, 4),
168
+ ]
169
+ for level, size, color_key, before, after in heading_specs:
170
+ h = doc.styles[f"Heading {level}"]
171
+ h.font.name = LATIN_FONT
172
+ h.font.size = Pt(size)
173
+ h.font.bold = True
174
+ h.font.color.rgb = _hex_to_rgb(COLORS[color_key])
175
+ h.paragraph_format.space_before = Pt(before)
176
+ h.paragraph_format.space_after = Pt(after)
177
+ h.paragraph_format.keep_with_next = True
178
+ _set_style_eastasia_font(h, font_name)
179
+
180
+
181
+ # ── Markdown parser ─────────────────────────────────────────────
182
+
183
+ _RE_HEADING = re.compile(r"^(#{1,6})\s+(.+?)\s*#*\s*$")
184
+ _RE_TABLE_SEP = re.compile(r"^\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)+\|?\s*$")
185
+ _RE_FENCE = re.compile(r"^(\s*)(```|~~~)\s*(\S*)\s*$")
186
+ _RE_HRULE = re.compile(r"^\s*([-*_])(\s*\1){2,}\s*$")
187
+ _RE_UL = re.compile(r"^(\s*)([-*+])\s+(.+)$")
188
+ _RE_OL = re.compile(r"^(\s*)(\d+)[.)]\s+(.+)$")
189
+ _RE_QUOTE = re.compile(r"^\s*>\s?(.*)$")
190
+
191
+ # Chinese-style section headings (common in LLM Chinese reports)
192
+ _RE_CN_H2 = re.compile(r"^[一二三四五六七八九十百千]+[、..]\s*(.+)$")
193
+ _RE_CN_H3 = re.compile(r"^(\d+\.\d+)\s+(.+)$")
194
+ _RE_CN_H4 = re.compile(r"^([一二三四五六七八九十]+)\s*(.+)$")
195
+
196
+
197
+ def _is_tab_row(line: str) -> bool:
198
+ return line.count("\t") >= 2 and "|" not in line and bool(line.strip())
199
+
200
+
201
+ def _tab_rows_to_pipe(rows: list) -> tuple:
202
+ split_rows = [[c.strip() for c in r.split("\t")] for r in rows]
203
+ n = max(len(r) for r in split_rows)
204
+
205
+ def to_pipe(cells):
206
+ while len(cells) < n:
207
+ cells.append("")
208
+ return "| " + " | ".join(cells[:n]) + " |"
209
+
210
+ return [to_pipe(r) for r in split_rows], "| " + " | ".join(["---"] * n) + " |"
211
+
212
+
213
+ def _is_implicit_heading(line: str, next_line: str) -> bool:
214
+ s = line.strip()
215
+ if not s or len(s) > 15:
216
+ return False
217
+ if any(p in s for p in ",。、:;!?()()【】—…·"):
218
+ return False
219
+ return bool(next_line and (_RE_UL.match(next_line) or _RE_OL.match(next_line)))
220
+
221
+
222
+ def _is_any_heading(line: str, next_line: str) -> bool:
223
+ return bool(
224
+ _RE_HEADING.match(line)
225
+ or _RE_CN_H2.match(line)
226
+ or _RE_CN_H3.match(line)
227
+ or _RE_CN_H4.match(line)
228
+ or _is_implicit_heading(line, next_line)
229
+ )
230
+
231
+
232
+ def parse_markdown(md_text: str) -> list:
233
+ """Parse Markdown text into a list of blocks.
234
+
235
+ Supports: headings, tab/pipe tables, fenced code, blockquotes,
236
+ ordered/unordered lists (with nesting), horizontal rules,
237
+ Chinese-style section headings.
238
+ """
239
+ lines = md_text.split("\n")
240
+ blocks: list = []
241
+ i = 0
242
+ n = len(lines)
243
+
244
+ while i < n:
245
+ line = lines[i]
246
+ next_line = lines[i + 1] if i + 1 < n else ""
247
+
248
+ # blank line
249
+ if not line.strip():
250
+ i += 1
251
+ continue
252
+
253
+ # Markdown # heading
254
+ m = _RE_HEADING.match(line)
255
+ if m:
256
+ blocks.append(("heading", len(m.group(1)), m.group(2).strip()))
257
+ i += 1
258
+ continue
259
+
260
+ # Fenced code block
261
+ m = _RE_FENCE.match(line)
262
+ if m:
263
+ fence = m.group(2)
264
+ i += 1
265
+ code_lines = []
266
+ while i < n and not lines[i].strip().startswith(fence):
267
+ code_lines.append(lines[i])
268
+ i += 1
269
+ i += 1
270
+ blocks.append(("code", "\n".join(code_lines)))
271
+ continue
272
+
273
+ # Horizontal rule
274
+ if _RE_HRULE.match(line):
275
+ blocks.append(("hr",))
276
+ i += 1
277
+ continue
278
+
279
+ # Tab-separated table
280
+ if _is_tab_row(line):
281
+ tab_rows = [line]
282
+ i += 1
283
+ while i < n and _is_tab_row(lines[i]):
284
+ tab_rows.append(lines[i])
285
+ i += 1
286
+ if len(tab_rows) >= 2:
287
+ pipe_rows, sep = _tab_rows_to_pipe(tab_rows)
288
+ blocks.append(("table", pipe_rows, sep))
289
+ else:
290
+ blocks.append(("paragraph", tab_rows[0].replace("\t", " ")))
291
+ continue
292
+
293
+ # Pipe table
294
+ if "|" in line and i + 1 < n and _RE_TABLE_SEP.match(lines[i + 1]):
295
+ table_lines = [line]
296
+ sep_line = lines[i + 1]
297
+ i += 2
298
+ while i < n and "|" in lines[i] and lines[i].strip():
299
+ table_lines.append(lines[i])
300
+ i += 1
301
+ blocks.append(("table", table_lines, sep_line))
302
+ continue
303
+
304
+ # Blockquote
305
+ if _RE_QUOTE.match(line):
306
+ quote_lines = []
307
+ while i < n and _RE_QUOTE.match(lines[i]):
308
+ quote_lines.append(_RE_QUOTE.match(lines[i]).group(1))
309
+ i += 1
310
+ blocks.append(("quote", "\n".join(quote_lines).strip()))
311
+ continue
312
+
313
+ # Chinese-style headings
314
+ m = _RE_CN_H2.match(line)
315
+ if m:
316
+ blocks.append(("heading", 1, line.strip()))
317
+ i += 1
318
+ continue
319
+
320
+ m = _RE_CN_H3.match(line)
321
+ if m:
322
+ blocks.append(("heading", 3, line.strip()))
323
+ i += 1
324
+ continue
325
+
326
+ m = _RE_CN_H4.match(line)
327
+ if m:
328
+ blocks.append(("heading", 4, line.strip()))
329
+ i += 1
330
+ continue
331
+
332
+ # Table/figure caption
333
+ if re.match(r"^[表图]\s*\d+[::]\s*.+$", line.strip()):
334
+ next_real = next((lines[j] for j in range(i + 1, n) if lines[j].strip()), "")
335
+ if _is_tab_row(next_real) or ("|" in next_real):
336
+ blocks.append(("caption", line.strip()))
337
+ i += 1
338
+ continue
339
+
340
+ # Implicit heading (short line followed by list)
341
+ if _is_implicit_heading(line, next_line):
342
+ blocks.append(("heading", 3, line.strip()))
343
+ i += 1
344
+ continue
345
+
346
+ # Triangle bullet paragraph
347
+ if line.strip().startswith("▸"):
348
+ blocks.append(("paragraph", line.strip()))
349
+ i += 1
350
+ continue
351
+
352
+ # List (ordered or unordered)
353
+ if _RE_UL.match(line) or _RE_OL.match(line):
354
+ items = []
355
+ while i < n:
356
+ m_ul = _RE_UL.match(lines[i])
357
+ m_ol = _RE_OL.match(lines[i])
358
+ if m_ul:
359
+ items.append(("ul", len(m_ul.group(1).expandtabs(4)), m_ul.group(3)))
360
+ i += 1
361
+ elif m_ol:
362
+ items.append(("ol", len(m_ol.group(1).expandtabs(4)), m_ol.group(3), int(m_ol.group(2))))
363
+ i += 1
364
+ elif lines[i].startswith((" ", "\t")) and lines[i].strip() and items:
365
+ prev = items[-1]
366
+ items[-1] = (prev[0], prev[1], prev[2] + " " + lines[i].strip())
367
+ i += 1
368
+ elif not lines[i].strip():
369
+ nxt = lines[i + 1] if i + 1 < n else ""
370
+ if _RE_UL.match(nxt) or _RE_OL.match(nxt):
371
+ i += 1
372
+ else:
373
+ break
374
+ else:
375
+ break
376
+ blocks.append(("list", items))
377
+ continue
378
+
379
+ # Plain paragraph (accumulate until next block boundary)
380
+ para_lines = [line]
381
+ i += 1
382
+ while i < n:
383
+ l = lines[i]
384
+ nxt = lines[i + 1] if i + 1 < n else ""
385
+ if not l.strip():
386
+ break
387
+ if _RE_FENCE.match(l) or _RE_HRULE.match(l):
388
+ break
389
+ if _RE_UL.match(l) or _RE_OL.match(l) or _RE_QUOTE.match(l):
390
+ break
391
+ if "|" in l and i + 1 < n and _RE_TABLE_SEP.match(lines[i + 1]):
392
+ break
393
+ if _is_tab_row(l):
394
+ break
395
+ if _is_any_heading(l, nxt):
396
+ break
397
+ if re.match(r"^[表图]\s*\d+[::]\s*.+$", l.strip()):
398
+ break
399
+ para_lines.append(l)
400
+ i += 1
401
+ blocks.append(("paragraph", " ".join(p.strip() for p in para_lines)))
402
+
403
+ return blocks
404
+
405
+
406
+ # ── Inline formatting ───────────────────────────────────────────
407
+
408
+ _INLINE_PATTERN = re.compile(
409
+ r"(\*\*\*[^*\n]+?\*\*\*" # ***bold italic***
410
+ r"|___[^_\n]+?___" # ___bold italic___
411
+ r"|\*\*[^*\n]+?\*\*" # **bold**
412
+ r"|__[^_\n]+?__" # __bold__
413
+ r"|~~[^~\n]+?~~" # ~~strike~~
414
+ r"|`[^`\n]+?`" # `code`
415
+ r"|\[[^\]]+\]\((?:<[^>\n]+>|[^)\n]+)\)" # [text](url) or [text](<url>)
416
+ r"|<https?://[^>\s]+>" # <https://example.com>
417
+ r"|\*[^*\n]+?\*" # *italic*
418
+ r"|(?<!\w)_[^_\n]+?_(?!\w))" # _italic_
419
+ )
420
+
421
+
422
+ def _unwrap_inline_token(part: str) -> tuple[str, str]:
423
+ if part.startswith("***") and part.endswith("***") and len(part) > 6:
424
+ return "bold_italic", part[3:-3]
425
+ if part.startswith("___") and part.endswith("___") and len(part) > 6:
426
+ return "bold_italic", part[3:-3]
427
+ if part.startswith("**") and part.endswith("**") and len(part) > 4:
428
+ return "bold", part[2:-2]
429
+ if part.startswith("__") and part.endswith("__") and len(part) > 4:
430
+ return "bold", part[2:-2]
431
+ if part.startswith("~~") and part.endswith("~~") and len(part) > 4:
432
+ return "strike", part[2:-2]
433
+ if part.startswith("`") and part.endswith("`") and len(part) > 2:
434
+ return "code", part[1:-1]
435
+ if part.startswith("<") and part.endswith(">") and part[1:].startswith(("http://", "https://")):
436
+ return "link", part[1:-1]
437
+ if part.startswith("[") and part.endswith(")") and "](" in part:
438
+ m_link = re.match(r"\[([^\]]+)\]\((?:<([^>\n]+)>|([^)]+))\)", part)
439
+ if m_link:
440
+ return "link", m_link.group(1)
441
+ if part.startswith("*") and part.endswith("*") and len(part) > 2:
442
+ return "italic", part[1:-1]
443
+ if part.startswith("_") and part.endswith("_") and len(part) > 2:
444
+ return "italic", part[1:-1]
445
+ return "plain", part
446
+
447
+
448
+ def _inline_plain_text(text: str) -> str:
449
+ """Return inline Markdown text without formatting tokens.
450
+
451
+ Cover titles and Word heading styles are rendered as single runs, so inline
452
+ Markdown tokens there would leak as literal ``**``/``*`` text.
453
+ """
454
+ if not text:
455
+ return ""
456
+
457
+ parts: list[str] = []
458
+ for part in _INLINE_PATTERN.split(text):
459
+ if not part:
460
+ continue
461
+ _, plain = _unwrap_inline_token(part)
462
+ parts.append(plain)
463
+ return "".join(parts).strip()
464
+
465
+
466
+ def _add_inline(paragraph, text: str, font_name: str, base_color: str | None = None):
467
+ if not text:
468
+ return
469
+ parts = _INLINE_PATTERN.split(text)
470
+ for part in parts:
471
+ if not part:
472
+ continue
473
+
474
+ kind, plain = _unwrap_inline_token(part)
475
+ if kind == "bold_italic":
476
+ run = paragraph.add_run(plain)
477
+ run.bold = True
478
+ run.italic = True
479
+ run.font.color.rgb = _hex_to_rgb(COLORS["dark"])
480
+ elif kind == "bold":
481
+ run = paragraph.add_run(plain)
482
+ run.bold = True
483
+ run.font.color.rgb = _hex_to_rgb(COLORS["dark"])
484
+ elif kind == "strike":
485
+ run = paragraph.add_run(plain)
486
+ run.font.strike = True
487
+ elif kind == "code":
488
+ run = paragraph.add_run(plain)
489
+ run.font.name = LATIN_FONT
490
+ _set_run_eastasia_font(run, font_name)
491
+ run.font.size = Pt(9.5)
492
+ run.font.color.rgb = _hex_to_rgb(COLORS["negative"])
493
+ elif kind == "link":
494
+ url = _inline_link_target(part)
495
+ if url.startswith(("http://", "https://")):
496
+ _append_hyperlink(paragraph, plain, url, font_name)
497
+ continue
498
+ run = paragraph.add_run(plain)
499
+ run.font.color.rgb = _hex_to_rgb(COLORS["primary"])
500
+ run.font.underline = True
501
+ elif kind == "italic":
502
+ run = paragraph.add_run(plain)
503
+ run.italic = True
504
+ else:
505
+ run = paragraph.add_run(plain)
506
+ if base_color:
507
+ run.font.color.rgb = _hex_to_rgb(base_color)
508
+
509
+ _set_run_eastasia_font(run, font_name)
510
+
511
+
512
+ def _inline_link_target(part: str) -> str:
513
+ if part.startswith("<") and part.endswith(">"):
514
+ return part[1:-1].strip()
515
+ m_link = re.match(r"\[([^\]]+)\]\((?:<([^>\n]+)>|([^)]+))\)", part)
516
+ if not m_link:
517
+ return ""
518
+ return (m_link.group(2) or m_link.group(3) or "").strip()
519
+
520
+
521
+ # ── Block renderers ─────────────────────────────────────────────
522
+
523
+ def _parse_table_row(line: str) -> list[str]:
524
+ line = line.strip()
525
+ if line.startswith("|"):
526
+ line = line[1:]
527
+ if line.endswith("|"):
528
+ line = line[:-1]
529
+ return [c.strip() for c in line.split("|")]
530
+
531
+
532
+ def _parse_table_alignment(sep_line: str) -> list:
533
+ aligns = []
534
+ for piece in _parse_table_row(sep_line):
535
+ piece = piece.strip()
536
+ if piece.startswith(":") and piece.endswith(":"):
537
+ aligns.append(WD_ALIGN_PARAGRAPH.CENTER)
538
+ elif piece.endswith(":"):
539
+ aligns.append(WD_ALIGN_PARAGRAPH.RIGHT)
540
+ else:
541
+ aligns.append(WD_ALIGN_PARAGRAPH.LEFT)
542
+ return aligns
543
+
544
+
545
+ def _render_table(doc, table_lines, sep_line, font_name: str):
546
+ headers = _parse_table_row(table_lines[0])
547
+ if not headers:
548
+ return
549
+ if len(headers) > 4:
550
+ _render_wide_table_as_sections(doc, table_lines, sep_line, font_name)
551
+ return
552
+ n_cols = len(headers)
553
+
554
+ aligns = _parse_table_alignment(sep_line)
555
+ while len(aligns) < n_cols:
556
+ aligns.append(WD_ALIGN_PARAGRAPH.LEFT)
557
+
558
+ rows = []
559
+ for line in table_lines[1:]:
560
+ row = _parse_table_row(line)
561
+ if len(row) < n_cols:
562
+ row = row + [""] * (n_cols - len(row))
563
+ else:
564
+ row = row[:n_cols]
565
+ rows.append(row)
566
+
567
+ table = doc.add_table(rows=1 + len(rows), cols=n_cols)
568
+ table.alignment = WD_TABLE_ALIGNMENT.CENTER
569
+ table.style = "Table Grid"
570
+
571
+ # Header row
572
+ for j, h in enumerate(headers):
573
+ cell = table.rows[0].cells[j]
574
+ cell.text = ""
575
+ p = cell.paragraphs[0]
576
+ p.alignment = WD_ALIGN_PARAGRAPH.CENTER
577
+ run = p.add_run(h)
578
+ run.bold = True
579
+ run.font.size = Pt(9.5)
580
+ run.font.color.rgb = RGBColor(0xFF, 0xFF, 0xFF)
581
+ run.font.name = LATIN_FONT
582
+ _set_run_eastasia_font(run, font_name)
583
+ _set_cell_shading(cell, COLORS["primary"])
584
+ cell.vertical_alignment = WD_ALIGN_VERTICAL.CENTER
585
+
586
+ # Data rows
587
+ for i, row in enumerate(rows):
588
+ for j in range(n_cols):
589
+ cell = table.rows[i + 1].cells[j]
590
+ cell.text = ""
591
+ p = cell.paragraphs[0]
592
+ p.alignment = aligns[j]
593
+ _add_inline(p, row[j], font_name)
594
+ for run in p.runs:
595
+ if run.font.size is None:
596
+ run.font.size = Pt(9.5)
597
+ cell.vertical_alignment = WD_ALIGN_VERTICAL.CENTER
598
+ if i % 2 == 1:
599
+ _set_cell_shading(cell, COLORS["light_bg"])
600
+
601
+
602
+ def _render_wide_table_as_sections(doc, table_lines, sep_line, font_name: str):
603
+ """Render wide tables (5+ columns) as compact row sections."""
604
+ headers = _parse_table_row(table_lines[0])
605
+ rows = []
606
+ for line in table_lines[1:]:
607
+ row = _parse_table_row(line)
608
+ if len(row) < len(headers):
609
+ row = row + [""] * (len(headers) - len(row))
610
+ rows.append(row[: len(headers)])
611
+
612
+ for idx, row in enumerate(rows):
613
+ title = row[0].strip() if row else f"Item {idx + 1}"
614
+ p = doc.add_paragraph()
615
+ p.paragraph_format.space_before = Pt(6 if idx == 0 else 8)
616
+ p.paragraph_format.space_after = Pt(2)
617
+ run = p.add_run(title)
618
+ run.bold = True
619
+ run.font.size = Pt(10.5)
620
+ run.font.color.rgb = _hex_to_rgb(COLORS["dark"])
621
+ run.font.name = LATIN_FONT
622
+ _set_run_eastasia_font(run, font_name)
623
+
624
+ compact_rows = []
625
+ for header, value in zip(headers[1:], row[1:]):
626
+ value = value.strip()
627
+ if value:
628
+ compact_rows.append([header.strip(), value])
629
+ if not compact_rows:
630
+ continue
631
+ table = doc.add_table(rows=len(compact_rows), cols=2)
632
+ table.alignment = WD_TABLE_ALIGNMENT.CENTER
633
+ table.style = "Table Grid"
634
+ for r_idx, (header, value) in enumerate(compact_rows):
635
+ h_cell = table.rows[r_idx].cells[0]
636
+ v_cell = table.rows[r_idx].cells[1]
637
+ h_cell.text = ""
638
+ v_cell.text = ""
639
+ hp = h_cell.paragraphs[0]
640
+ vp = v_cell.paragraphs[0]
641
+ hr = hp.add_run(header)
642
+ hr.bold = True
643
+ hr.font.size = Pt(9.5)
644
+ hr.font.color.rgb = _hex_to_rgb(COLORS["primary"])
645
+ hr.font.name = LATIN_FONT
646
+ _set_run_eastasia_font(hr, font_name)
647
+ _add_inline(vp, value, font_name)
648
+ for run in vp.runs:
649
+ if run.font.size is None:
650
+ run.font.size = Pt(9.5)
651
+ h_cell.vertical_alignment = WD_ALIGN_VERTICAL.CENTER
652
+ v_cell.vertical_alignment = WD_ALIGN_VERTICAL.CENTER
653
+ if r_idx % 2 == 1:
654
+ _set_cell_shading(h_cell, COLORS["light_bg"])
655
+ _set_cell_shading(v_cell, COLORS["light_bg"])
656
+
657
+
658
+ _BULLETS = ["•", "○", "▪", "·", "–"]
659
+
660
+
661
+ def _render_list(doc, items, font_name: str):
662
+ if not items:
663
+ return
664
+ min_indent = min(it[1] for it in items)
665
+ counters: dict = {}
666
+ last_kind_at: dict = {}
667
+
668
+ for item in items:
669
+ kind, indent, content = item[:3]
670
+ source_number = item[3] if len(item) > 3 else None
671
+ level = max(0, min((indent - min_indent) // 2, 4))
672
+
673
+ for lvl in [k for k in counters if k > level]:
674
+ counters.pop(lvl, None)
675
+ last_kind_at.pop(lvl, None)
676
+
677
+ if last_kind_at.get(level) != kind:
678
+ counters[level] = source_number if kind == "ol" and source_number is not None else 1
679
+ last_kind_at[level] = kind
680
+
681
+ if kind == "ol":
682
+ number = source_number if source_number is not None else counters[level]
683
+ label = f"{number}. "
684
+ counters[level] = number + 1
685
+ else:
686
+ label = _BULLETS[level % len(_BULLETS)] + " "
687
+
688
+ p = doc.add_paragraph()
689
+ p.paragraph_format.left_indent = Cm(0.5 + level * 0.6)
690
+ p.paragraph_format.first_line_indent = Cm(-0.5)
691
+ p.paragraph_format.space_after = Pt(2)
692
+ p.paragraph_format.line_spacing = 1.3
693
+
694
+ bullet_run = p.add_run(label)
695
+ bullet_run.font.name = LATIN_FONT
696
+ bullet_run.font.size = Pt(10.5)
697
+ if kind == "ol":
698
+ bullet_run.font.color.rgb = _hex_to_rgb(COLORS["primary"])
699
+ bullet_run.bold = True
700
+ _set_run_eastasia_font(bullet_run, font_name)
701
+
702
+ _add_inline(p, content, font_name)
703
+
704
+
705
+ def _render_caption(doc, text: str, font_name: str):
706
+ p = doc.add_paragraph()
707
+ p.paragraph_format.space_before = Pt(8)
708
+ p.paragraph_format.space_after = Pt(2)
709
+ run = p.add_run(text)
710
+ run.font.size = Pt(9.5)
711
+ run.font.italic = True
712
+ run.font.color.rgb = _hex_to_rgb(COLORS["neutral"])
713
+ run.font.name = LATIN_FONT
714
+ _set_run_eastasia_font(run, font_name)
715
+
716
+
717
+ def _render_code_block(doc, code: str, font_name: str):
718
+ p = doc.add_paragraph()
719
+ p.paragraph_format.space_before = Pt(4)
720
+ p.paragraph_format.space_after = Pt(4)
721
+ p.paragraph_format.left_indent = Cm(0.4)
722
+ p.paragraph_format.line_spacing = 1.15
723
+ _set_paragraph_shading(p, COLORS["light_bg"])
724
+ run = p.add_run(code)
725
+ run.font.name = LATIN_FONT
726
+ _set_run_eastasia_font(run, font_name)
727
+ run.font.size = Pt(9)
728
+ run.font.color.rgb = _hex_to_rgb(COLORS["dark"])
729
+
730
+
731
+ def _render_quote(doc, text: str, font_name: str):
732
+ p = doc.add_paragraph()
733
+ p.paragraph_format.left_indent = Cm(0.5)
734
+ p.paragraph_format.space_before = Pt(4)
735
+ p.paragraph_format.space_after = Pt(4)
736
+ _set_paragraph_left_border(p, COLORS["primary"])
737
+ _add_inline(p, text, font_name, base_color=COLORS["neutral"])
738
+
739
+
740
+ def _render_hr(doc):
741
+ p = doc.add_paragraph()
742
+ p.paragraph_format.space_before = Pt(6)
743
+ p.paragraph_format.space_after = Pt(6)
744
+ _set_paragraph_bottom_border(p, COLORS["primary"])
745
+
746
+
747
+ # ── Cover / footer ──────────────────────────────────────────────
748
+
749
+ def _add_cover(doc, title: str, subtitle: str | None, font_name: str):
750
+ p = doc.add_paragraph()
751
+ p.alignment = WD_ALIGN_PARAGRAPH.CENTER
752
+ p.paragraph_format.space_before = Pt(12)
753
+ p.paragraph_format.space_after = Pt(8)
754
+ run = p.add_run(title)
755
+ run.font.size = Pt(22)
756
+ run.font.bold = True
757
+ run.font.color.rgb = _hex_to_rgb(COLORS["primary"])
758
+ run.font.name = LATIN_FONT
759
+ _set_run_eastasia_font(run, font_name)
760
+
761
+ if subtitle:
762
+ p2 = doc.add_paragraph()
763
+ p2.alignment = WD_ALIGN_PARAGRAPH.CENTER
764
+ p2.paragraph_format.space_after = Pt(12)
765
+ sr = p2.add_run(subtitle)
766
+ sr.font.size = Pt(11)
767
+ sr.font.color.rgb = _hex_to_rgb(COLORS["neutral"])
768
+ sr.font.italic = True
769
+ sr.font.name = LATIN_FONT
770
+ _set_run_eastasia_font(sr, font_name)
771
+
772
+ _render_hr(doc)
773
+
774
+
775
+ def _add_page_field(paragraph):
776
+ run = paragraph.add_run()
777
+ fld_char_begin = OxmlElement("w:fldChar")
778
+ fld_char_begin.set(qn("w:fldCharType"), "begin")
779
+ instr_text = OxmlElement("w:instrText")
780
+ instr_text.set(qn("xml:space"), "preserve")
781
+ instr_text.text = "PAGE"
782
+ fld_char_separate = OxmlElement("w:fldChar")
783
+ fld_char_separate.set(qn("w:fldCharType"), "separate")
784
+ text = OxmlElement("w:t")
785
+ text.text = "1"
786
+ fld_char_end = OxmlElement("w:fldChar")
787
+ fld_char_end.set(qn("w:fldCharType"), "end")
788
+ run._r.append(fld_char_begin)
789
+ run._r.append(instr_text)
790
+ run._r.append(fld_char_separate)
791
+ run._r.append(text)
792
+ run._r.append(fld_char_end)
793
+
794
+
795
+ def _add_footer(doc, footer_text: str | None, font_name: str):
796
+ footer = doc.sections[0].footer
797
+ fp = footer.paragraphs[0]
798
+ fp.alignment = WD_ALIGN_PARAGRAPH.CENTER
799
+ text = footer_text or DEFAULT_FOOTER
800
+ run = fp.add_run(text + " | ")
801
+ run.font.size = Pt(8)
802
+ run.font.color.rgb = _hex_to_rgb(COLORS["dark"])
803
+ run.font.name = LATIN_FONT
804
+ _set_run_eastasia_font(run, font_name)
805
+ _add_page_field(fp)
806
+
807
+
808
+ # ── Quality check ───────────────────────────────────────────────
809
+
810
+ def _check_input_quality(md_text: str):
811
+ if "�" in md_text:
812
+ n = md_text.count("�")
813
+ warnings.warn(
814
+ f"Input Markdown contains {n} U+FFFD replacement characters. "
815
+ f"Source text was corrupted upstream — this tool preserves them as-is.",
816
+ stacklevel=2,
817
+ )
818
+
819
+
820
+ # ── Public API ──────────────────────────────────────────────────
821
+
822
+ def convert(
823
+ md_path: str | Path,
824
+ docx_path: str | Path,
825
+ *,
826
+ title: str | None = None,
827
+ subtitle: str | None = None,
828
+ footer: str | None = None,
829
+ font: str | None = None,
830
+ template: str = "default",
831
+ ) -> Path:
832
+ """Convert a Markdown file to a styled DOCX document.
833
+
834
+ Args:
835
+ md_path: Path to the input Markdown file.
836
+ docx_path: Path for the output .docx file.
837
+ title: Document title. If *None*, extracted from the first ``#`` heading.
838
+ subtitle: Optional subtitle/date line below the title.
839
+ footer: Footer text. Defaults to ``"Generated Brief"``.
840
+ font: East-Asian font name. Defaults to ``宋体``.
841
+ template: Template ID (executive_brief, research_note, formal_internal_report).
842
+ Defaults to "default" which uses the standard style.
843
+
844
+ Returns:
845
+ The *docx_path* as a :class:`~pathlib.Path`.
846
+ """
847
+ md_text = Path(md_path).read_text(encoding="utf-8")
848
+ _check_input_quality(md_text)
849
+
850
+ # Load template configuration if not default
851
+ template_config = None
852
+ if template and template != "default":
853
+ from multi_agent_brief.outputs.templates import get_template
854
+ template_config = get_template(template)
855
+
856
+ if title is None:
857
+ m = re.search(r"^#\s+(.+)$", md_text, re.MULTILINE)
858
+ if m:
859
+ title = _inline_plain_text(m.group(1).strip())
860
+ else:
861
+ for line in md_text.splitlines():
862
+ line = line.strip()
863
+ if line and not line.startswith("---"):
864
+ title = _inline_plain_text(line)
865
+ break
866
+ else:
867
+ title = Path(md_path).stem
868
+ else:
869
+ title = _inline_plain_text(title)
870
+
871
+ if font is None:
872
+ font = EAST_ASIA_FONT
873
+
874
+ doc = Document()
875
+
876
+ # Apply template-specific styles if configured
877
+ if template_config:
878
+ _setup_document_styles_with_template(doc, font, template_config)
879
+ else:
880
+ _setup_document_styles(doc, font)
881
+
882
+ # Cover page - use template footer if configured
883
+ effective_footer = footer
884
+ if template_config and not footer:
885
+ effective_footer = template_config.footer_text
886
+
887
+ _add_cover(doc, title, subtitle, font)
888
+
889
+ # Remove the title line from body to avoid duplication with cover
890
+ body_lines = md_text.splitlines()
891
+ for idx, line in enumerate(body_lines):
892
+ if not line.strip():
893
+ continue
894
+ if _inline_plain_text(line.strip().lstrip("#").strip()) == title:
895
+ body_lines.pop(idx)
896
+ break
897
+
898
+ blocks = parse_markdown("\n".join(body_lines))
899
+ skipped_title_block = False
900
+ for block in blocks:
901
+ btype = block[0]
902
+ if btype == "heading":
903
+ level, text = block[1], _inline_plain_text(block[2])
904
+ if not skipped_title_block and text == title:
905
+ skipped_title_block = True
906
+ continue
907
+ if re.match(r"^[一二三四五六七八九十]+[、..]", text.strip()):
908
+ level = 1
909
+ doc.add_heading(text, level=min(level, 4))
910
+ elif btype == "paragraph":
911
+ if not skipped_title_block and _inline_plain_text(block[1].strip()) == title:
912
+ skipped_title_block = True
913
+ continue
914
+ p = doc.add_paragraph()
915
+ _add_inline(p, block[1], font)
916
+ elif btype == "list":
917
+ _render_list(doc, block[1], font)
918
+ elif btype == "table":
919
+ _render_table(doc, block[1], block[2], font)
920
+ elif btype == "code":
921
+ _render_code_block(doc, block[1], font)
922
+ elif btype == "caption":
923
+ _render_caption(doc, block[1], font)
924
+ elif btype == "quote":
925
+ _render_quote(doc, block[1], font)
926
+ elif btype == "hr":
927
+ _render_hr(doc)
928
+
929
+ # Add disclaimer if template requires it
930
+ if template_config and template_config.show_disclaimer and template_config.disclaimer_text:
931
+ doc.add_paragraph() # spacing
932
+ p = doc.add_paragraph()
933
+ p.paragraph_format.space_before = Pt(12)
934
+ _set_paragraph_left_border(p, COLORS["neutral"])
935
+ run = p.add_run(template_config.disclaimer_text)
936
+ run.font.size = Pt(8)
937
+ run.font.italic = True
938
+ run.font.color.rgb = _hex_to_rgb(COLORS["neutral"])
939
+ run.font.name = LATIN_FONT
940
+ _set_run_eastasia_font(run, font)
941
+
942
+ _add_footer(doc, effective_footer, font)
943
+
944
+ out = Path(docx_path)
945
+ out.parent.mkdir(parents=True, exist_ok=True)
946
+ doc.save(str(out))
947
+ return out
948
+
949
+
950
+ def _setup_document_styles_with_template(doc, font_name: str, template_config) -> None:
951
+ """Set up document styles with template-specific overrides."""
952
+ section = doc.sections[0]
953
+ section.page_width = Cm(21)
954
+ section.page_height = Cm(29.7)
955
+ section.left_margin = Cm(3.17)
956
+ section.right_margin = Cm(3.17)
957
+ section.top_margin = Cm(2.54)
958
+ section.bottom_margin = Cm(2.54)
959
+
960
+ normal = doc.styles["Normal"]
961
+ normal.font.name = LATIN_FONT
962
+ normal.font.size = Pt(template_config.body_font_size)
963
+ normal.font.color.rgb = _hex_to_rgb(COLORS["neutral"])
964
+ normal.paragraph_format.space_after = Pt(6)
965
+ normal.paragraph_format.line_spacing = template_config.line_spacing
966
+ _set_style_eastasia_font(normal, font_name)
967
+
968
+ heading_specs = [
969
+ (1, template_config.heading_font_size_h1, "dark", 14, 8),
970
+ (2, template_config.heading_font_size_h2, "primary", 12, 6),
971
+ (3, 12, "primary", 10, 4),
972
+ (4, 11, "dark", 8, 4),
973
+ ]
974
+ for level, size, color_key, before, after in heading_specs:
975
+ h = doc.styles[f"Heading {level}"]
976
+ h.font.name = LATIN_FONT
977
+ h.font.size = Pt(size)
978
+ h.font.bold = True
979
+ h.font.color.rgb = _hex_to_rgb(COLORS[color_key])
980
+ h.paragraph_format.space_before = Pt(before)
981
+ h.paragraph_format.space_after = Pt(after)
982
+ h.paragraph_format.keep_with_next = True
983
+ _set_style_eastasia_font(h, font_name)