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,942 @@
1
+ """deliver — show or send finalized reader delivery artifacts."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import hashlib
7
+ import json
8
+ import re
9
+ import sys
10
+ from dataclasses import dataclass
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+ from multi_agent_brief.delivery.base import DeliveryArtifact, DeliveryResult, DeliveryTarget
15
+ from multi_agent_brief.delivery.feishu import FeishuDeliveryConnector
16
+ from multi_agent_brief.delivery.gws import GwsGmailDeliveryConnector
17
+ from multi_agent_brief.orchestrator.runtime_state import (
18
+ E_ACTIVE_REPAIR_OPEN,
19
+ E_RUNTIME_STATE_NOT_INITIALIZED,
20
+ RuntimeStateError,
21
+ append_event,
22
+ check_runtime_state,
23
+ raise_if_active_repair_open,
24
+ read_event_log_records_strict,
25
+ runtime_state_paths,
26
+ )
27
+ from multi_agent_brief.orchestrator.run_integrity import (
28
+ interpret_run_integrity,
29
+ project_for_read,
30
+ workflow_with_sticky_contamination_events,
31
+ )
32
+ from multi_agent_brief.outputs.reader_final_gate import (
33
+ combine_reader_final_gate_results,
34
+ detect_reader_residue,
35
+ detect_reader_residue_in_docx,
36
+ )
37
+ from multi_agent_brief.product.policy_gate_adapter import (
38
+ policy_forbidden_phrases,
39
+ resolve_workspace_policy_gate_adapter,
40
+ )
41
+
42
+
43
+ E_DELIVERY_BUNDLE_MISSING = "E_DELIVERY_BUNDLE_MISSING"
44
+ E_DELIVERY_NOT_CLEAN = "E_DELIVERY_NOT_CLEAN"
45
+ E_DELIVERY_FAILED = "E_DELIVERY_FAILED"
46
+ E_DELIVERY_EVENT_FAILED = "E_DELIVERY_EVENT_FAILED"
47
+ E_DELIVERY_RUNTIME_MISSING = "E_DELIVERY_RUNTIME_MISSING"
48
+ E_DELIVERY_TARGET_INVALID = "E_DELIVERY_TARGET_INVALID"
49
+ E_DELIVERY_ARTIFACT_MISMATCH = "E_DELIVERY_ARTIFACT_MISMATCH"
50
+ E_DELIVERY_RUN_INTEGRITY_BLOCKED = "E_DELIVERY_RUN_INTEGRITY_BLOCKED"
51
+
52
+ _RECIPIENT_ID_RE = re.compile(r"\b(?:oc|ou|on|om|cli|fld|f)[A-Za-z0-9_-]{8,}\b")
53
+ _LONG_TOKEN_RE = re.compile(r"\b[A-Za-z0-9][A-Za-z0-9_-]{23,}\b")
54
+
55
+
56
+ @dataclass(frozen=True)
57
+ class DeliveryBundle:
58
+ workspace: Path
59
+ artifacts: list[Path]
60
+ markdown: Path | None
61
+ docx: Path | None
62
+ artifact_sha256: dict[str, str]
63
+
64
+ def relative_artifacts(self) -> list[str]:
65
+ return [_workspace_relative(self.workspace, path) for path in self.artifacts]
66
+
67
+
68
+ class DeliverCommandError(Exception):
69
+ def __init__(
70
+ self,
71
+ message: str,
72
+ *,
73
+ error_code: str,
74
+ target: str = "",
75
+ channel: str = "",
76
+ delivered: bool = False,
77
+ extra: dict[str, Any] | None = None,
78
+ ) -> None:
79
+ super().__init__(message)
80
+ self.error_code = error_code
81
+ self.target = target
82
+ self.channel = channel
83
+ self.delivered = delivered
84
+ self.extra = extra or {}
85
+
86
+ def to_payload(self) -> dict[str, Any]:
87
+ payload: dict[str, Any] = {
88
+ "ok": False,
89
+ "error_code": self.error_code,
90
+ "target": self.target,
91
+ "channel": self.channel,
92
+ "delivered": self.delivered,
93
+ "message": str(self),
94
+ }
95
+ payload.update(self.extra)
96
+ return payload
97
+
98
+
99
+ def register(subparsers: argparse._SubParsersAction) -> None:
100
+ parser = subparsers.add_parser(
101
+ "deliver",
102
+ help="Show or send finalized reader delivery artifacts.",
103
+ )
104
+ parser.add_argument("--workspace", required=True, help="Path to workspace directory.")
105
+ parser.add_argument(
106
+ "--target",
107
+ choices=("local", "feishu", "gmail"),
108
+ default="local",
109
+ help="Delivery target. Defaults to local.",
110
+ )
111
+ parser.add_argument(
112
+ "--channel",
113
+ choices=("doc", "drive", "chat", "draft", "send"),
114
+ help="Delivery channel. Feishu: doc|drive|chat. Gmail: draft|send.",
115
+ )
116
+ parser.add_argument(
117
+ "--recipient",
118
+ help="Feishu folder token/chat id or Gmail recipient. Event metadata stores only recipient_present and recipient_sha256.",
119
+ )
120
+ parser.add_argument("--subject", help="Gmail subject. Defaults to the delivery title.")
121
+ parser.add_argument("--body", help="Gmail body. Defaults to a short delivery note and brief excerpt.")
122
+ parser.add_argument("--json", action="store_true", help="Emit machine-readable JSON.")
123
+
124
+
125
+ def handle(args: argparse.Namespace) -> int:
126
+ target = getattr(args, "target", "local") or "local"
127
+ channel = getattr(args, "channel", None) or ("local" if target == "local" else "")
128
+ try:
129
+ payload = deliver_workspace(
130
+ workspace=args.workspace,
131
+ target=target,
132
+ channel=channel,
133
+ recipient=getattr(args, "recipient", None) or "",
134
+ subject=getattr(args, "subject", None) or "",
135
+ body=getattr(args, "body", None) or "",
136
+ )
137
+ except DeliverCommandError as exc:
138
+ payload = exc.to_payload()
139
+ payload["target"] = payload.get("target") or target
140
+ payload["channel"] = payload.get("channel") or channel
141
+ if getattr(args, "json", False):
142
+ print(json.dumps(payload, ensure_ascii=False, indent=2, sort_keys=True))
143
+ else:
144
+ print(f"[deliver] Error: {exc}", file=sys.stderr)
145
+ return 1
146
+
147
+ if getattr(args, "json", False):
148
+ print(json.dumps(payload, ensure_ascii=False, indent=2, sort_keys=True))
149
+ elif target == "local":
150
+ print("[deliver] Delivery bundle ready:")
151
+ for artifact in payload["delivery_artifacts"]:
152
+ print(f" - {artifact}")
153
+ print("[deliver] Internal audit/control records remain under output/intermediate/.")
154
+ _print_run_integrity_warning(payload)
155
+ elif target == "gmail":
156
+ if payload.get("sent"):
157
+ print(f"[deliver] Gmail message sent for {payload['artifact']}")
158
+ else:
159
+ print(f"[deliver] Gmail draft created for {payload['artifact']}")
160
+ _print_run_integrity_warning(payload)
161
+ else:
162
+ suffix = f" {payload['channel']}" if payload.get("channel") else ""
163
+ url = payload.get("url") or ""
164
+ if url:
165
+ print(f"[deliver] Delivered to {payload['target']}{suffix}: {url}")
166
+ else:
167
+ print(f"[deliver] Delivered to {payload['target']}{suffix}: {payload['artifact']}")
168
+ if payload.get("event_recorded") is False:
169
+ print(
170
+ "[deliver] Warning: delivery succeeded but delivery_succeeded event was not recorded; do not retry blindly.",
171
+ file=sys.stderr,
172
+ )
173
+ _print_run_integrity_warning(payload)
174
+ return 0
175
+
176
+
177
+ def deliver_workspace(
178
+ *,
179
+ workspace: str | Path,
180
+ target: str = "local",
181
+ channel: str = "",
182
+ recipient: str = "",
183
+ subject: str = "",
184
+ body: str = "",
185
+ ) -> dict[str, Any]:
186
+ ws = _require_workspace(workspace)
187
+ bundle = _load_delivery_bundle(ws)
188
+ _verify_current_delivery_artifacts(bundle)
189
+ _preflight_delivery_event_surface(ws)
190
+ _preflight_no_active_repair(ws, target=target, channel=channel)
191
+ _refresh_runtime_state_before_delivery(ws, target=target, channel=channel)
192
+ run_integrity = _delivery_run_integrity(ws)
193
+ _preflight_run_integrity_for_delivery(
194
+ run_integrity,
195
+ target=target,
196
+ channel=channel,
197
+ )
198
+
199
+ if target == "local":
200
+ artifact = bundle.markdown or bundle.artifacts[0]
201
+ _record_delivery_event(
202
+ ws,
203
+ event_type="delivery_attempted",
204
+ target="local",
205
+ channel="local",
206
+ artifact=artifact,
207
+ recipient=recipient,
208
+ )
209
+ _record_delivery_event(
210
+ ws,
211
+ event_type="delivery_succeeded",
212
+ target="local",
213
+ channel="local",
214
+ artifact=artifact,
215
+ recipient=recipient,
216
+ )
217
+ return {
218
+ "ok": True,
219
+ "target": "local",
220
+ "channel": "local",
221
+ "artifact": _workspace_relative(ws, artifact),
222
+ "delivery_artifacts": bundle.relative_artifacts(),
223
+ "delivered": False,
224
+ "message": "Delivery bundle ready",
225
+ "run_integrity": run_integrity,
226
+ }
227
+
228
+ if target == "gmail":
229
+ return _deliver_gmail(
230
+ ws,
231
+ bundle=bundle,
232
+ channel=channel,
233
+ recipient=recipient,
234
+ subject=subject,
235
+ body=body,
236
+ run_integrity=run_integrity,
237
+ )
238
+
239
+ if target != "feishu":
240
+ raise DeliverCommandError(
241
+ f"Unsupported delivery target: {target}",
242
+ error_code=E_DELIVERY_TARGET_INVALID,
243
+ target=target,
244
+ channel=channel,
245
+ )
246
+ if channel not in {"doc", "drive", "chat"}:
247
+ raise DeliverCommandError(
248
+ "Feishu delivery requires --channel doc|drive|chat.",
249
+ error_code=E_DELIVERY_TARGET_INVALID,
250
+ target=target,
251
+ channel=channel,
252
+ )
253
+ if not recipient:
254
+ raise DeliverCommandError(
255
+ "Feishu delivery requires --recipient.",
256
+ error_code=E_DELIVERY_TARGET_INVALID,
257
+ target=target,
258
+ channel=channel,
259
+ )
260
+
261
+ artifact = _select_feishu_artifact(bundle, channel)
262
+ _record_delivery_event(
263
+ ws,
264
+ event_type="delivery_attempted",
265
+ target=target,
266
+ channel=channel,
267
+ artifact=artifact,
268
+ recipient=recipient,
269
+ )
270
+
271
+ result = FeishuDeliveryConnector().deliver(
272
+ DeliveryArtifact(path=str(artifact), title=artifact.stem),
273
+ DeliveryTarget(channel=channel, recipient=recipient),
274
+ )
275
+ final_event = "delivery_succeeded" if result.delivered else "delivery_failed"
276
+ event_recorded = True
277
+ event_error = ""
278
+ try:
279
+ _record_delivery_event(
280
+ ws,
281
+ event_type=final_event,
282
+ target=target,
283
+ channel=channel,
284
+ artifact=artifact,
285
+ recipient=recipient,
286
+ url=str(result.metadata.get("url") or ""),
287
+ )
288
+ except DeliverCommandError as exc:
289
+ event_recorded = False
290
+ event_error = str(exc)
291
+ if not result.delivered:
292
+ raise
293
+ if not result.delivered:
294
+ raise DeliverCommandError(
295
+ _safe_delivery_message(result, channel, recipient=recipient),
296
+ error_code=E_DELIVERY_FAILED,
297
+ target=target,
298
+ channel=channel,
299
+ )
300
+
301
+ return {
302
+ "ok": True,
303
+ "target": target,
304
+ "channel": channel,
305
+ "artifact": _workspace_relative(ws, artifact),
306
+ "delivered": True,
307
+ "message": _safe_delivery_message(result, channel, recipient=recipient),
308
+ "url": str(result.metadata.get("url") or ""),
309
+ "event_recorded": event_recorded,
310
+ "event_error": event_error,
311
+ "run_integrity": run_integrity,
312
+ }
313
+
314
+
315
+ def _deliver_gmail(
316
+ workspace: Path,
317
+ *,
318
+ bundle: DeliveryBundle,
319
+ channel: str,
320
+ recipient: str,
321
+ subject: str,
322
+ body: str,
323
+ run_integrity: dict[str, Any],
324
+ ) -> dict[str, Any]:
325
+ if channel not in {"draft", "send"}:
326
+ raise DeliverCommandError(
327
+ "Gmail delivery requires --channel draft|send.",
328
+ error_code=E_DELIVERY_TARGET_INVALID,
329
+ target="gmail",
330
+ channel=channel,
331
+ )
332
+ if not recipient:
333
+ raise DeliverCommandError(
334
+ "Gmail delivery requires --recipient.",
335
+ error_code=E_DELIVERY_TARGET_INVALID,
336
+ target="gmail",
337
+ channel=channel,
338
+ )
339
+
340
+ artifact = _select_gmail_attachment(bundle)
341
+ markdown = bundle.markdown
342
+ gmail_subject = subject.strip() or _default_gmail_subject(bundle)
343
+ gmail_body = body.strip() or _default_gmail_body(bundle)
344
+ _record_delivery_event(
345
+ workspace,
346
+ event_type="delivery_attempted",
347
+ target="gmail",
348
+ channel=channel,
349
+ artifact=artifact,
350
+ recipient=recipient,
351
+ )
352
+ result = GwsGmailDeliveryConnector().deliver(
353
+ DeliveryArtifact(path=str(artifact), title=artifact.stem),
354
+ DeliveryTarget(
355
+ channel=channel,
356
+ recipient=recipient,
357
+ metadata={
358
+ "subject": gmail_subject,
359
+ "body": gmail_body,
360
+ "attachments": [str(artifact)],
361
+ "markdown": str(markdown) if markdown else "",
362
+ },
363
+ ),
364
+ )
365
+ final_event = _gmail_success_event(channel) if result.delivered else "delivery_failed"
366
+ event_recorded = True
367
+ event_error = ""
368
+ try:
369
+ _record_delivery_event(
370
+ workspace,
371
+ event_type=final_event,
372
+ target="gmail",
373
+ channel=channel,
374
+ artifact=artifact,
375
+ recipient=recipient,
376
+ metadata=_gmail_event_metadata(channel, result),
377
+ )
378
+ except DeliverCommandError as exc:
379
+ event_recorded = False
380
+ event_error = str(exc)
381
+ if not result.delivered:
382
+ raise
383
+ side_effect = "Gmail draft was created" if channel == "draft" else "Gmail message was sent"
384
+ inspect_target = "Gmail Drafts" if channel == "draft" else "Gmail Sent Mail"
385
+ raise DeliverCommandError(
386
+ f"{side_effect} but {_gmail_success_event(channel)} event was not recorded. "
387
+ f"Inspect {inspect_target} before retrying; do not retry blindly.",
388
+ error_code=E_DELIVERY_EVENT_FAILED,
389
+ target="gmail",
390
+ channel=channel,
391
+ extra={
392
+ "artifact": _workspace_relative(workspace, artifact),
393
+ "draft_created": channel == "draft",
394
+ "sent": channel == "send",
395
+ "event_recorded": event_recorded,
396
+ "event_error": event_error,
397
+ "run_integrity": run_integrity,
398
+ },
399
+ ) from exc
400
+ if not result.delivered:
401
+ fallback = "Gmail draft creation failed" if channel == "draft" else "Gmail send failed"
402
+ extra: dict[str, Any] = {}
403
+ if result.metadata.get("outcome_unknown"):
404
+ extra = {
405
+ "artifact": _workspace_relative(workspace, artifact),
406
+ "draft_created": False,
407
+ "sent": False,
408
+ "event_recorded": event_recorded,
409
+ "event_error": event_error,
410
+ "outcome_unknown": True,
411
+ "inspect_target": result.metadata.get("inspect_target") or (
412
+ "Gmail Drafts" if channel == "draft" else "Gmail Sent Mail"
413
+ ),
414
+ "run_integrity": run_integrity,
415
+ }
416
+ raise DeliverCommandError(
417
+ _sanitize_delivery_message(result.message or fallback, recipient=recipient),
418
+ error_code=E_DELIVERY_FAILED,
419
+ target="gmail",
420
+ channel=channel,
421
+ extra=extra,
422
+ )
423
+ return {
424
+ "ok": True,
425
+ "target": "gmail",
426
+ "channel": channel,
427
+ "artifact": _workspace_relative(workspace, artifact),
428
+ "delivered": channel == "send",
429
+ "draft_created": channel == "draft",
430
+ "sent": channel == "send",
431
+ "message": "Gmail draft created" if channel == "draft" else "Gmail message sent",
432
+ "event_recorded": event_recorded,
433
+ "event_error": event_error,
434
+ "run_integrity": run_integrity,
435
+ }
436
+
437
+
438
+ def _gmail_success_event(channel: str) -> str:
439
+ return "delivery_draft_created" if channel == "draft" else "delivery_succeeded"
440
+
441
+
442
+ def _gmail_event_metadata(channel: str, result: DeliveryResult) -> dict[str, Any]:
443
+ if channel == "draft":
444
+ metadata = {"draft_id_present": bool(result.metadata.get("draft_id_present"))}
445
+ else:
446
+ metadata = {"sent_message_present": bool(result.metadata.get("sent_message_present"))}
447
+ if result.metadata.get("outcome_unknown"):
448
+ metadata["outcome_unknown"] = True
449
+ metadata["timeout"] = bool(result.metadata.get("timeout"))
450
+ metadata["inspect_target"] = result.metadata.get("inspect_target") or (
451
+ "Gmail Drafts" if channel == "draft" else "Gmail Sent Mail"
452
+ )
453
+ return metadata
454
+
455
+
456
+ def _require_workspace(workspace: str | Path) -> Path:
457
+ ws = Path(workspace).expanduser().resolve()
458
+ if not (ws / "config.yaml").exists():
459
+ raise DeliverCommandError(
460
+ f"Workspace config.yaml not found: {ws / 'config.yaml'}",
461
+ error_code=E_DELIVERY_BUNDLE_MISSING,
462
+ )
463
+ return ws
464
+
465
+
466
+ def _load_delivery_bundle(workspace: Path) -> DeliveryBundle:
467
+ report_path = workspace / "output" / "intermediate" / "finalize_report.json"
468
+ if not report_path.exists():
469
+ raise DeliverCommandError(
470
+ "Delivery bundle is missing. Run: multi-agent-brief finalize --config <workspace>/config.yaml",
471
+ error_code=E_DELIVERY_BUNDLE_MISSING,
472
+ )
473
+ try:
474
+ report = json.loads(report_path.read_text(encoding="utf-8"))
475
+ except json.JSONDecodeError as exc:
476
+ raise DeliverCommandError(
477
+ f"finalize_report.json is not valid JSON: {exc}",
478
+ error_code=E_DELIVERY_BUNDLE_MISSING,
479
+ ) from exc
480
+ if not isinstance(report, dict):
481
+ raise DeliverCommandError(
482
+ "finalize_report.json must be an object.",
483
+ error_code=E_DELIVERY_BUNDLE_MISSING,
484
+ )
485
+
486
+ reader_clean = report.get("reader_clean")
487
+ if report.get("status") != "pass" or not isinstance(reader_clean, dict) or reader_clean.get("status") != "pass":
488
+ raise DeliverCommandError(
489
+ "Delivery bundle is not clean. Run finalize and resolve reader-clean findings before delivery.",
490
+ error_code=E_DELIVERY_NOT_CLEAN,
491
+ )
492
+ raw_artifacts = report.get("delivery_artifacts")
493
+ if not isinstance(raw_artifacts, list) or not raw_artifacts:
494
+ raise DeliverCommandError(
495
+ "Delivery bundle is missing delivery_artifacts. Run: multi-agent-brief finalize --config <workspace>/config.yaml",
496
+ error_code=E_DELIVERY_BUNDLE_MISSING,
497
+ )
498
+ raw_hashes = report.get("delivery_artifact_sha256")
499
+ if not isinstance(raw_hashes, dict) or not raw_hashes:
500
+ raise DeliverCommandError(
501
+ "Delivery bundle is missing delivery_artifact_sha256. Run finalize again before delivery.",
502
+ error_code=E_DELIVERY_BUNDLE_MISSING,
503
+ )
504
+
505
+ delivery_root = (workspace / "output" / "delivery").resolve()
506
+ artifacts: list[Path] = []
507
+ artifact_hashes: dict[str, str] = {}
508
+ for raw in raw_artifacts:
509
+ if not isinstance(raw, str) or not raw.strip():
510
+ raise DeliverCommandError(
511
+ "Delivery bundle contains an invalid artifact path.",
512
+ error_code=E_DELIVERY_BUNDLE_MISSING,
513
+ )
514
+ path = Path(raw).expanduser()
515
+ resolved = path.resolve() if path.is_absolute() else (workspace / path).resolve()
516
+ try:
517
+ resolved.relative_to(delivery_root)
518
+ except ValueError as exc:
519
+ raise DeliverCommandError(
520
+ "Delivery bundle may only contain output/delivery artifacts.",
521
+ error_code=E_DELIVERY_BUNDLE_MISSING,
522
+ ) from exc
523
+ if not resolved.exists():
524
+ raise DeliverCommandError(
525
+ f"Delivery artifact not found: {_workspace_relative(workspace, resolved)}",
526
+ error_code=E_DELIVERY_BUNDLE_MISSING,
527
+ )
528
+ expected_hash = _hash_for_delivery_artifact(
529
+ raw_hashes,
530
+ raw_path=raw,
531
+ workspace=workspace,
532
+ resolved=resolved,
533
+ )
534
+ rel = _workspace_relative(workspace, resolved)
535
+ if not expected_hash:
536
+ raise DeliverCommandError(
537
+ f"Delivery artifact hash missing for {rel}. Run finalize again before delivery.",
538
+ error_code=E_DELIVERY_BUNDLE_MISSING,
539
+ )
540
+ actual_hash = _sha256_file(resolved)
541
+ if actual_hash != expected_hash:
542
+ raise DeliverCommandError(
543
+ f"Delivery artifact has changed since finalize: {rel}. Run finalize again before delivery.",
544
+ error_code=E_DELIVERY_ARTIFACT_MISMATCH,
545
+ extra={"artifact": rel},
546
+ )
547
+ artifacts.append(resolved)
548
+ artifact_hashes[rel] = expected_hash
549
+
550
+ markdown = next((path for path in artifacts if path.name == "brief.md"), None)
551
+ docx = next((path for path in artifacts if path.suffix.lower() == ".docx"), None)
552
+ return DeliveryBundle(
553
+ workspace=workspace,
554
+ artifacts=artifacts,
555
+ markdown=markdown,
556
+ docx=docx,
557
+ artifact_sha256=artifact_hashes,
558
+ )
559
+
560
+
561
+ def _hash_for_delivery_artifact(
562
+ hashes: dict[str, Any],
563
+ *,
564
+ raw_path: str,
565
+ workspace: Path,
566
+ resolved: Path,
567
+ ) -> str:
568
+ rel = _workspace_relative(workspace, resolved)
569
+ candidates = [
570
+ raw_path,
571
+ rel,
572
+ resolved.as_posix(),
573
+ str(resolved),
574
+ ]
575
+ for key in candidates:
576
+ value = hashes.get(key)
577
+ if isinstance(value, str) and value.strip():
578
+ return value.strip()
579
+ return ""
580
+
581
+
582
+ def _verify_current_delivery_artifacts(bundle: DeliveryBundle) -> None:
583
+ markdown_results = []
584
+ docx_results = []
585
+ forbidden_phrases = policy_forbidden_phrases(resolve_workspace_policy_gate_adapter(bundle.workspace))
586
+ for artifact in bundle.artifacts:
587
+ rel = _workspace_relative(bundle.workspace, artifact)
588
+ suffix = artifact.suffix.lower()
589
+ if suffix == ".md":
590
+ markdown_results.append(
591
+ detect_reader_residue(
592
+ artifact.read_text(encoding="utf-8"),
593
+ artifact=rel,
594
+ forbidden_phrases=forbidden_phrases,
595
+ )
596
+ )
597
+ elif suffix == ".docx":
598
+ docx_results.append(
599
+ detect_reader_residue_in_docx(artifact, artifact=rel, forbidden_phrases=forbidden_phrases)
600
+ )
601
+ else:
602
+ raise DeliverCommandError(
603
+ f"Unsupported delivery artifact type: {rel}",
604
+ error_code=E_DELIVERY_BUNDLE_MISSING,
605
+ )
606
+ clean = combine_reader_final_gate_results([*markdown_results, *docx_results])
607
+ if clean.status != "pass":
608
+ raise DeliverCommandError(
609
+ "Current delivery artifacts fail the reader-final gate. Run finalize again before delivery.",
610
+ error_code=E_DELIVERY_NOT_CLEAN,
611
+ extra={"reader_clean": clean.to_report_dict()},
612
+ )
613
+
614
+
615
+ def _select_feishu_artifact(bundle: DeliveryBundle, channel: str) -> Path:
616
+ if channel == "drive" and bundle.docx is not None:
617
+ return bundle.docx
618
+ if bundle.markdown is not None:
619
+ return bundle.markdown
620
+ raise DeliverCommandError(
621
+ "Delivery bundle is missing output/delivery/brief.md.",
622
+ error_code=E_DELIVERY_BUNDLE_MISSING,
623
+ target="feishu",
624
+ channel=channel,
625
+ )
626
+
627
+
628
+ def _select_gmail_attachment(bundle: DeliveryBundle) -> Path:
629
+ return bundle.docx or bundle.markdown or bundle.artifacts[0]
630
+
631
+
632
+ def _record_delivery_event(
633
+ workspace: Path,
634
+ *,
635
+ event_type: str,
636
+ target: str,
637
+ channel: str,
638
+ artifact: Path,
639
+ recipient: str = "",
640
+ url: str = "",
641
+ metadata: dict[str, Any] | None = None,
642
+ ) -> None:
643
+ try:
644
+ run_id = _delivery_run_id(workspace)
645
+ append_event(
646
+ workspace=workspace,
647
+ run_id=run_id,
648
+ event_type=event_type,
649
+ actor="cli",
650
+ reason=_event_reason(event_type),
651
+ metadata={
652
+ "target": target,
653
+ "channel": channel,
654
+ "artifact": _workspace_relative(workspace, artifact),
655
+ "recipient_present": bool(recipient),
656
+ "recipient_sha256": _sha256(recipient) if recipient else "",
657
+ "url": url,
658
+ **(metadata or {}),
659
+ },
660
+ )
661
+ except (RuntimeStateError, OSError, json.JSONDecodeError) as exc:
662
+ raise DeliverCommandError(
663
+ f"Unable to record delivery event: {exc}",
664
+ error_code=E_DELIVERY_EVENT_FAILED,
665
+ target=target,
666
+ channel=channel,
667
+ ) from exc
668
+
669
+
670
+ def _preflight_delivery_event_surface(workspace: Path) -> None:
671
+ try:
672
+ _delivery_run_id(workspace)
673
+ paths = runtime_state_paths(workspace)
674
+ event_log = paths["event_log"]
675
+ if event_log.exists():
676
+ raw = event_log.read_bytes()
677
+ if raw and not raw.endswith(b"\n"):
678
+ raise RuntimeStateError("event_log.jsonl is not newline-terminated.")
679
+ for lineno, line in enumerate(raw.decode("utf-8").splitlines(), start=1):
680
+ if not line.strip():
681
+ continue
682
+ payload = json.loads(line)
683
+ if not isinstance(payload, dict):
684
+ raise RuntimeStateError(f"event_log.jsonl line {lineno} is not an object.")
685
+ except DeliverCommandError:
686
+ raise
687
+ except (RuntimeStateError, OSError, json.JSONDecodeError) as exc:
688
+ raise DeliverCommandError(
689
+ f"Delivery event surface is not writable/readable: {exc}",
690
+ error_code=E_DELIVERY_EVENT_FAILED,
691
+ ) from exc
692
+
693
+
694
+ def _preflight_no_active_repair(workspace: Path, *, target: str, channel: str) -> None:
695
+ paths = runtime_state_paths(workspace)
696
+ try:
697
+ workflow = json.loads(paths["workflow_state"].read_text(encoding="utf-8"))
698
+ if not isinstance(workflow, dict):
699
+ raise RuntimeStateError("workflow_state.json must contain an object.")
700
+ raise_if_active_repair_open(workspace=workspace, workflow=workflow)
701
+ except RuntimeStateError as exc:
702
+ if exc.error_code == E_ACTIVE_REPAIR_OPEN:
703
+ raise DeliverCommandError(
704
+ str(exc),
705
+ error_code=E_ACTIVE_REPAIR_OPEN,
706
+ target=target,
707
+ channel=channel,
708
+ extra={
709
+ "runtime_error_code": E_ACTIVE_REPAIR_OPEN,
710
+ "details": exc.details,
711
+ },
712
+ ) from exc
713
+ raise DeliverCommandError(
714
+ f"Unable to verify active repair state before delivery: {exc}",
715
+ error_code=E_DELIVERY_EVENT_FAILED,
716
+ target=target,
717
+ channel=channel,
718
+ extra={"runtime_error_code": exc.error_code or E_DELIVERY_EVENT_FAILED},
719
+ ) from exc
720
+ except (OSError, json.JSONDecodeError) as exc:
721
+ raise DeliverCommandError(
722
+ f"workflow_state.json is unreadable before delivery: {exc}",
723
+ error_code=E_DELIVERY_EVENT_FAILED,
724
+ target=target,
725
+ channel=channel,
726
+ ) from exc
727
+
728
+
729
+ def _refresh_runtime_state_before_delivery(workspace: Path, *, target: str, channel: str) -> None:
730
+ paths = runtime_state_paths(workspace)
731
+ if not paths["runtime_manifest"].exists() or not paths["workflow_state"].exists():
732
+ return
733
+ try:
734
+ check_runtime_state(workspace=workspace, actor="cli")
735
+ except RuntimeStateError as exc:
736
+ raise DeliverCommandError(
737
+ f"Delivery blocked because runtime state integrity could not be refreshed: {exc}",
738
+ error_code=E_DELIVERY_RUN_INTEGRITY_BLOCKED,
739
+ target=target,
740
+ channel=channel,
741
+ extra={
742
+ "runtime_error_code": exc.error_code or E_DELIVERY_RUN_INTEGRITY_BLOCKED,
743
+ "run_integrity": _delivery_run_integrity(workspace),
744
+ },
745
+ ) from exc
746
+ except Exception as exc:
747
+ raise DeliverCommandError(
748
+ f"Delivery blocked because runtime state integrity could not be refreshed: {exc}",
749
+ error_code=E_DELIVERY_EVENT_FAILED,
750
+ target=target,
751
+ channel=channel,
752
+ ) from exc
753
+
754
+
755
+ def _delivery_run_id(workspace: Path) -> str:
756
+ paths = runtime_state_paths(workspace)
757
+ if not paths["runtime_manifest"].exists() or not paths["workflow_state"].exists():
758
+ raise DeliverCommandError(
759
+ "Runtime state is not initialized; deliver will not create a new run trace. Run `multi-agent-brief run --workspace <workspace>` first.",
760
+ error_code=E_DELIVERY_RUNTIME_MISSING,
761
+ extra={"runtime_error_code": E_RUNTIME_STATE_NOT_INITIALIZED},
762
+ )
763
+ manifest = json.loads(paths["runtime_manifest"].read_text(encoding="utf-8"))
764
+ run_id = manifest.get("run_id")
765
+ if not isinstance(run_id, str) or not run_id.strip():
766
+ raise RuntimeStateError("runtime_manifest.json is missing run_id.")
767
+ return run_id
768
+
769
+
770
+ def _delivery_run_integrity(workspace: Path) -> dict[str, Any]:
771
+ paths = runtime_state_paths(workspace)
772
+ if not paths["workflow_state"].exists():
773
+ return project_for_read(
774
+ interpret_run_integrity(
775
+ None,
776
+ field_present=True,
777
+ unavailable_reason={
778
+ "reason_code": "workflow_state_missing",
779
+ "message": "workflow_state.json is missing.",
780
+ },
781
+ )
782
+ )
783
+ try:
784
+ workflow = json.loads(paths["workflow_state"].read_text(encoding="utf-8"))
785
+ except (OSError, json.JSONDecodeError) as exc:
786
+ raise DeliverCommandError(
787
+ f"workflow_state.json is unreadable; cannot verify run integrity: {exc}",
788
+ error_code=E_DELIVERY_EVENT_FAILED,
789
+ ) from exc
790
+ if not isinstance(workflow, dict):
791
+ raise DeliverCommandError(
792
+ "workflow_state.json must contain an object; cannot verify run integrity.",
793
+ error_code=E_DELIVERY_EVENT_FAILED,
794
+ )
795
+ try:
796
+ workflow = workflow_with_sticky_contamination_events(
797
+ workflow,
798
+ read_event_log_records_strict(paths["event_log"]),
799
+ )
800
+ except RuntimeStateError:
801
+ pass
802
+ return project_for_read(
803
+ interpret_run_integrity(
804
+ workflow.get("run_integrity"),
805
+ field_present="run_integrity" in workflow,
806
+ )
807
+ )
808
+
809
+
810
+ def _preflight_run_integrity_for_delivery(
811
+ run_integrity: dict[str, Any],
812
+ *,
813
+ target: str,
814
+ channel: str,
815
+ ) -> None:
816
+ if run_integrity.get("status") == "clean" and run_integrity.get("reference_eligible") is True:
817
+ return
818
+ reasons = run_integrity.get("reasons") if isinstance(run_integrity.get("reasons"), list) else []
819
+ first_reason = reasons[0] if reasons and isinstance(reasons[0], dict) else {}
820
+ message = first_reason.get("message") or first_reason.get("reason_code") or "run integrity is not clean"
821
+ raise DeliverCommandError(
822
+ "Delivery blocked because run integrity is not clean. "
823
+ f"Run `multi-agent-brief status --workspace <workspace>` and resolve: {message}",
824
+ error_code=E_DELIVERY_RUN_INTEGRITY_BLOCKED,
825
+ target=target,
826
+ channel=channel,
827
+ extra={"run_integrity": run_integrity},
828
+ )
829
+
830
+
831
+ def _print_run_integrity_warning(payload: dict[str, Any]) -> None:
832
+ integrity = payload.get("run_integrity")
833
+ if not isinstance(integrity, dict) or integrity.get("reference_eligible") is not False:
834
+ return
835
+ print(f"[deliver] Run integrity: {integrity.get('status') or 'unknown'}", file=sys.stderr)
836
+ print("[deliver] Reference eligible: no", file=sys.stderr)
837
+ reasons = integrity.get("reasons") if isinstance(integrity.get("reasons"), list) else []
838
+ if reasons:
839
+ first = reasons[0] if isinstance(reasons[0], dict) else {}
840
+ message = first.get("message") or first.get("reason_code") or "run is contaminated"
841
+ print(f"[deliver] Reason: {message}", file=sys.stderr)
842
+
843
+
844
+ def _event_reason(event_type: str) -> str:
845
+ return {
846
+ "delivery_attempted": "Reader delivery attempted.",
847
+ "delivery_draft_created": "Reader delivery draft created.",
848
+ "delivery_succeeded": "Reader delivery succeeded.",
849
+ "delivery_failed": "Reader delivery failed.",
850
+ }.get(event_type, "Reader delivery event.")
851
+
852
+
853
+ def _workspace_relative(workspace: Path, path: Path) -> str:
854
+ resolved = path.expanduser().resolve()
855
+ try:
856
+ return resolved.relative_to(workspace.resolve()).as_posix()
857
+ except ValueError:
858
+ return resolved.as_posix()
859
+
860
+
861
+ def _sha256(value: str) -> str:
862
+ return hashlib.sha256(value.encode("utf-8")).hexdigest()
863
+
864
+
865
+ def _sha256_file(path: Path) -> str:
866
+ h = hashlib.sha256()
867
+ with path.open("rb") as f:
868
+ for chunk in iter(lambda: f.read(1024 * 1024), b""):
869
+ h.update(chunk)
870
+ return h.hexdigest()
871
+
872
+
873
+ def _default_gmail_subject(bundle: DeliveryBundle) -> str:
874
+ title = ""
875
+ if bundle.markdown is not None:
876
+ try:
877
+ for line in bundle.markdown.read_text(encoding="utf-8").splitlines():
878
+ stripped = line.strip()
879
+ if stripped.startswith("# "):
880
+ title = stripped[2:].strip()
881
+ break
882
+ except OSError:
883
+ title = ""
884
+ return f"BriefLoop delivery: {title or 'Final brief'}"
885
+
886
+
887
+ def _default_gmail_body(bundle: DeliveryBundle) -> str:
888
+ attachment = _workspace_relative(bundle.workspace, _select_gmail_attachment(bundle))
889
+ excerpt = ""
890
+ if bundle.markdown is not None:
891
+ try:
892
+ text = bundle.markdown.read_text(encoding="utf-8")
893
+ excerpt = _markdown_excerpt(text)
894
+ except OSError:
895
+ excerpt = ""
896
+ lines = [
897
+ "Please review the attached BriefLoop delivery.",
898
+ "",
899
+ f"Attachment: {attachment}",
900
+ "",
901
+ "Brief excerpt:",
902
+ excerpt or "(No markdown excerpt available.)",
903
+ "",
904
+ "Audit/control files are not attached.",
905
+ ]
906
+ return "\n".join(lines)
907
+
908
+
909
+ def _markdown_excerpt(text: str, *, limit: int = 1200) -> str:
910
+ cleaned_lines = []
911
+ for line in text.splitlines():
912
+ stripped = line.strip()
913
+ if not stripped:
914
+ continue
915
+ heading_text = stripped.lstrip("#").strip().lower()
916
+ if heading_text == "source appendix":
917
+ break
918
+ cleaned_lines.append(stripped)
919
+ excerpt = "\n".join(cleaned_lines).strip()
920
+ if len(excerpt) <= limit:
921
+ return excerpt
922
+ return excerpt[: limit - 3].rstrip() + "..."
923
+
924
+
925
+ def _safe_delivery_message(result: DeliveryResult, channel: str, *, recipient: str = "") -> str:
926
+ if result.delivered:
927
+ if channel == "doc":
928
+ return "Doc created"
929
+ if channel == "drive":
930
+ return "File uploaded"
931
+ if channel == "chat":
932
+ return "Message sent"
933
+ return _sanitize_delivery_message(result.message or "Delivery failed", recipient=recipient)
934
+
935
+
936
+ def _sanitize_delivery_message(message: str, *, recipient: str = "") -> str:
937
+ text = str(message)
938
+ if recipient:
939
+ text = text.replace(recipient, "[recipient]")
940
+ text = _RECIPIENT_ID_RE.sub("[recipient]", text)
941
+ text = _LONG_TOKEN_RE.sub("[token]", text)
942
+ return text