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,1449 @@
1
+ """Product-layer ReportPack and ReportSpec CLI surfaces."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import glob
7
+ import hashlib
8
+ import json
9
+ import shutil
10
+ import tempfile
11
+ from copy import deepcopy
12
+ from datetime import datetime, timezone
13
+ from pathlib import Path
14
+ from typing import Any
15
+
16
+ import yaml
17
+
18
+ from multi_agent_brief.contracts.schemas.evidence_span_registry import EVIDENCE_SPAN_REGISTRY_SCHEMA_VERSION
19
+ from multi_agent_brief.contracts.source_metadata import normalize_source_category
20
+ from multi_agent_brief.inputs.contracts import extracted_markdown_path
21
+ from multi_agent_brief.product.bundle_projection import (
22
+ ReportBundleProjectionError,
23
+ write_report_bundle_manifest,
24
+ )
25
+ from multi_agent_brief.product.policy_registry import PolicyProfileRegistry
26
+ from multi_agent_brief.product.policy_resolver import PolicyProfileResolution, resolve_policy_profile
27
+ from multi_agent_brief.product.quality_panel import (
28
+ QualityPanelError,
29
+ quality_panel_path,
30
+ write_quality_panel,
31
+ write_quality_panel_html,
32
+ write_quality_summary,
33
+ )
34
+ from multi_agent_brief.product.report_pack_aliases import (
35
+ RECOMMENDED_REPORT_PACK_ENTRIES,
36
+ aliases_for_report_pack,
37
+ recommended_entries_for_pack_ids,
38
+ resolve_report_pack_id,
39
+ )
40
+ from multi_agent_brief.product.report_registry import ReportPackRegistry
41
+ from multi_agent_brief.product.report_spec import (
42
+ ReportSpecLoadError,
43
+ load_report_spec,
44
+ validate_report_spec_payload,
45
+ )
46
+ from multi_agent_brief.product.template_registry import ReportTemplateRegistry
47
+
48
+ SPECIALIZED_REPORT_PACK_POLICY_PROFILES = {
49
+ "evidence_extract": "evidence_extract_default",
50
+ "solar_industry_periodic": "solar_manufacturing_default",
51
+ }
52
+ EVIDENCE_EXTRACT_BINARY_EXTENSIONS = {".pdf", ".docx", ".pptx", ".xlsx", ".xls", ".png", ".jpg", ".jpeg"}
53
+ EVIDENCE_EXTRACT_TEXT_EXTENSIONS = {".md", ".txt", ".json"}
54
+ EVIDENCE_EXTRACT_SPAN_EXCERPT_LIMIT = 1200
55
+ EVIDENCE_EXTRACT_SOURCE_LOCK_SCHEMA_VERSION = "briefloop.evidence_extract_source_lock.v1"
56
+ EVIDENCE_EXTRACT_PAGE_INVENTORY_SCHEMA_VERSION = "briefloop.evidence_extract_page_inventory.v1"
57
+ PRODUCT_WORKSPACE_SELECTOR_MAX_ITEMS = 20
58
+
59
+
60
+ def register_new_workspace(subparsers: argparse._SubParsersAction) -> None:
61
+ parser = subparsers.add_parser(
62
+ "new",
63
+ help="Create a conservative zero-config workspace from a ReportPack.",
64
+ )
65
+ parser.add_argument("report_pack", help="Product entry or ReportPack id, for example industry-weekly.")
66
+ parser.add_argument("workspace", help="Target workspace directory.")
67
+ parser.add_argument("--force", action="store_true", help="Overwrite existing init files.")
68
+ parser.add_argument(
69
+ "--company",
70
+ default="Your Organization",
71
+ help="Organization name placeholder.",
72
+ )
73
+ parser.add_argument(
74
+ "--industry",
75
+ help=(
76
+ "Industry or theme hint for deterministic PolicyProfile resolution. "
77
+ "Low-confidence or ambiguous matches use the ReportPack default."
78
+ ),
79
+ )
80
+ parser.add_argument(
81
+ "--policy-profile",
82
+ help="Explicit PolicyProfile override, for example finance_default.",
83
+ )
84
+ parser.add_argument("--title", help="Brief title. Defaults to the pack title.")
85
+ parser.add_argument(
86
+ "--audience",
87
+ help="Target reader label. Defaults to the pack audience label.",
88
+ )
89
+ parser.add_argument(
90
+ "--language",
91
+ choices=["en-US", "zh-CN", "bilingual"],
92
+ help="Brief language. Defaults to the pack audience language.",
93
+ )
94
+
95
+
96
+ def register_packs(subparsers: argparse._SubParsersAction) -> None:
97
+ parser = subparsers.add_parser(
98
+ "packs",
99
+ help="List and inspect supported and experimental ReportPack contracts.",
100
+ )
101
+ actions = parser.add_subparsers(dest="packs_action", required=True)
102
+
103
+ list_parser = actions.add_parser("list", help="List packaged ReportPacks.")
104
+ list_parser.add_argument("--json", action="store_true", help="Emit machine-readable JSON.")
105
+
106
+ show_parser = actions.add_parser("show", help="Show a packaged ReportPack.")
107
+ show_parser.add_argument("pack_id", help="Product entry or ReportPack id, for example industry-weekly.")
108
+ show_parser.add_argument("--json", action="store_true", help="Emit machine-readable JSON.")
109
+
110
+ templates_parser = actions.add_parser(
111
+ "templates",
112
+ help="List packaged ReportTemplate contracts.",
113
+ )
114
+ templates_parser.add_argument("--json", action="store_true", help="Emit machine-readable JSON.")
115
+
116
+ bundle_parser = actions.add_parser(
117
+ "bundle",
118
+ help="Write a delivery/audit bundle projection for a finalized workspace.",
119
+ )
120
+ bundle_parser.add_argument("--workspace", required=True, help="Path to workspace directory.")
121
+ bundle_parser.add_argument(
122
+ "--output",
123
+ help="Manifest output path. Defaults to <workspace>/output/report_bundle_manifest.json.",
124
+ )
125
+ bundle_parser.add_argument(
126
+ "--write-archives",
127
+ action="store_true",
128
+ help="Write clean delivery_bundle.zip and audit_bundle.zip from the manifest artifacts.",
129
+ )
130
+ bundle_parser.add_argument("--json", action="store_true", help="Emit machine-readable JSON.")
131
+
132
+
133
+ def register_validate_report_spec(subparsers: argparse._SubParsersAction) -> None:
134
+ parser = subparsers.add_parser(
135
+ "validate-report-spec",
136
+ help="Validate a ReportSpec YAML file.",
137
+ )
138
+ parser.add_argument("report_spec", help="Path to report_spec.yaml.")
139
+ parser.add_argument("--json", action="store_true", help="Emit machine-readable JSON.")
140
+
141
+
142
+ def register_extract(subparsers: argparse._SubParsersAction) -> None:
143
+ parser = subparsers.add_parser(
144
+ "extract",
145
+ help="Register an explicit evidence-extract scope and local source files.",
146
+ )
147
+ parser.add_argument("--workspace", required=True, help="Path to an evidence_extract workspace.")
148
+ parser.add_argument("--scope", required=True, help="Explicit extraction scope.")
149
+ parser.add_argument(
150
+ "--source",
151
+ action="append",
152
+ default=[],
153
+ help="Local source file path. May be repeated.",
154
+ )
155
+ parser.add_argument(
156
+ "--sources",
157
+ nargs="+",
158
+ default=[],
159
+ help="One or more local source file paths or shell-style globs.",
160
+ )
161
+ parser.add_argument(
162
+ "--source-category",
163
+ default="other",
164
+ help="Reader-facing source_category to write into manual source entries. Defaults to other.",
165
+ )
166
+ parser.add_argument("--language", default="en", help="Source language hint for manual source entries.")
167
+ parser.add_argument(
168
+ "--force",
169
+ action="store_true",
170
+ help="Replace previously registered evidence-extract source copies.",
171
+ )
172
+ parser.add_argument("--json", action="store_true", help="Emit machine-readable JSON.")
173
+
174
+
175
+ def register_quality(subparsers: argparse._SubParsersAction) -> None:
176
+ parser = subparsers.add_parser(
177
+ "quality",
178
+ help="Write experimental Quality Panel projection artifacts.",
179
+ )
180
+ actions = parser.add_subparsers(dest="quality_action", required=True)
181
+
182
+ summarize_parser = actions.add_parser(
183
+ "summarize",
184
+ help="Write Quality Panel JSON, Markdown, and static HTML projection artifacts.",
185
+ )
186
+ summarize_parser.add_argument("--workspace", required=True, help="Path to workspace directory.")
187
+ summarize_parser.add_argument("--json", action="store_true", help="Emit machine-readable JSON.")
188
+
189
+
190
+ def handle_new_workspace(args: argparse.Namespace) -> int:
191
+ registry = ReportPackRegistry.from_package()
192
+ requested_pack_id = resolve_report_pack_id(args.report_pack)
193
+ pack = registry.get(requested_pack_id)
194
+ if pack is None:
195
+ payload = {
196
+ "ok": False,
197
+ "error": f"unknown report pack: {args.report_pack}",
198
+ **_report_pack_entrypoint_payload(registry),
199
+ }
200
+ _print_payload("new", payload, as_json=False)
201
+ return 1
202
+
203
+ target = Path(args.workspace)
204
+ try:
205
+ creation = _create_report_pack_workspace(target=target, pack=pack, args=args)
206
+ except (FileExistsError, OSError, ValueError) as exc:
207
+ payload = {
208
+ "ok": False,
209
+ "error": str(exc),
210
+ "workspace": str(target),
211
+ "report_pack": pack.pack_id,
212
+ }
213
+ _print_payload("new", payload, as_json=False)
214
+ return 1
215
+
216
+ payload = {
217
+ "ok": True,
218
+ "workspace": str(target),
219
+ "report_pack": pack.pack_id,
220
+ "report_spec": str(target / "report_spec.yaml"),
221
+ "policy_profile": creation.get("policy_profile"),
222
+ "policy_profile_resolution": creation.get("policy_profile_resolution"),
223
+ "boundary": "zero_config_workspace_skeleton_only",
224
+ }
225
+ _print_payload("new", payload, as_json=False)
226
+ return 0
227
+
228
+
229
+ def handle_packs(args: argparse.Namespace) -> int:
230
+ registry = ReportPackRegistry.from_package()
231
+ if args.packs_action == "list":
232
+ payload = _with_report_pack_aliases(registry.to_list_payload())
233
+ _print_payload("packs list", payload, as_json=getattr(args, "json", False))
234
+ return 0 if payload["ok"] else 1
235
+
236
+ if args.packs_action == "show":
237
+ requested_pack_id = resolve_report_pack_id(args.pack_id)
238
+ pack = registry.get(requested_pack_id)
239
+ if pack is None:
240
+ payload = {
241
+ "ok": False,
242
+ "error": f"unknown report pack: {args.pack_id}",
243
+ **_report_pack_entrypoint_payload(registry),
244
+ }
245
+ _print_payload("packs show", payload, as_json=getattr(args, "json", False))
246
+ return 1
247
+ payload = {
248
+ "ok": True,
249
+ "pack": dict(pack.payload),
250
+ "aliases": aliases_for_report_pack(pack.pack_id),
251
+ "recommended_entry": RECOMMENDED_REPORT_PACK_ENTRIES.get(pack.pack_id),
252
+ "source": "packaged_report_pack",
253
+ }
254
+ _print_payload("packs show", payload, as_json=getattr(args, "json", False))
255
+ return 0
256
+
257
+ if args.packs_action == "templates":
258
+ template_registry = ReportTemplateRegistry.from_package()
259
+ payload = template_registry.to_list_payload()
260
+ _print_payload("packs templates", payload, as_json=getattr(args, "json", False))
261
+ return 0 if payload["ok"] else 1
262
+
263
+ if args.packs_action == "bundle":
264
+ try:
265
+ payload = write_report_bundle_manifest(
266
+ workspace=getattr(args, "workspace"),
267
+ output_path=getattr(args, "output", None),
268
+ write_archives=getattr(args, "write_archives", False),
269
+ )
270
+ except ReportBundleProjectionError as exc:
271
+ payload = {
272
+ "ok": False,
273
+ "error": str(exc),
274
+ "workspace": str(getattr(args, "workspace")),
275
+ }
276
+ _print_payload("packs bundle", payload, as_json=getattr(args, "json", False))
277
+ return 1
278
+ payload["ok"] = True
279
+ _print_payload("packs bundle", payload, as_json=getattr(args, "json", False))
280
+ return 0
281
+
282
+ return 1
283
+
284
+
285
+ def handle_validate_report_spec(args: argparse.Namespace) -> int:
286
+ registry = ReportPackRegistry.from_package()
287
+ policy_registry = PolicyProfileRegistry.from_package()
288
+ path = Path(args.report_spec)
289
+ try:
290
+ payload = load_report_spec(path)
291
+ except OSError as exc:
292
+ result = {
293
+ "ok": False,
294
+ "errors": [{"field": str(path), "error": str(exc), "severity": "error"}],
295
+ }
296
+ _print_payload("validate-report-spec", result, as_json=getattr(args, "json", False))
297
+ return 1
298
+ except ReportSpecLoadError as exc:
299
+ result = {
300
+ "ok": False,
301
+ "errors": [{"field": str(exc.path), "error": exc.message, "severity": "error"}],
302
+ }
303
+ _print_payload("validate-report-spec", result, as_json=getattr(args, "json", False))
304
+ return 1
305
+
306
+ validation = validate_report_spec_payload(
307
+ payload,
308
+ known_report_packs=registry.pack_ids(),
309
+ report_type_by_pack=registry.report_type_by_pack(),
310
+ known_policy_profiles=policy_registry.profile_ids(),
311
+ default_policy_profile_by_pack=registry.default_policy_profile_by_pack(),
312
+ )
313
+ result = validation.to_dict()
314
+ result["path"] = str(path)
315
+ _print_payload("validate-report-spec", result, as_json=getattr(args, "json", False))
316
+ return 0 if validation.ok else 1
317
+
318
+
319
+ def handle_extract(args: argparse.Namespace) -> int:
320
+ workspace = Path(args.workspace).expanduser().resolve()
321
+ try:
322
+ payload = _register_evidence_extract_scope(workspace=workspace, args=args)
323
+ except (OSError, ReportSpecLoadError, ValueError, yaml.YAMLError) as exc:
324
+ payload = {
325
+ "ok": False,
326
+ "error": str(exc),
327
+ "workspace": str(workspace),
328
+ "boundary": "evidence_extract_scope_source_and_text_span_registration_only",
329
+ }
330
+ _print_payload("extract", payload, as_json=getattr(args, "json", False))
331
+ return 1
332
+
333
+ _print_payload("extract", payload, as_json=getattr(args, "json", False))
334
+ return 0
335
+
336
+
337
+ def handle_quality(args: argparse.Namespace) -> int:
338
+ action = getattr(args, "quality_action", "")
339
+ if action != "summarize":
340
+ return 1
341
+
342
+ workspace = Path(args.workspace).expanduser().resolve()
343
+ try:
344
+ _require_existing_briefloop_workspace(workspace)
345
+ panel = write_quality_panel(workspace=workspace)
346
+ summary = write_quality_summary(workspace=workspace, panel_payload=panel)
347
+ html = write_quality_panel_html(workspace=workspace, panel_payload=panel)
348
+ except (QualityPanelError, OSError, ValueError, json.JSONDecodeError) as exc:
349
+ payload = {
350
+ "ok": False,
351
+ "error": str(exc),
352
+ "workspace": str(workspace),
353
+ "boundary": "quality_projection_only_not_gate_or_release_authority",
354
+ }
355
+ _print_payload("quality summarize", payload, as_json=getattr(args, "json", False))
356
+ return 1
357
+
358
+ payload = {
359
+ "ok": True,
360
+ "workspace": str(workspace),
361
+ "quality_panel": _workspace_relative(workspace, quality_panel_path(workspace)),
362
+ "quality_summary": summary["path"],
363
+ "quality_summary_sha256": summary["sha256"],
364
+ "quality_panel_html": html["path"],
365
+ "quality_panel_html_sha256": html["sha256"],
366
+ "overall_status": panel.get("overall_status"),
367
+ "recommended_actions": panel.get("recommended_actions", []),
368
+ "boundary": "quality_projection_only_not_gate_or_release_authority",
369
+ "non_claims": [
370
+ "not_a_quality_score",
371
+ "not_a_gate_report_replacement",
372
+ "not_release_authorization",
373
+ "not_delivery_approval",
374
+ "not_semantic_truth_proof",
375
+ "not_repair_execution",
376
+ ],
377
+ }
378
+ _print_payload("quality summarize", payload, as_json=getattr(args, "json", False))
379
+ return 0
380
+
381
+
382
+ def _require_existing_briefloop_workspace(workspace: Path) -> None:
383
+ if not workspace.exists() or not workspace.is_dir():
384
+ raise ValueError(f"workspace does not exist: {workspace}")
385
+ if not (workspace / "config.yaml").exists() and not (
386
+ workspace / "output" / "intermediate" / "runtime_manifest.json"
387
+ ).exists():
388
+ raise ValueError(f"not a BriefLoop workspace: {workspace}")
389
+
390
+
391
+ def _print_payload(label: str, payload: dict[str, Any], *, as_json: bool) -> None:
392
+ if as_json:
393
+ print(json.dumps(payload, ensure_ascii=False, indent=2, sort_keys=True))
394
+ return
395
+
396
+ print(f"[{label}] ok: {payload.get('ok')}")
397
+ if label == "packs list":
398
+ for item in payload.get("packs", []):
399
+ entry = item.get("recommended_entry") or item.get("pack_id")
400
+ print(
401
+ f"- {entry}: {item.get('display_name')} ({item.get('status')}; "
402
+ f"internal: {item.get('pack_id')})"
403
+ )
404
+ for error in payload.get("errors", []):
405
+ print(f"[error] {error.get('field')}: {error.get('error')}")
406
+ elif label == "packs templates":
407
+ for item in payload.get("templates", []):
408
+ print(f"- {item.get('template_id')}: {item.get('display_name')} ({item.get('status')})")
409
+ for error in payload.get("errors", []):
410
+ print(f"[error] {error.get('field')}: {error.get('error')}")
411
+ elif label == "packs show":
412
+ if payload.get("ok"):
413
+ pack = payload.get("pack", {})
414
+ print(f"pack_id: {pack.get('pack_id')}")
415
+ if payload.get("recommended_entry"):
416
+ print(f"recommended_entry: {payload.get('recommended_entry')}")
417
+ if payload.get("aliases"):
418
+ print(f"aliases: {', '.join(payload.get('aliases') or [])}")
419
+ print(f"report_type: {pack.get('report_type')}")
420
+ print(f"status: {pack.get('status')}")
421
+ print(f"boundary: {_report_pack_boundary_text(pack)}")
422
+ else:
423
+ print(payload.get("error"))
424
+ recommended = payload.get("recommended_entries") or []
425
+ if recommended:
426
+ print(f"try: {', '.join(recommended)}")
427
+ internal = payload.get("internal_pack_ids") or []
428
+ if internal:
429
+ print(f"internal_pack_ids: {', '.join(internal)}")
430
+ elif label == "new":
431
+ if payload.get("ok"):
432
+ workspace = payload.get("workspace")
433
+ print(f"Created BriefLoop workspace: {workspace}")
434
+ print(f"report_pack: {payload.get('report_pack')}")
435
+ print(f"report_spec: {payload.get('report_spec')}")
436
+ resolution = payload.get("policy_profile_resolution")
437
+ resolution = resolution if isinstance(resolution, dict) else {}
438
+ print(f"policy_profile: {payload.get('policy_profile') or 'unknown'}")
439
+ print(f"policy_profile_source: {resolution.get('source') or 'unknown'}")
440
+ print(
441
+ "boundary: product workspace skeleton only; no stages, gates,"
442
+ " rendering, or delivery were run"
443
+ )
444
+ print()
445
+ print("Next:")
446
+ print(f" Add local evidence files under {workspace}/input/sources/")
447
+ print(f" briefloop doctor --config {workspace}/config.yaml")
448
+ print(f" briefloop run --workspace {workspace}")
449
+ else:
450
+ print(payload.get("error"))
451
+ available = payload.get("available_packs") or []
452
+ if available:
453
+ print(f"available_packs: {', '.join(available)}")
454
+ recommended = payload.get("recommended_entries") or []
455
+ if recommended:
456
+ print(f"try: {', '.join(recommended)}")
457
+ internal = payload.get("internal_pack_ids") or []
458
+ if internal:
459
+ print(f"internal_pack_ids: {', '.join(internal)}")
460
+ elif label == "packs bundle":
461
+ if payload.get("ok"):
462
+ print(f"manifest: {payload.get('manifest_path')}")
463
+ print(f"delivery_artifacts: {payload.get('delivery_bundle', {}).get('artifact_count')}")
464
+ print(f"audit_artifacts: {payload.get('audit_bundle', {}).get('artifact_count')}")
465
+ archives = payload.get("bundle_archives") if isinstance(payload.get("bundle_archives"), dict) else {}
466
+ if archives.get("status") == "generated":
467
+ delivery_archive = archives.get("delivery") if isinstance(archives.get("delivery"), dict) else {}
468
+ audit_archive = archives.get("audit") if isinstance(archives.get("audit"), dict) else {}
469
+ print(f"delivery_archive: {delivery_archive.get('path')}")
470
+ print(f"audit_archive: {audit_archive.get('path')}")
471
+ print("boundary: bundle projection/export only; no render, delivery approval, or gate bypass")
472
+ else:
473
+ print(payload.get("error"))
474
+ elif label == "extract":
475
+ if payload.get("ok"):
476
+ print(f"workspace: {payload.get('workspace')}")
477
+ print(f"scope: {payload.get('scope')}")
478
+ print(f"registered_sources: {payload.get('source_count')}")
479
+ print(f"extraction_scope: {payload.get('extraction_scope')}")
480
+ print(f"audit_extraction_scope: {payload.get('audit_extraction_scope')}")
481
+ if payload.get("evidence_span_registry"):
482
+ print(f"evidence_span_registry: {payload.get('evidence_span_registry')}")
483
+ print(f"evidence_span_registry_span_count: {payload.get('evidence_span_registry_span_count')}")
484
+ for warning in payload.get("warnings", []):
485
+ print(f"[warning] {warning.get('code')}: {warning.get('message')}")
486
+ print(
487
+ "boundary: source/scope/text-span registration only; no binary parsing,"
488
+ " semantic support assessment, legal conclusion, delivery, or gate bypass"
489
+ )
490
+ else:
491
+ print(payload.get("error"))
492
+ elif label == "quality summarize":
493
+ if payload.get("ok"):
494
+ print(f"workspace: {payload.get('workspace')}")
495
+ print(f"quality_panel: {payload.get('quality_panel')}")
496
+ print(f"quality_summary: {payload.get('quality_summary')}")
497
+ print(f"quality_panel_html: {payload.get('quality_panel_html')}")
498
+ print(f"overall_status: {payload.get('overall_status')}")
499
+ actions = payload.get("recommended_actions")
500
+ action_count = len(actions) if isinstance(actions, list) else 0
501
+ print(f"recommended_actions: {action_count}")
502
+ print(
503
+ "boundary: quality projection only; no gates were run, no repair was started,"
504
+ " no delivery was approved, and no release was authorized"
505
+ )
506
+ else:
507
+ print(payload.get("error"))
508
+ else:
509
+ print(f"report_pack: {payload.get('report_pack')}")
510
+ print(f"resolved_policy_profile: {payload.get('resolved_policy_profile')}")
511
+ print(f"policy_profile_source: {payload.get('policy_profile_source')}")
512
+ print(f"report_type: {payload.get('report_type')}")
513
+ for error in payload.get("errors", []):
514
+ print(f"[error] {error.get('field')}: {error.get('error')}")
515
+ for warning in payload.get("warnings", []):
516
+ print(f"[warning] {warning.get('field')}: {warning.get('error')}")
517
+
518
+
519
+ def _report_pack_entrypoint_payload(registry: ReportPackRegistry) -> dict[str, Any]:
520
+ pack_ids = sorted(registry.pack_ids())
521
+ return {
522
+ "available_packs": pack_ids,
523
+ "internal_pack_ids": pack_ids,
524
+ "recommended_entries": recommended_entries_for_pack_ids(pack_ids),
525
+ }
526
+
527
+
528
+ def _with_report_pack_aliases(payload: dict[str, Any]) -> dict[str, Any]:
529
+ enriched = deepcopy(payload)
530
+ packs = []
531
+ for item in enriched.get("packs", []):
532
+ if not isinstance(item, dict):
533
+ packs.append(item)
534
+ continue
535
+ pack_id = str(item.get("pack_id") or "")
536
+ updated = dict(item)
537
+ updated["aliases"] = aliases_for_report_pack(pack_id)
538
+ recommended_entry = RECOMMENDED_REPORT_PACK_ENTRIES.get(pack_id)
539
+ if recommended_entry:
540
+ updated["recommended_entry"] = recommended_entry
541
+ packs.append(updated)
542
+ enriched["packs"] = packs
543
+ return enriched
544
+
545
+
546
+ def _report_pack_boundary_text(pack: dict[str, Any]) -> str:
547
+ status = str(pack.get("status") or "").strip()
548
+ if status == "supported":
549
+ return "supported product-layer contract; control spine and gates remain required"
550
+ return "experimental product-layer contract only"
551
+
552
+
553
+ def _resolve_report_pack_policy_profile(
554
+ *,
555
+ pack: Any,
556
+ args: argparse.Namespace,
557
+ known_policy_profiles: set[str],
558
+ ) -> PolicyProfileResolution:
559
+ explicit_profile = getattr(args, "policy_profile", None)
560
+ resolution = resolve_policy_profile(
561
+ default_policy_profile=pack.default_policy_profile,
562
+ explicit_policy_profile=explicit_profile,
563
+ industry=getattr(args, "industry", None),
564
+ company=getattr(args, "company", None),
565
+ known_policy_profiles=known_policy_profiles,
566
+ )
567
+ if explicit_profile:
568
+ return resolution
569
+
570
+ specialized_default = SPECIALIZED_REPORT_PACK_POLICY_PROFILES.get(pack.pack_id)
571
+ if (
572
+ specialized_default
573
+ and pack.default_policy_profile == specialized_default
574
+ and resolution.policy_profile != specialized_default
575
+ ):
576
+ return PolicyProfileResolution(
577
+ policy_profile=specialized_default,
578
+ source="report_pack.default_policy_profile",
579
+ input=resolution.input,
580
+ matched_rule="specialized_report_pack_default",
581
+ confidence="default_specialized_pack",
582
+ alternatives=(resolution.policy_profile,),
583
+ )
584
+ return resolution
585
+
586
+
587
+ def _create_report_pack_workspace(*, target: Path, pack: Any, args: argparse.Namespace) -> dict[str, Any]:
588
+ from multi_agent_brief.cli.init_wizard import InitProfile, create_workspace
589
+
590
+ policy_registry = PolicyProfileRegistry.from_package()
591
+ spec = deepcopy(dict(pack.default_report_spec))
592
+ policy_resolution = _resolve_report_pack_policy_profile(
593
+ pack=pack,
594
+ args=args,
595
+ known_policy_profiles=policy_registry.profile_ids(),
596
+ )
597
+ spec["policy_profile"] = policy_resolution.policy_profile
598
+ spec["policy_profile_resolution"] = policy_resolution.to_dict()
599
+ audience = spec.get("audience") if isinstance(spec.get("audience"), dict) else {}
600
+ title = args.title or str(spec.get("title") or pack.display_name or "BriefLoop Report")
601
+ language = args.language or str(audience.get("language") or "en-US")
602
+ reader_label = args.audience or str(audience.get("label") or "business reader")
603
+ industry_hint = getattr(args, "industry", None)
604
+ industry_text = industry_hint if isinstance(industry_hint, str) and industry_hint.strip() else pack.display_name
605
+ spec["title"] = title
606
+ spec["audience"] = dict(audience)
607
+ spec["audience"]["label"] = reader_label
608
+ spec["audience"]["language"] = language
609
+ cadence = str(spec.get("cadence") or "weekly")
610
+ outputs = (
611
+ spec.get("outputs")
612
+ if isinstance(spec.get("outputs"), list)
613
+ else ["markdown", "docx"]
614
+ )
615
+
616
+ profile = InitProfile(
617
+ interface_language=language,
618
+ output_language=language,
619
+ company=args.company,
620
+ role="report_owner",
621
+ industry=industry_text,
622
+ industry_text=industry_text,
623
+ brief_title=title,
624
+ audience=reader_label,
625
+ audience_profile="management",
626
+ focus_areas=[pack.display_name, "source-backed claims", "reader-ready brief"],
627
+ task_objective=(
628
+ f"Prepare a {pack.display_name} using local-first sources and the "
629
+ "BriefLoop control spine."
630
+ ),
631
+ forbidden_sources=[
632
+ "confidential material not approved for this workspace",
633
+ "private messages",
634
+ "credentials",
635
+ "material non-public information",
636
+ ],
637
+ cadence=cadence,
638
+ selector_max_items=PRODUCT_WORKSPACE_SELECTOR_MAX_ITEMS,
639
+ output_formats=[str(item) for item in outputs],
640
+ source_profile="conservative",
641
+ web_search_enabled=False,
642
+ web_search_mode="disabled",
643
+ )
644
+ spec_path = target / "report_spec.yaml"
645
+ if spec_path.exists() and not getattr(args, "force", False):
646
+ raise FileExistsError(
647
+ f"Refusing to overwrite existing file: {spec_path}. Use --force to overwrite."
648
+ )
649
+ create_workspace(target, profile, force=bool(getattr(args, "force", False)))
650
+ spec_path.write_text(
651
+ yaml.safe_dump(spec, sort_keys=False, allow_unicode=True),
652
+ encoding="utf-8",
653
+ )
654
+ return {
655
+ "policy_profile": policy_resolution.policy_profile,
656
+ "policy_profile_resolution": policy_resolution.to_dict(),
657
+ }
658
+
659
+
660
+ def _register_evidence_extract_scope(*, workspace: Path, args: argparse.Namespace) -> dict[str, Any]:
661
+ if not workspace.exists() or not workspace.is_dir():
662
+ raise ValueError(f"workspace does not exist: {workspace}")
663
+ spec_path = workspace / "report_spec.yaml"
664
+ if not spec_path.exists():
665
+ raise ValueError("report_spec.yaml not found. Run `briefloop new evidence-extract <workspace>` first.")
666
+ spec = load_report_spec(spec_path)
667
+ if spec.get("report_pack") != "evidence_extract":
668
+ raise ValueError(
669
+ "extract is only supported for evidence_extract workspaces in this release."
670
+ )
671
+ scope = str(getattr(args, "scope", "") or "").strip()
672
+ if not scope:
673
+ raise ValueError("--scope must be non-empty")
674
+
675
+ source_paths = _resolve_extract_source_paths(
676
+ [*getattr(args, "source", []), *getattr(args, "sources", [])]
677
+ )
678
+ if not source_paths:
679
+ raise ValueError("at least one --source or --sources path is required")
680
+ resolved_sources: list[Path] = []
681
+ seen_resolved: set[Path] = set()
682
+ for source_path in source_paths:
683
+ resolved = source_path.expanduser().resolve()
684
+ if resolved in seen_resolved:
685
+ continue
686
+ seen_resolved.add(resolved)
687
+ if not resolved.exists() or not resolved.is_file():
688
+ raise ValueError(f"source file not found: {source_path}")
689
+ resolved_sources.append(resolved)
690
+ resolved_sources = _filter_paired_mineru_markdown_sources(resolved_sources)
691
+
692
+ sources_dir = workspace / "input" / "sources" / "evidence_extract"
693
+ warnings: list[dict[str, str]] = []
694
+ registered: list[dict[str, Any]] = []
695
+ derived_inputs_by_source: dict[Path, Path] = {}
696
+ for idx, resolved in enumerate(resolved_sources, start=1):
697
+ target = sources_dir / f"{idx:03d}-{_safe_filename(resolved.name)}"
698
+ rel_target = _workspace_relative(workspace, target)
699
+ extension = target.suffix.lower()
700
+ derived_input = (
701
+ _adjacent_mineru_markdown_for_source(resolved)
702
+ if extension in EVIDENCE_EXTRACT_BINARY_EXTENSIONS
703
+ else None
704
+ )
705
+ derived_target = extracted_markdown_path(target) if derived_input is not None else None
706
+ derived_rel_target = _workspace_relative(workspace, derived_target) if derived_target is not None else ""
707
+ manual_enabled = extension in EVIDENCE_EXTRACT_TEXT_EXTENSIONS or derived_input is not None
708
+ if extension in EVIDENCE_EXTRACT_BINARY_EXTENSIONS:
709
+ if derived_input is None:
710
+ warnings.append(
711
+ {
712
+ "code": "binary_source_registered_only",
713
+ "message": (
714
+ f"{rel_target} was registered as durable source bytes; "
715
+ "BriefLoop does not parse binary/PDF spans in this command."
716
+ ),
717
+ }
718
+ )
719
+ warnings.append(
720
+ {
721
+ "code": "requires_mineru_extraction",
722
+ "message": (
723
+ f"{rel_target} has no adjacent MinerU Markdown representation; "
724
+ f"expected {extracted_markdown_path(resolved).name} before text-span registration."
725
+ ),
726
+ }
727
+ )
728
+ else:
729
+ derived_inputs_by_source[resolved] = derived_input
730
+ warnings.append(
731
+ {
732
+ "code": "mineru_derived_markdown_registered",
733
+ "message": (
734
+ f"{rel_target} remains the locked source bytes; "
735
+ f"{derived_rel_target} is used as the MinerU-derived text representation."
736
+ ),
737
+ }
738
+ )
739
+ elif extension and extension not in EVIDENCE_EXTRACT_TEXT_EXTENSIONS:
740
+ warnings.append(
741
+ {
742
+ "code": "unknown_text_support",
743
+ "message": f"{rel_target} was registered, but automatic text ingestion may not support it.",
744
+ }
745
+ )
746
+ elif not extension:
747
+ warnings.append(
748
+ {
749
+ "code": "unknown_text_support",
750
+ "message": f"{rel_target} was registered, but automatic text ingestion may not support it.",
751
+ }
752
+ )
753
+ registered.append(
754
+ {
755
+ "source_id": f"SRC-{idx:03d}",
756
+ "name": resolved.stem,
757
+ "path": rel_target,
758
+ "filename": target.name,
759
+ "extension": extension,
760
+ "source_sha256": _sha256_file(resolved),
761
+ "source_size_bytes": resolved.stat().st_size,
762
+ "manual_enabled": manual_enabled,
763
+ }
764
+ )
765
+ if derived_input is not None and derived_target is not None:
766
+ registered[-1].update(
767
+ {
768
+ "derived_markdown_path": derived_rel_target,
769
+ "derived_markdown_filename": derived_target.name,
770
+ "derived_markdown_sha256": _sha256_file(derived_input),
771
+ "derived_markdown_size_bytes": derived_input.stat().st_size,
772
+ "derived_markdown_derivation": "mineru_adjacent_markdown",
773
+ "derived_markdown_extractor": "mineru",
774
+ "text_evidence_path": derived_rel_target,
775
+ "text_evidence_sha256": _sha256_file(derived_input),
776
+ "text_evidence_size_bytes": derived_input.stat().st_size,
777
+ "text_evidence_basis": "mineru_derived_markdown",
778
+ }
779
+ )
780
+
781
+ if sources_dir.exists() and any(sources_dir.iterdir()) and not getattr(args, "force", False):
782
+ raise FileExistsError(
783
+ f"Refusing to overwrite existing evidence-extract sources: {sources_dir}. Use --force."
784
+ )
785
+ _build_sources_yaml_text(
786
+ workspace=workspace,
787
+ sources=registered,
788
+ source_category=normalize_source_category(getattr(args, "source_category", None), default="other"),
789
+ language=str(getattr(args, "language", "") or "en").strip() or "en",
790
+ )
791
+ staged_sources: dict[Path, Path] = {}
792
+ staging_parent = workspace / "output" / "intermediate"
793
+ managed_candidates = [*resolved_sources, *derived_inputs_by_source.values()]
794
+ managed_sources = (
795
+ _managed_extract_source_inputs(managed_candidates, sources_dir=sources_dir)
796
+ if getattr(args, "force", False)
797
+ else []
798
+ )
799
+ if managed_sources:
800
+ staging_parent.mkdir(parents=True, exist_ok=True)
801
+ with tempfile.TemporaryDirectory(
802
+ prefix=".briefloop-evidence-extract-",
803
+ dir=staging_parent,
804
+ ) as staging_dir_text:
805
+ staged_sources = _stage_extract_source_files(
806
+ managed_sources,
807
+ staging_dir=Path(staging_dir_text),
808
+ )
809
+ _copy_extract_sources(
810
+ workspace=workspace,
811
+ sources_dir=sources_dir,
812
+ sources=resolved_sources,
813
+ registered=registered,
814
+ derived_inputs_by_source=derived_inputs_by_source,
815
+ staged_sources=staged_sources,
816
+ force=bool(getattr(args, "force", False)),
817
+ )
818
+ else:
819
+ _copy_extract_sources(
820
+ workspace=workspace,
821
+ sources_dir=sources_dir,
822
+ sources=resolved_sources,
823
+ registered=registered,
824
+ derived_inputs_by_source=derived_inputs_by_source,
825
+ staged_sources={},
826
+ force=bool(getattr(args, "force", False)),
827
+ )
828
+
829
+ _refresh_registered_source_digests(workspace=workspace, registered=registered)
830
+ sources_yaml_text = _build_sources_yaml_text(
831
+ workspace=workspace,
832
+ sources=registered,
833
+ source_category=normalize_source_category(getattr(args, "source_category", None), default="other"),
834
+ language=str(getattr(args, "language", "") or "en").strip() or "en",
835
+ )
836
+ source_lock_path = _write_evidence_extract_source_lock(
837
+ workspace=workspace,
838
+ sources=registered,
839
+ scope=scope,
840
+ warnings=warnings,
841
+ )
842
+ page_inventory_path, page_count, page_inventory_source_count = _write_evidence_extract_page_inventory(
843
+ workspace=workspace,
844
+ sources=registered,
845
+ scope=scope,
846
+ warnings=warnings,
847
+ source_lock_path=source_lock_path,
848
+ )
849
+ span_registry_path, span_count, span_source_count = _write_evidence_extract_span_registry(
850
+ workspace=workspace,
851
+ sources=registered,
852
+ warnings=warnings,
853
+ )
854
+ extraction_scope_text = _extraction_scope_text(scope=scope, sources=registered, warnings=warnings)
855
+ _write_extraction_scope(workspace=workspace, text=extraction_scope_text)
856
+ (workspace / "sources.yaml").write_text(sources_yaml_text, encoding="utf-8")
857
+ payload = {
858
+ "ok": True,
859
+ "workspace": str(workspace),
860
+ "scope": scope,
861
+ "source_count": len(registered),
862
+ "sources": registered,
863
+ "extraction_scope": "extraction_scope.yaml",
864
+ "audit_extraction_scope": "output/audit/extraction_scope.yaml",
865
+ "source_lock": _workspace_relative(workspace, source_lock_path),
866
+ "audit_source_lock": "output/audit/evidence_extract_source_lock.json",
867
+ "page_inventory": _workspace_relative(workspace, page_inventory_path),
868
+ "audit_page_inventory": "output/audit/evidence_extract_page_inventory.json",
869
+ "page_inventory_source_count": page_inventory_source_count,
870
+ "page_inventory_page_count": page_count,
871
+ "evidence_span_registry": _workspace_relative(workspace, span_registry_path) if span_registry_path else "",
872
+ "evidence_span_registry_source_count": span_source_count,
873
+ "evidence_span_registry_span_count": span_count,
874
+ "warnings": warnings,
875
+ "boundary": "evidence_extract_scope_source_and_text_span_registration_only",
876
+ "non_claims": [
877
+ "no_binary_span_extraction",
878
+ "no_claim_support_matrix_generation",
879
+ "no_semantic_support_assessment",
880
+ "no_legal_conclusion",
881
+ "no_disclosure_readiness",
882
+ "no_delivery_or_publication_authority",
883
+ ],
884
+ }
885
+ return payload
886
+
887
+
888
+ def _write_evidence_extract_source_lock(
889
+ *,
890
+ workspace: Path,
891
+ sources: list[dict[str, Any]],
892
+ scope: str,
893
+ warnings: list[dict[str, str]],
894
+ ) -> Path:
895
+ created_at = datetime.now(timezone.utc).replace(microsecond=0).isoformat()
896
+ locked_sources: list[dict[str, Any]] = []
897
+ for record in sources:
898
+ source_record = {
899
+ "source_id": str(record.get("source_id") or ""),
900
+ "path": str(record.get("path") or ""),
901
+ "filename": str(record.get("filename") or ""),
902
+ "extension": str(record.get("extension") or ""),
903
+ "source_sha256": str(record.get("source_sha256") or ""),
904
+ "source_size_bytes": int(record.get("source_size_bytes") or 0),
905
+ "registered_only": not bool(record.get("manual_enabled")),
906
+ "lock_status": "locked_source_bytes",
907
+ }
908
+ if record.get("derived_markdown_path"):
909
+ source_record["derived_markdown"] = {
910
+ "path": str(record.get("derived_markdown_path") or ""),
911
+ "filename": str(record.get("derived_markdown_filename") or ""),
912
+ "sha256": str(record.get("derived_markdown_sha256") or ""),
913
+ "size_bytes": int(record.get("derived_markdown_size_bytes") or 0),
914
+ "derivation": str(record.get("derived_markdown_derivation") or ""),
915
+ "extractor": str(record.get("derived_markdown_extractor") or ""),
916
+ "source_path": str(record.get("path") or ""),
917
+ }
918
+ source_record["text_evidence_path"] = str(record.get("text_evidence_path") or "")
919
+ source_record["text_evidence_basis"] = str(record.get("text_evidence_basis") or "")
920
+ locked_sources.append(source_record)
921
+ payload = {
922
+ "schema_version": EVIDENCE_EXTRACT_SOURCE_LOCK_SCHEMA_VERSION,
923
+ "report_pack": "evidence_extract",
924
+ "created_at": created_at,
925
+ "scope_path": "extraction_scope.yaml",
926
+ "source_count": len(sources),
927
+ "sources": locked_sources,
928
+ "scope_excerpt": scope[:500],
929
+ "warnings": warnings,
930
+ "boundary": "deterministic_registered_source_lock_only",
931
+ "non_claims": [
932
+ "extract_command_does_not_run_mineru",
933
+ "derived_markdown_is_text_representation_not_original_source",
934
+ "no_pdf_or_binary_page_extraction",
935
+ "no_pdf_or_binary_page_extraction_without_derived_markdown",
936
+ "no_rendered_page_visual_check",
937
+ "no_evidence_ledger_generation",
938
+ "no_citation_gate",
939
+ "no_semantic_support_assessment",
940
+ "no_legal_conclusion",
941
+ "no_disclosure_readiness",
942
+ "no_delivery_or_publication_authority",
943
+ ],
944
+ }
945
+ lock_path = workspace / "output" / "intermediate" / "evidence_extract_source_lock.json"
946
+ lock_path.parent.mkdir(parents=True, exist_ok=True)
947
+ text = json.dumps(payload, ensure_ascii=False, indent=2, sort_keys=True) + "\n"
948
+ lock_path.write_text(text, encoding="utf-8")
949
+ audit_path = workspace / "output" / "audit" / "evidence_extract_source_lock.json"
950
+ audit_path.parent.mkdir(parents=True, exist_ok=True)
951
+ audit_path.write_text(text, encoding="utf-8")
952
+ return lock_path
953
+
954
+
955
+ def _write_evidence_extract_page_inventory(
956
+ *,
957
+ workspace: Path,
958
+ sources: list[dict[str, Any]],
959
+ scope: str,
960
+ warnings: list[dict[str, str]],
961
+ source_lock_path: Path,
962
+ ) -> tuple[Path, int, int]:
963
+ generated_at = datetime.now(timezone.utc).replace(microsecond=0).isoformat()
964
+ inventory_sources: list[dict[str, Any]] = []
965
+ page_count = 0
966
+ inventory_source_count = 0
967
+ for record in sources:
968
+ source_id = str(record.get("source_id") or "")
969
+ source_path = str(record.get("path") or "")
970
+ extension = str(record.get("extension") or "")
971
+ source_file = workspace / source_path
972
+ text_evidence = _text_evidence_for_record(workspace=workspace, record=record)
973
+ source_text = _source_text_for_span_registry(text_evidence["path"]) if text_evidence else None
974
+ page_basis = str(text_evidence["basis"]) if text_evidence else ""
975
+ needs_visual_inspection = page_basis == "mineru_derived_markdown"
976
+ pages: list[dict[str, Any]] = []
977
+ if source_text is not None and source_text.strip():
978
+ page_id = _evidence_extract_page_id(source_id)
979
+ pages.append(
980
+ {
981
+ "page_id": page_id,
982
+ "page_number": 1,
983
+ "page_label": "logical-page-1",
984
+ "page_basis": page_basis,
985
+ "has_searchable_text": True,
986
+ "needs_visual_inspection": needs_visual_inspection,
987
+ "char_start": 0,
988
+ "char_end": len(source_text),
989
+ }
990
+ )
991
+ inventory_status = "text_logical_page_seeded"
992
+ inventory_source_count += 1
993
+ page_count += 1
994
+ elif source_text is not None:
995
+ inventory_status = "text_empty_no_pages"
996
+ warnings.append(
997
+ {
998
+ "code": "page_inventory_skipped_empty_text_source",
999
+ "message": f"{source_path} has no non-empty text; no logical page was generated.",
1000
+ }
1001
+ )
1002
+ else:
1003
+ inventory_status = "unsupported_source_format_registered_only"
1004
+
1005
+ inventory_sources.append(
1006
+ {
1007
+ "source_id": source_id,
1008
+ "source_path": source_path,
1009
+ "extension": extension,
1010
+ "source_sha256": str(record.get("source_sha256") or ""),
1011
+ "inventory_status": inventory_status,
1012
+ "page_count": len(pages),
1013
+ "needs_external_extraction_tool": source_text is None,
1014
+ "visual_inspection_required": source_text is None or needs_visual_inspection,
1015
+ "pages": pages,
1016
+ }
1017
+ )
1018
+ if text_evidence is not None:
1019
+ inventory_sources[-1]["text_source_path"] = str(text_evidence["rel_path"])
1020
+ inventory_sources[-1]["text_source_sha256"] = str(text_evidence["sha256"])
1021
+ inventory_sources[-1]["text_evidence_basis"] = str(text_evidence["basis"])
1022
+
1023
+ payload = {
1024
+ "schema_version": EVIDENCE_EXTRACT_PAGE_INVENTORY_SCHEMA_VERSION,
1025
+ "report_pack": "evidence_extract",
1026
+ "generated_at": generated_at,
1027
+ "scope_path": "extraction_scope.yaml",
1028
+ "source_lock_path": "output/intermediate/evidence_extract_source_lock.json",
1029
+ "source_lock_sha256": _sha256_file(source_lock_path),
1030
+ "source_count": len(inventory_sources),
1031
+ "page_count": page_count,
1032
+ "inventory_source_count": inventory_source_count,
1033
+ "sources": inventory_sources,
1034
+ "scope_excerpt": scope[:500],
1035
+ "warnings": warnings,
1036
+ "boundary": "deterministic_page_inventory_seed_not_document_parsing",
1037
+ "non_claims": [
1038
+ "no_pdf_or_binary_page_extraction",
1039
+ "no_rendered_page_visual_check",
1040
+ "no_table_or_figure_extraction",
1041
+ "no_evidence_ledger_generation",
1042
+ "no_citation_gate",
1043
+ "no_semantic_support_assessment",
1044
+ "no_legal_conclusion",
1045
+ "no_disclosure_readiness",
1046
+ "no_delivery_or_publication_authority",
1047
+ ],
1048
+ }
1049
+ inventory_path = workspace / "output" / "intermediate" / "evidence_extract_page_inventory.json"
1050
+ inventory_path.parent.mkdir(parents=True, exist_ok=True)
1051
+ text = json.dumps(payload, ensure_ascii=False, indent=2, sort_keys=True) + "\n"
1052
+ inventory_path.write_text(text, encoding="utf-8")
1053
+ audit_path = workspace / "output" / "audit" / "evidence_extract_page_inventory.json"
1054
+ audit_path.parent.mkdir(parents=True, exist_ok=True)
1055
+ audit_path.write_text(text, encoding="utf-8")
1056
+ return inventory_path, page_count, inventory_source_count
1057
+
1058
+
1059
+ def _evidence_extract_page_id(source_id: str) -> str:
1060
+ return f"PAGE-{source_id}-001"
1061
+
1062
+
1063
+ def _copy_extract_sources(
1064
+ *,
1065
+ workspace: Path,
1066
+ sources_dir: Path,
1067
+ sources: list[Path],
1068
+ registered: list[dict[str, Any]],
1069
+ derived_inputs_by_source: dict[Path, Path],
1070
+ staged_sources: dict[Path, Path],
1071
+ force: bool,
1072
+ ) -> None:
1073
+ sources_dir.mkdir(parents=True, exist_ok=True)
1074
+ if force:
1075
+ for path in sources_dir.iterdir():
1076
+ if path.is_file():
1077
+ path.unlink()
1078
+
1079
+ for source, record in zip(sources, registered):
1080
+ shutil.copy2(staged_sources.get(source, source), workspace / record["path"])
1081
+ derived_input = derived_inputs_by_source.get(source)
1082
+ if derived_input is not None and record.get("derived_markdown_path"):
1083
+ shutil.copy2(
1084
+ staged_sources.get(derived_input, derived_input),
1085
+ workspace / str(record["derived_markdown_path"]),
1086
+ )
1087
+
1088
+
1089
+ def _refresh_registered_source_digests(*, workspace: Path, registered: list[dict[str, Any]]) -> None:
1090
+ for record in registered:
1091
+ source_path = workspace / str(record.get("path") or "")
1092
+ record["source_sha256"] = _sha256_file(source_path)
1093
+ record["source_size_bytes"] = source_path.stat().st_size
1094
+ if record.get("derived_markdown_path"):
1095
+ derived_path = workspace / str(record.get("derived_markdown_path") or "")
1096
+ derived_sha = _sha256_file(derived_path)
1097
+ derived_size = derived_path.stat().st_size
1098
+ record["derived_markdown_sha256"] = derived_sha
1099
+ record["derived_markdown_size_bytes"] = derived_size
1100
+ record["text_evidence_sha256"] = derived_sha
1101
+ record["text_evidence_size_bytes"] = derived_size
1102
+
1103
+
1104
+ def _managed_extract_source_inputs(sources: list[Path], *, sources_dir: Path) -> list[Path]:
1105
+ managed_root = sources_dir.expanduser().resolve()
1106
+ managed: list[Path] = []
1107
+ for source in sources:
1108
+ try:
1109
+ source.expanduser().resolve().relative_to(managed_root)
1110
+ except ValueError:
1111
+ continue
1112
+ managed.append(source)
1113
+ return managed
1114
+
1115
+
1116
+ def _stage_extract_source_files(sources: list[Path], *, staging_dir: Path) -> dict[Path, Path]:
1117
+ """Copy managed inputs before managed-source cleanup.
1118
+
1119
+ `extract --force` may be rerun with source paths that already live under
1120
+ `input/sources/evidence_extract/`. Staging first prevents the cleanup step
1121
+ from deleting those managed inputs before the final copy reads them. External
1122
+ inputs are not staged through system temp.
1123
+ """
1124
+
1125
+ staging_dir.mkdir(parents=True, exist_ok=True)
1126
+ staged: dict[Path, Path] = {}
1127
+ for idx, source in enumerate(sources, start=1):
1128
+ target = staging_dir / f"{idx:03d}-{_safe_filename(source.name)}"
1129
+ shutil.copy2(source, target)
1130
+ staged[source] = target
1131
+ return staged
1132
+
1133
+
1134
+ def _resolve_extract_source_paths(values: list[str]) -> list[Path]:
1135
+ paths: list[Path] = []
1136
+ for value in values:
1137
+ raw = str(value).strip()
1138
+ if not raw:
1139
+ continue
1140
+ expanded = str(Path(raw).expanduser())
1141
+ if any(token in raw for token in "*?[]"):
1142
+ matches = sorted(glob.glob(expanded))
1143
+ paths.extend(Path(item) for item in matches)
1144
+ else:
1145
+ paths.append(Path(expanded))
1146
+ return paths
1147
+
1148
+
1149
+ def _write_extraction_scope(
1150
+ *,
1151
+ workspace: Path,
1152
+ text: str,
1153
+ ) -> None:
1154
+ (workspace / "extraction_scope.yaml").write_text(text, encoding="utf-8")
1155
+ audit_dir = workspace / "output" / "audit"
1156
+ audit_dir.mkdir(parents=True, exist_ok=True)
1157
+ (audit_dir / "extraction_scope.yaml").write_text(text, encoding="utf-8")
1158
+
1159
+
1160
+ def _write_evidence_extract_span_registry(
1161
+ *,
1162
+ workspace: Path,
1163
+ sources: list[dict[str, Any]],
1164
+ warnings: list[dict[str, str]],
1165
+ ) -> tuple[Path | None, int, int]:
1166
+ registry_sources: list[dict[str, Any]] = []
1167
+ generated_at = datetime.now(timezone.utc).replace(microsecond=0).isoformat()
1168
+ for record in sources:
1169
+ if not bool(record.get("manual_enabled")):
1170
+ continue
1171
+ text_evidence = _text_evidence_for_record(workspace=workspace, record=record)
1172
+ if text_evidence is None:
1173
+ continue
1174
+ source_path = str(text_evidence["rel_path"])
1175
+ source_text = _source_text_for_span_registry(text_evidence["path"])
1176
+ if source_text is None:
1177
+ warnings.append(
1178
+ {
1179
+ "code": "text_span_seed_skipped",
1180
+ "message": f"{source_path} is not readable as UTF-8 text; no evidence span was generated.",
1181
+ }
1182
+ )
1183
+ continue
1184
+ span = _first_text_span(
1185
+ source_text,
1186
+ source_id=str(record.get("source_id") or ""),
1187
+ )
1188
+ if span is None:
1189
+ warnings.append(
1190
+ {
1191
+ "code": "text_span_seed_skipped",
1192
+ "message": f"{source_path} has no non-empty text; no evidence span was generated.",
1193
+ }
1194
+ )
1195
+ continue
1196
+ registry_sources.append(
1197
+ {
1198
+ "source_id": record["source_id"],
1199
+ "source_type": "local_file",
1200
+ "source_tier": "registered_local_source",
1201
+ "source_path": source_path,
1202
+ "retrieved_at": generated_at,
1203
+ "spans": [span],
1204
+ "metadata": {
1205
+ "source_sha256": record.get("source_sha256", ""),
1206
+ "source_size_bytes": record.get("source_size_bytes", 0),
1207
+ "text_evidence_sha256": text_evidence.get("sha256", ""),
1208
+ "text_evidence_size_bytes": text_evidence.get("size_bytes", 0),
1209
+ "text_evidence_basis": text_evidence.get("basis", ""),
1210
+ "evidence_extract_source": True,
1211
+ "extraction_scope": "extraction_scope.yaml",
1212
+ },
1213
+ }
1214
+ )
1215
+ if record.get("derived_markdown_path"):
1216
+ registry_sources[-1]["metadata"]["original_source_path"] = record.get("path", "")
1217
+ registry_sources[-1]["metadata"]["derived_markdown_path"] = record.get("derived_markdown_path", "")
1218
+
1219
+ if not registry_sources:
1220
+ registry_path = workspace / "output" / "intermediate" / "evidence_span_registry.json"
1221
+ try:
1222
+ registry_path.unlink()
1223
+ except FileNotFoundError:
1224
+ pass
1225
+ warnings.append(
1226
+ {
1227
+ "code": "no_text_evidence_spans_generated",
1228
+ "message": "No text source supported deterministic evidence-span seed generation.",
1229
+ }
1230
+ )
1231
+ return None, 0, 0
1232
+
1233
+ payload = {
1234
+ "schema_version": EVIDENCE_SPAN_REGISTRY_SCHEMA_VERSION,
1235
+ "sources": registry_sources,
1236
+ "metadata": {
1237
+ "source": "evidence_extract",
1238
+ "boundary": "deterministic_text_span_seed_not_semantic_support",
1239
+ "extraction_scope": "extraction_scope.yaml",
1240
+ "non_claims": [
1241
+ "no_semantic_support_assessment",
1242
+ "no_claim_support_matrix_generation",
1243
+ "no_binary_span_extraction",
1244
+ "no_legal_conclusion",
1245
+ "no_disclosure_readiness",
1246
+ ],
1247
+ },
1248
+ }
1249
+ intermediate = workspace / "output" / "intermediate"
1250
+ intermediate.mkdir(parents=True, exist_ok=True)
1251
+ registry_path = intermediate / "evidence_span_registry.json"
1252
+ registry_path.write_text(
1253
+ json.dumps(payload, ensure_ascii=False, indent=2, sort_keys=True) + "\n",
1254
+ encoding="utf-8",
1255
+ )
1256
+ span_count = sum(len(source.get("spans") or []) for source in registry_sources)
1257
+ return registry_path, span_count, len(registry_sources)
1258
+
1259
+
1260
+ def _source_text_for_span_registry(path: Path) -> str | None:
1261
+ try:
1262
+ raw_text = path.read_text(encoding="utf-8")
1263
+ except (OSError, UnicodeDecodeError):
1264
+ return None
1265
+ if path.suffix.lower() == ".json":
1266
+ try:
1267
+ payload = json.loads(raw_text)
1268
+ except json.JSONDecodeError:
1269
+ return raw_text
1270
+ if isinstance(payload, dict) and isinstance(payload.get("content"), str):
1271
+ return payload["content"]
1272
+ return raw_text
1273
+
1274
+
1275
+ def _adjacent_mineru_markdown_for_source(path: Path) -> Path | None:
1276
+ candidate = extracted_markdown_path(path)
1277
+ if candidate.exists() and candidate.is_file():
1278
+ return candidate
1279
+ return None
1280
+
1281
+
1282
+ def _filter_paired_mineru_markdown_sources(sources: list[Path]) -> list[Path]:
1283
+ source_set = set(sources)
1284
+ consumed_markdown = {
1285
+ extracted_markdown_path(source).resolve()
1286
+ for source in sources
1287
+ if source.suffix.lower() in EVIDENCE_EXTRACT_BINARY_EXTENSIONS
1288
+ and extracted_markdown_path(source).resolve() in source_set
1289
+ }
1290
+ if not consumed_markdown:
1291
+ return sources
1292
+ return [source for source in sources if source not in consumed_markdown]
1293
+
1294
+
1295
+ def _text_evidence_for_record(*, workspace: Path, record: dict[str, Any]) -> dict[str, Any] | None:
1296
+ if not bool(record.get("manual_enabled")):
1297
+ return None
1298
+ rel_path = str(record.get("text_evidence_path") or record.get("path") or "")
1299
+ if not rel_path:
1300
+ return None
1301
+ return {
1302
+ "path": workspace / rel_path,
1303
+ "rel_path": rel_path,
1304
+ "sha256": str(record.get("text_evidence_sha256") or record.get("source_sha256") or ""),
1305
+ "size_bytes": int(record.get("text_evidence_size_bytes") or record.get("source_size_bytes") or 0),
1306
+ "basis": str(record.get("text_evidence_basis") or "utf8_text_file"),
1307
+ }
1308
+
1309
+
1310
+ def _first_text_span(source_text: str, *, source_id: str) -> dict[str, Any] | None:
1311
+ start = next((idx for idx, char in enumerate(source_text) if not char.isspace()), None)
1312
+ if start is None:
1313
+ return None
1314
+ paragraph_end = source_text.find("\n\n", start)
1315
+ if paragraph_end == -1:
1316
+ paragraph_end = len(source_text)
1317
+ end = min(paragraph_end, start + EVIDENCE_EXTRACT_SPAN_EXCERPT_LIMIT)
1318
+ while end > start and source_text[end - 1].isspace():
1319
+ end -= 1
1320
+ if end <= start:
1321
+ return None
1322
+ raw_excerpt = source_text[start:end]
1323
+ source_digits = source_id.removeprefix("SRC-")
1324
+ return {
1325
+ "span_id": f"ESP-{source_digits}-01",
1326
+ "page_id": _evidence_extract_page_id(source_id),
1327
+ "page_number": 1,
1328
+ "raw_excerpt": raw_excerpt,
1329
+ "hash": "sha256:" + hashlib.sha256(raw_excerpt.encode("utf-8")).hexdigest(),
1330
+ "span_role": "direct_statement",
1331
+ "char_start": start,
1332
+ "char_end": end,
1333
+ }
1334
+
1335
+
1336
+ def _extraction_scope_text(
1337
+ *,
1338
+ scope: str,
1339
+ sources: list[dict[str, Any]],
1340
+ warnings: list[dict[str, str]],
1341
+ ) -> str:
1342
+ payload = {
1343
+ "schema_version": "briefloop.extraction_scope.v1",
1344
+ "report_pack": "evidence_extract",
1345
+ "scope": scope,
1346
+ "source_count": len(sources),
1347
+ "sources": sources,
1348
+ "created_at": datetime.now(timezone.utc).replace(microsecond=0).isoformat(),
1349
+ "warnings": warnings,
1350
+ "boundary": "scope_source_and_text_span_registration_only",
1351
+ "non_claims": [
1352
+ "no_binary_span_extraction",
1353
+ "no_semantic_support_assessment",
1354
+ "no_legal_conclusion",
1355
+ "no_disclosure_readiness",
1356
+ "no_semantic_proof",
1357
+ "no_claim_support_matrix_generation",
1358
+ "no_delivery_or_publication_authority",
1359
+ ],
1360
+ }
1361
+ return yaml.safe_dump(payload, sort_keys=False, allow_unicode=True)
1362
+
1363
+
1364
+ def _build_sources_yaml_text(
1365
+ *,
1366
+ workspace: Path,
1367
+ sources: list[dict[str, Any]],
1368
+ source_category: str,
1369
+ language: str,
1370
+ ) -> str:
1371
+ path = workspace / "sources.yaml"
1372
+ data = yaml.safe_load(path.read_text(encoding="utf-8")) if path.exists() else {}
1373
+ data = data if isinstance(data, dict) else {}
1374
+ strategy = data.get("source_strategy") if isinstance(data.get("source_strategy"), dict) else {}
1375
+ enabled = strategy.get("enabled_providers")
1376
+ if isinstance(enabled, str):
1377
+ enabled = [enabled]
1378
+ elif not isinstance(enabled, list):
1379
+ enabled = []
1380
+ if "manual" not in enabled:
1381
+ enabled.append("manual")
1382
+ strategy["enabled_providers"] = enabled
1383
+ strategy.setdefault("profile", "conservative")
1384
+ data["source_strategy"] = strategy
1385
+
1386
+ manual = data.get("manual") if isinstance(data.get("manual"), dict) else {}
1387
+ existing = [
1388
+ item
1389
+ for item in manual.get("sources", [])
1390
+ if isinstance(item, dict) and not item.get("evidence_extract_registered")
1391
+ ]
1392
+ for record in sources:
1393
+ text_path = str(record.get("text_evidence_path") or record["path"])
1394
+ existing.append(
1395
+ {
1396
+ "name": record["name"],
1397
+ "path": text_path,
1398
+ "category": source_category,
1399
+ "language": language,
1400
+ "enabled": bool(record.get("manual_enabled")),
1401
+ "evidence_extract_registered": True,
1402
+ "registered_only": not bool(record.get("manual_enabled")),
1403
+ "metadata": {
1404
+ "source_id": record["source_id"],
1405
+ "extraction_scope": "extraction_scope.yaml",
1406
+ "source_sha256": record["source_sha256"],
1407
+ "source_size_bytes": record["source_size_bytes"],
1408
+ "original_source_path": record["path"],
1409
+ },
1410
+ }
1411
+ )
1412
+ if record.get("derived_markdown_path"):
1413
+ existing[-1]["metadata"].update(
1414
+ {
1415
+ "derived_markdown_path": record["derived_markdown_path"],
1416
+ "derived_markdown_sha256": record["derived_markdown_sha256"],
1417
+ "derived_markdown_size_bytes": record["derived_markdown_size_bytes"],
1418
+ "text_evidence_basis": record.get("text_evidence_basis", ""),
1419
+ }
1420
+ )
1421
+ manual["enabled"] = True
1422
+ manual["sources"] = existing
1423
+ data["manual"] = manual
1424
+ web_search = data.get("web_search") if isinstance(data.get("web_search"), dict) else {}
1425
+ web_search.setdefault("enabled", False)
1426
+ web_search.setdefault("mode", "disabled")
1427
+ data["web_search"] = web_search
1428
+ return yaml.safe_dump(data, sort_keys=False, allow_unicode=True)
1429
+
1430
+
1431
+ def _safe_filename(name: str) -> str:
1432
+ safe = "".join(ch if ch.isalnum() or ch in "._-" else "-" for ch in name.strip())
1433
+ safe = safe.strip(".-")
1434
+ return safe or "source"
1435
+
1436
+
1437
+ def _sha256_file(path: Path) -> str:
1438
+ digest = hashlib.sha256()
1439
+ with path.open("rb") as handle:
1440
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
1441
+ digest.update(chunk)
1442
+ return digest.hexdigest()
1443
+
1444
+
1445
+ def _workspace_relative(workspace: Path, path: Path) -> str:
1446
+ try:
1447
+ return path.resolve().relative_to(workspace.resolve()).as_posix()
1448
+ except ValueError:
1449
+ return str(path)