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,2498 @@
1
+ """Quality-gate report generation and workspace state helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import re
8
+ import uuid
9
+ from concurrent.futures import ThreadPoolExecutor, as_completed
10
+ from hashlib import sha256
11
+ from pathlib import Path
12
+ from typing import Any, Callable
13
+
14
+ import yaml
15
+
16
+ from multi_agent_brief.audit.deterministic import run_deterministic_audit
17
+ from multi_agent_brief.audit.harness import QualityHarnessAuditAgent
18
+ from multi_agent_brief.core.citations import SRC_REF_PATTERN
19
+ from multi_agent_brief.core.claim_ledger import ClaimLedger
20
+ from multi_agent_brief.core.schemas import AuditFinding
21
+ from multi_agent_brief.orchestrator.runtime_state import (
22
+ RuntimeStateError,
23
+ append_event,
24
+ initialize_runtime_state,
25
+ load_artifact_contracts,
26
+ load_stage_specs,
27
+ raise_if_active_repair_open,
28
+ runtime_state_paths,
29
+ show_runtime_state,
30
+ utc_now,
31
+ )
32
+ from multi_agent_brief.orchestrator.runtime_state.claim_support_matrix import (
33
+ project_claim_support_matrix_from_workspace,
34
+ )
35
+ from multi_agent_brief.orchestrator.runtime_state.artifact_registry import (
36
+ ARTIFACT_VALID,
37
+ _validate_screened_candidates_payload,
38
+ )
39
+ from multi_agent_brief.orchestrator.runtime_state.errors import (
40
+ E_ACTIVE_REPAIR_OPEN,
41
+ E_FROZEN_GATE_REPORT_ALREADY_EXISTS,
42
+ E_TRANSACTION_INTEGRITY,
43
+ )
44
+ from multi_agent_brief.orchestrator_contract import resolve_repo_workdir
45
+ from multi_agent_brief.outputs.atomic_reader_projection import (
46
+ project_atomic_reader_text_from_workspace,
47
+ )
48
+ from multi_agent_brief.product.policy_gate_adapter import (
49
+ policy_gate_is_strict,
50
+ resolve_workspace_policy_gate_adapter,
51
+ )
52
+ from multi_agent_brief.quality_gates.contract import (
53
+ GATE_IDS,
54
+ QUALITY_GATE_SCHEMA,
55
+ QUALITY_GATE_STATE_FILES,
56
+ empty_quality_gate_report,
57
+ load_quality_gate_report,
58
+ load_quality_gate_report_for_stage,
59
+ quality_gate_report_key_for_stage,
60
+ quality_gate_report_path_for_stage,
61
+ quality_gate_paths,
62
+ validate_quality_gate_report_payload,
63
+ validate_quality_gate_workspace,
64
+ )
65
+
66
+
67
+ GATE_EVENT_ACTOR = "cli"
68
+ CURRENT_WORDS = re.compile(r"\b(this week|current|latest|newly|本周|本期|当前|最新|新增)\b", re.IGNORECASE)
69
+ ANALYST_DRAFT_SNAPSHOT_FILE = "output/intermediate/analyst_draft_snapshot.md"
70
+ FACT_NUMBER_RE = re.compile(
71
+ r"(?<![\w])(?:[$€¥£]\s*)?\d+(?:[,.]\d+)*(?:\.\d+)?%?(?:\s*(?:million|billion|trillion|thousand|mn|bn|mw|gw|gwh|mwh|%))?",
72
+ re.IGNORECASE,
73
+ )
74
+ ENTITY_RE = re.compile(
75
+ r"\b(?:[A-Z][A-Za-z0-9&.-]*|[A-Z]{2,})(?:[ \t]+(?:[A-Z][A-Za-z0-9&.-]*|[A-Z]{2,})){1,5}\b"
76
+ )
77
+ ENTITY_STOP_PHRASES = {
78
+ "Executive Summary",
79
+ "Key Takeaways",
80
+ "Important Notes",
81
+ }
82
+ STRATEGIC_IMPLICATION_PHRASES: tuple[tuple[str, tuple[str, ...]], ...] = (
83
+ ("early_mover_demand", ("early-mover demand", "early mover demand")),
84
+ ("procurement_pathways", ("procurement pathway", "procurement pathways")),
85
+ ("municipal_buyer_demand", ("municipal buyer demand", "municipal buyers demand")),
86
+ ("policy_driven_demand", ("policy-driven demand", "policy driven demand")),
87
+ ("partnership_recommendations", ("partnership recommendation", "partnership recommendations")),
88
+ )
89
+ FINAL_ABSTRACT_COMPARISON_RE = re.compile(
90
+ r"\b(?:better than|worse than|outperform(?:s|ed|ing)?|underperform(?:s|ed|ing)?|"
91
+ r"compared with|compared to|versus|vs\.?|higher than|lower than)\b|"
92
+ r"(?:相比|相较|优于|劣于|高于|低于|超过)",
93
+ re.IGNORECASE,
94
+ )
95
+ FINAL_ABSTRACT_SUPERLATIVE_RE = re.compile(
96
+ r"\b(?:best|largest|smallest|leading|market-leading|dominant|unmatched)\b|"
97
+ r"(?:最佳|最大|最小|领先|主导)",
98
+ re.IGNORECASE,
99
+ )
100
+ FINAL_ABSTRACT_RECOMMENDATION_RE = re.compile(
101
+ r"\b(?:recommend(?:s|ed|ing|ation)?|should|must|outlook|forecast|projection|scenario)\b|"
102
+ r"(?:建议|应该|必须|展望|预测|情景|推演)",
103
+ re.IGNORECASE,
104
+ )
105
+ FINAL_ABSTRACT_BASIS_HEADING_RE = re.compile(
106
+ r"\b(?:basis|methodology|method|benchmark|comparison basis|assumptions?|scope)\b|"
107
+ r"(?:比较基准|方法|基准|假设|范围)",
108
+ re.IGNORECASE,
109
+ )
110
+ FINAL_ABSTRACT_LIMITATION_HEADING_RE = re.compile(
111
+ r"\b(?:limitations?|assumptions?|scope|caveats?|constraints?)\b|"
112
+ r"(?:限制|局限|假设|范围|注意事项)",
113
+ re.IGNORECASE,
114
+ )
115
+ FINAL_ABSTRACT_SOURCE_HEADING_RE = re.compile(
116
+ r"\b(?:source appendix|sources|references|bibliography)\b|(?:来源|参考)",
117
+ re.IGNORECASE,
118
+ )
119
+ FINAL_ABSTRACT_CASE_HEADING_RE = re.compile(
120
+ r"\b(?:key cases|case studies|cases)\b|(?:关键案例|案例)",
121
+ re.IGNORECASE,
122
+ )
123
+ FINAL_ABSTRACT_CASE_FIELD_PATTERNS: dict[str, re.Pattern[str]] = {
124
+ "date_or_period": re.compile(r"\b20\d{2}(?:-\d{2}(?:-\d{2})?)?\b|(?:日期|时间|期间|窗口)"),
125
+ "source_reference": re.compile(r"\[src:[^\]]+\]|\[S\d+\]|(?:source|来源)[::]", re.IGNORECASE),
126
+ "impact_or_relevance": re.compile(r"\b(?:impact|relevance|implication|why it matters)\b|(?:影响|意义|启示|相关性)"),
127
+ }
128
+ GATE_RULE_DOC_ANCHOR = "docs/agent-contract.md#quality-gate-rule-summaries"
129
+ GATE_RULES: dict[str, dict[str, str]] = {
130
+ "coverage_omission": {
131
+ "rule_summary": (
132
+ "High-priority selected screened candidates should carry into Claim Ledger claims and cited brief "
133
+ "references, unless an explicit limitation or omission reason is recorded."
134
+ ),
135
+ "docs_anchor": "docs/agent-contract.md#coverage_omission",
136
+ },
137
+ "material_fact": {
138
+ "rule_summary": (
139
+ "Reader-facing factual claims must be traceable to supported Claim Ledger entries; numbers "
140
+ "and material assertions cannot rely on uncited prose alone."
141
+ ),
142
+ "docs_anchor": "docs/agent-contract.md#material_fact",
143
+ },
144
+ "freshness": {
145
+ "rule_summary": (
146
+ "Time-sensitive claims must respect the workspace freshness window and source-date requirements."
147
+ ),
148
+ "docs_anchor": "docs/agent-contract.md#freshness",
149
+ },
150
+ "target_relevance": {
151
+ "rule_summary": (
152
+ "The reader-facing summary must keep the configured target entity or topic visible."
153
+ ),
154
+ "docs_anchor": "docs/agent-contract.md#target_relevance",
155
+ },
156
+ "editor_new_fact": {
157
+ "rule_summary": (
158
+ "The Delivery Editor may polish wording but must not introduce factual tokens absent from the "
159
+ "Analyst draft."
160
+ ),
161
+ "docs_anchor": "docs/agent-contract.md#editor_new_fact",
162
+ },
163
+ "final_abstract_quality": {
164
+ "rule_summary": (
165
+ "Final abstract quality checks surface deterministic reader-risk patterns as warnings only; "
166
+ "they do not score prose, prove quality, or approve delivery."
167
+ ),
168
+ "docs_anchor": "docs/agent-contract.md#final_abstract_quality",
169
+ },
170
+ }
171
+ FINDING_RULES: dict[str, dict[str, str]] = {
172
+ "target_relevance_gap": {
173
+ "rule_summary": "Executive summary target visibility is required for reader context.",
174
+ "docs_anchor": "docs/agent-contract.md#target_relevance_gap",
175
+ },
176
+ "target_priority_claim_missing_from_summary": {
177
+ "rule_summary": "High-priority target-specific Claim Ledger entries should be represented in the summary.",
178
+ "docs_anchor": "docs/agent-contract.md#target_relevance_gap",
179
+ },
180
+ "number_without_source": {
181
+ "rule_summary": "Numbers in the brief must be tied to source-backed Claim Ledger support.",
182
+ "docs_anchor": "docs/agent-contract.md#number_without_source",
183
+ },
184
+ "editor_introduced_new_fact": {
185
+ "rule_summary": "Editor-added factual tokens must be removed or routed back through the owner stages.",
186
+ "docs_anchor": "docs/agent-contract.md#editor_introduced_new_fact",
187
+ },
188
+ "unsupported_strategic_implication": {
189
+ "rule_summary": (
190
+ "Strategic implications and recommendations need Claim Ledger support; lexical overreach is flagged "
191
+ "as a non-blocking warning for auditor review."
192
+ ),
193
+ "docs_anchor": "docs/agent-contract.md#unsupported_strategic_implication",
194
+ },
195
+ "atomic_atom_id_residue": {
196
+ "rule_summary": (
197
+ "Atomic Claim Graph atom IDs are internal decomposition aids and must not appear in reader-facing prose."
198
+ ),
199
+ "docs_anchor": "docs/agent-contract.md#atomic-claim-graph",
200
+ },
201
+ "atomic_graph_process_residue": {
202
+ "rule_summary": (
203
+ "Atomic Claim Graph process wording is internal control-plane residue and must not appear in reader-facing prose."
204
+ ),
205
+ "docs_anchor": "docs/agent-contract.md#atomic-claim-graph",
206
+ },
207
+ "claim_support_matrix_blocking_support": {
208
+ "rule_summary": (
209
+ "A present valid Claim-Support Matrix explicitly records a high-materiality atom as unsupported, "
210
+ "contradicted, or insufficiently evidenced."
211
+ ),
212
+ "docs_anchor": "docs/agent-contract.md#claim-support-matrix",
213
+ },
214
+ "claim_support_matrix_weak_support": {
215
+ "rule_summary": (
216
+ "A present valid Claim-Support Matrix explicitly records weak support requiring downgrade or adjudication."
217
+ ),
218
+ "docs_anchor": "docs/agent-contract.md#claim-support-matrix",
219
+ },
220
+ "claim_support_matrix_inference_framing": {
221
+ "rule_summary": (
222
+ "A present valid Claim-Support Matrix explicitly records inferential support requiring reader-facing framing."
223
+ ),
224
+ "docs_anchor": "docs/agent-contract.md#claim-support-matrix",
225
+ },
226
+ "selected_candidate_missing_from_ledger": {
227
+ "rule_summary": (
228
+ "Selected high-priority screened candidates should not disappear before Claim Ledger freeze "
229
+ "without an explicit limitation or omission reason."
230
+ ),
231
+ "docs_anchor": "docs/agent-contract.md#coverage_omission",
232
+ },
233
+ "selected_candidate_missing_from_brief": {
234
+ "rule_summary": (
235
+ "Selected high-priority screened candidates that reach the Claim Ledger should be cited in the "
236
+ "audited or reader-facing brief unless intentionally scoped out."
237
+ ),
238
+ "docs_anchor": "docs/agent-contract.md#coverage_omission",
239
+ },
240
+ "final_scope_title_mismatch": {
241
+ "rule_summary": "Report title cadence should not contradict the configured report cadence.",
242
+ "docs_anchor": "docs/agent-contract.md#final_abstract_quality",
243
+ },
244
+ "final_missing_comparison_basis": {
245
+ "rule_summary": "Comparison framing should include an explicit basis, method, benchmark, or scope.",
246
+ "docs_anchor": "docs/agent-contract.md#final_abstract_quality",
247
+ },
248
+ "final_missing_limitation_section": {
249
+ "rule_summary": "Recommendation, forecast, comparison, or superlative framing should declare limitations, scope, or assumptions.",
250
+ "docs_anchor": "docs/agent-contract.md#final_abstract_quality",
251
+ },
252
+ "final_incomplete_key_case_fields": {
253
+ "rule_summary": "Key-case bullets should carry date/period, source reference, and relevance/impact fields.",
254
+ "docs_anchor": "docs/agent-contract.md#final_abstract_quality",
255
+ },
256
+ "final_unsupported_superlative": {
257
+ "rule_summary": "Superlative wording should carry explicit local support or be downgraded.",
258
+ "docs_anchor": "docs/agent-contract.md#final_abstract_quality",
259
+ },
260
+ }
261
+
262
+
263
+ def _gate_rule(gate_id: str) -> dict[str, str]:
264
+ return GATE_RULES.get(
265
+ gate_id,
266
+ {
267
+ "rule_summary": "Quality gate rule details are available in the runtime agent contract.",
268
+ "docs_anchor": GATE_RULE_DOC_ANCHOR,
269
+ },
270
+ )
271
+
272
+
273
+ def _finding_rule(*, finding_type: str, gate_id: str) -> dict[str, str]:
274
+ return FINDING_RULES.get(finding_type, _gate_rule(gate_id))
275
+
276
+
277
+ def _require_workspace(workspace: str | Path) -> Path:
278
+ ws = Path(workspace).expanduser().resolve()
279
+ if not (ws / "config.yaml").exists():
280
+ raise RuntimeStateError(
281
+ f"Workspace config.yaml not found: {ws / 'config.yaml'}",
282
+ details={"workspace": str(ws)},
283
+ )
284
+ return ws
285
+
286
+
287
+ def _write_json_atomic(path: Path, payload: dict[str, Any]) -> None:
288
+ path.parent.mkdir(parents=True, exist_ok=True)
289
+ text = json.dumps(payload, ensure_ascii=False, indent=2, sort_keys=True) + "\n"
290
+ tmp = path.with_name(f".{path.name}.{uuid.uuid4().hex}.tmp")
291
+ try:
292
+ tmp.write_text(text, encoding="utf-8")
293
+ os.replace(tmp, path)
294
+ except OSError as exc:
295
+ try:
296
+ tmp.unlink(missing_ok=True)
297
+ except OSError:
298
+ pass
299
+ raise RuntimeStateError(
300
+ f"Failed to write quality gate report: {path}",
301
+ details={"path": str(path), "reason": str(exc)},
302
+ ) from exc
303
+
304
+
305
+ def _sha256_file(path: Path) -> str:
306
+ digest = sha256()
307
+ with path.open("rb") as handle:
308
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
309
+ digest.update(chunk)
310
+ return digest.hexdigest()
311
+
312
+
313
+ def _read_json_object(path: Path) -> dict[str, Any] | None:
314
+ if not path.exists():
315
+ return None
316
+ try:
317
+ payload = json.loads(path.read_text(encoding="utf-8"))
318
+ except (OSError, json.JSONDecodeError):
319
+ return None
320
+ return payload if isinstance(payload, dict) else None
321
+
322
+
323
+ def _stable_report_projection(payload: Any) -> Any:
324
+ if isinstance(payload, dict):
325
+ return {
326
+ str(key): _stable_report_projection(value)
327
+ for key, value in sorted(payload.items(), key=lambda item: str(item[0]))
328
+ if key not in {"created_at", "updated_at"}
329
+ }
330
+ if isinstance(payload, list):
331
+ return [_stable_report_projection(item) for item in payload]
332
+ return payload
333
+
334
+
335
+ def _quality_gate_reports_equivalent(left: dict[str, Any], right: dict[str, Any]) -> bool:
336
+ return _stable_report_projection(left) == _stable_report_projection(right)
337
+
338
+
339
+ def _frozen_report_record(workspace: Path, artifact_id: str) -> dict[str, Any] | None:
340
+ try:
341
+ state = show_runtime_state(workspace=workspace)
342
+ except RuntimeStateError:
343
+ return None
344
+ stage_id = _gate_report_producer_stage(artifact_id)
345
+ if stage_id is None or not _stage_is_frozen(state, stage_id):
346
+ return None
347
+ artifacts = (state.get("artifact_registry") or {}).get("artifacts")
348
+ if not isinstance(artifacts, dict):
349
+ return None
350
+ record = artifacts.get(artifact_id)
351
+ return record if isinstance(record, dict) and record.get("sha256") else None
352
+
353
+
354
+ def _gate_report_producer_stage(artifact_id: str) -> str | None:
355
+ if artifact_id == "auditor_quality_gate_report":
356
+ return "auditor"
357
+ if artifact_id == "finalize_quality_gate_report":
358
+ return "finalize"
359
+ return None
360
+
361
+
362
+ def _stage_is_frozen(state: dict[str, Any], stage_id: str) -> bool:
363
+ workflow = state.get("workflow_state")
364
+ statuses = workflow.get("stage_statuses") if isinstance(workflow, dict) else None
365
+ stage = statuses.get(stage_id) if isinstance(statuses, dict) else None
366
+ return isinstance(stage, dict) and stage.get("status") in {"complete", "skipped"}
367
+
368
+
369
+ def _ensure_frozen_report_is_unchanged(
370
+ *,
371
+ workspace: Path,
372
+ report_path: Path,
373
+ artifact_id: str,
374
+ ) -> dict[str, Any] | None:
375
+ record = _frozen_report_record(workspace, artifact_id)
376
+ if record is None:
377
+ return None
378
+ expected_sha = str(record.get("sha256") or "")
379
+ if not report_path.exists():
380
+ raise RuntimeStateError(
381
+ f"Frozen quality gate report is missing: {_workspace_relative(workspace, report_path)}",
382
+ details={
383
+ "artifact_id": artifact_id,
384
+ "path": _workspace_relative(workspace, report_path),
385
+ },
386
+ error_code=E_TRANSACTION_INTEGRITY,
387
+ )
388
+ actual_sha = _sha256_file(report_path)
389
+ if actual_sha != expected_sha:
390
+ raise RuntimeStateError(
391
+ "Frozen quality gate report no longer matches artifact_registry.json.",
392
+ details={
393
+ "artifact_id": artifact_id,
394
+ "path": _workspace_relative(workspace, report_path),
395
+ "expected_sha256": expected_sha,
396
+ "actual_sha256": actual_sha,
397
+ },
398
+ error_code=E_TRANSACTION_INTEGRITY,
399
+ )
400
+ return record
401
+
402
+
403
+ def _workspace_relative(workspace: Path, path: Path) -> str:
404
+ resolved = path.expanduser().resolve()
405
+ try:
406
+ return resolved.relative_to(workspace).as_posix()
407
+ except ValueError:
408
+ return path.as_posix()
409
+
410
+
411
+ def _contracts(
412
+ *,
413
+ workspace: Path,
414
+ repo_workdir: str | Path | None,
415
+ ) -> tuple[Path, list[dict[str, Any]], list[dict[str, Any]]]:
416
+ repo = resolve_repo_workdir(repo_workdir, workspace=workspace)
417
+ return repo, load_stage_specs(repo), load_artifact_contracts(repo)
418
+
419
+
420
+ def _runtime_run_id(
421
+ *,
422
+ workspace: Path,
423
+ repo_workdir: str | Path | None,
424
+ runtime: str = "hermes",
425
+ ) -> str:
426
+ try:
427
+ state = show_runtime_state(workspace=workspace)
428
+ except RuntimeStateError:
429
+ state = initialize_runtime_state(
430
+ workspace=workspace,
431
+ runtime=runtime,
432
+ repo_workdir=repo_workdir,
433
+ actor=GATE_EVENT_ACTOR,
434
+ )
435
+ return str((state.get("manifest") or {}).get("run_id") or "")
436
+
437
+
438
+ def _load_config(workspace: Path) -> dict[str, Any]:
439
+ path = workspace / "config.yaml"
440
+ try:
441
+ data = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
442
+ except (OSError, yaml.YAMLError):
443
+ return {}
444
+ return data if isinstance(data, dict) else {}
445
+
446
+
447
+ def _resolve_path(workspace: Path, value: str | Path | None, default: str) -> Path:
448
+ if value is None:
449
+ return workspace / default
450
+ path = Path(value).expanduser()
451
+ if path.is_absolute():
452
+ return path.resolve()
453
+ workspace_candidate = (workspace / path).resolve()
454
+ if workspace_candidate.exists():
455
+ return workspace_candidate
456
+
457
+ cwd_candidate = path.resolve()
458
+ if cwd_candidate.exists():
459
+ return cwd_candidate
460
+
461
+ return workspace_candidate
462
+
463
+
464
+ def _read_text(path: Path, *, label: str) -> str:
465
+ if not path.exists():
466
+ raise RuntimeStateError(
467
+ f"{label} not found: {path}",
468
+ details={"path": str(path)},
469
+ )
470
+ try:
471
+ text = path.read_text(encoding="utf-8")
472
+ except OSError as exc:
473
+ raise RuntimeStateError(
474
+ f"Failed to read {label}: {path}",
475
+ details={"path": str(path), "reason": str(exc)},
476
+ ) from exc
477
+ if not text.strip():
478
+ raise RuntimeStateError(
479
+ f"{label} is empty: {path}",
480
+ details={"path": str(path)},
481
+ )
482
+ return text
483
+
484
+
485
+ def _read_optional_text(path: Path) -> str:
486
+ if not path.exists():
487
+ return ""
488
+ try:
489
+ return path.read_text(encoding="utf-8")
490
+ except OSError:
491
+ return ""
492
+
493
+
494
+ def _read_analyst_draft_snapshot(workspace: Path) -> str | None:
495
+ snapshot_path = workspace / ANALYST_DRAFT_SNAPSHOT_FILE
496
+ if not snapshot_path.exists():
497
+ return None
498
+ try:
499
+ return snapshot_path.read_text(encoding="utf-8")
500
+ except OSError as exc:
501
+ raise RuntimeStateError(
502
+ f"Failed to read Analyst draft snapshot: {snapshot_path}",
503
+ details={"path": str(snapshot_path), "reason": str(exc)},
504
+ ) from exc
505
+
506
+
507
+ def _load_ledger(path: Path, *, required: bool) -> ClaimLedger:
508
+ if not path.exists():
509
+ if required:
510
+ raise RuntimeStateError(
511
+ f"Claim ledger not found: {path}",
512
+ details={"path": str(path)},
513
+ )
514
+ return ClaimLedger()
515
+ try:
516
+ return ClaimLedger.import_json(path)
517
+ except (OSError, json.JSONDecodeError, TypeError, ValueError) as exc:
518
+ raise RuntimeStateError(
519
+ f"Failed to read Claim Ledger: {path}",
520
+ details={"path": str(path), "reason": str(exc)},
521
+ ) from exc
522
+
523
+
524
+ def _gate_status(findings: list[dict[str, Any]]) -> str:
525
+ if any(finding.get("blocking_level") == "blocking" for finding in findings):
526
+ return "fail"
527
+ if findings:
528
+ return "warning"
529
+ return "pass"
530
+
531
+
532
+ def _report_status(gate_results: list[dict[str, Any]]) -> str:
533
+ if any(result.get("status") == "fail" for result in gate_results):
534
+ return "fail"
535
+ if any(result.get("status") == "warning" for result in gate_results):
536
+ return "warning"
537
+ return "pass"
538
+
539
+
540
+ def _stage_exists(stages: list[dict[str, Any]], stage_id: str) -> bool:
541
+ return any(stage.get("stage_id") == stage_id for stage in stages)
542
+
543
+
544
+ def _artifact_exists(artifacts: list[dict[str, Any]], artifact_id: str) -> bool:
545
+ return any(artifact.get("artifact_id") == artifact_id for artifact in artifacts)
546
+
547
+
548
+ def _stage_or_none(stages: list[dict[str, Any]], preferred: str) -> str | None:
549
+ return preferred if _stage_exists(stages, preferred) else None
550
+
551
+
552
+ def _artifact_or_none(artifacts: list[dict[str, Any]], preferred: str) -> str | None:
553
+ return preferred if _artifact_exists(artifacts, preferred) else None
554
+
555
+
556
+ def _blocking_level(*, default_blocking: bool, strict: bool) -> str:
557
+ return "blocking" if default_blocking or strict else "warning"
558
+
559
+
560
+ def _apply_gate_context(
561
+ findings: list[dict[str, Any]],
562
+ *,
563
+ gate_stage_id: str,
564
+ gate_artifact_id: str,
565
+ ) -> list[dict[str, Any]]:
566
+ for finding in findings:
567
+ metadata = finding.get("metadata") if isinstance(finding.get("metadata"), dict) else {}
568
+ advisory_non_routable = (
569
+ finding.get("gate_id") == "final_abstract_quality"
570
+ and metadata.get("repair_boundary") == "advisory_non_routable"
571
+ )
572
+ repair_stage_id = None if advisory_non_routable else finding.get("repair_stage_id") or finding.get("stage_id")
573
+ repair_artifact_id = (
574
+ None if advisory_non_routable else finding.get("repair_artifact_id") or finding.get("artifact_id")
575
+ )
576
+ finding["gate_stage_id"] = gate_stage_id
577
+ finding["gate_artifact_id"] = gate_artifact_id
578
+ finding["repair_stage_id"] = repair_stage_id
579
+ finding["repair_artifact_id"] = repair_artifact_id
580
+ return findings
581
+
582
+
583
+ def _config_report_defaults(
584
+ config: dict[str, Any],
585
+ *,
586
+ report_date: str,
587
+ max_source_age_days: int | None,
588
+ ) -> tuple[str, int | None]:
589
+ report = config.get("report") or {}
590
+ if not isinstance(report, dict):
591
+ return report_date, max_source_age_days
592
+
593
+ resolved_report_date = report_date
594
+ if not resolved_report_date and report.get("date") is not None:
595
+ resolved_report_date = str(report.get("date") or "")
596
+
597
+ resolved_max_source_age_days = max_source_age_days
598
+ if resolved_max_source_age_days is None and "max_source_age_days" in report:
599
+ try:
600
+ resolved_max_source_age_days = int(report["max_source_age_days"])
601
+ except (TypeError, ValueError) as exc:
602
+ raise RuntimeStateError(
603
+ "Invalid report.max_source_age_days in config.yaml.",
604
+ details={"value": report.get("max_source_age_days")},
605
+ ) from exc
606
+ return resolved_report_date, resolved_max_source_age_days
607
+
608
+
609
+ def _finding(
610
+ *,
611
+ finding_id: str,
612
+ gate_id: str,
613
+ finding_type: str,
614
+ severity: str,
615
+ blocking_level: str,
616
+ repair_owner: str,
617
+ stage_id: str | None,
618
+ artifact_id: str | None,
619
+ description: str,
620
+ recommendation: str,
621
+ category: str,
622
+ claim_id: str | None = None,
623
+ source_id: str | None = None,
624
+ line_number: int | None = None,
625
+ evidence_ref: str = "",
626
+ metadata: dict[str, Any] | None = None,
627
+ ) -> dict[str, Any]:
628
+ rule = _finding_rule(finding_type=finding_type, gate_id=gate_id)
629
+ return {
630
+ "finding_id": finding_id,
631
+ "gate_id": gate_id,
632
+ "finding_type": finding_type,
633
+ "category": category,
634
+ "severity": severity,
635
+ "blocking_level": blocking_level,
636
+ "blocking": blocking_level == "blocking",
637
+ "repair_owner": repair_owner,
638
+ "stage_id": stage_id,
639
+ "artifact_id": artifact_id,
640
+ "gate_stage_id": None,
641
+ "gate_artifact_id": None,
642
+ "repair_stage_id": stage_id,
643
+ "repair_artifact_id": artifact_id,
644
+ "claim_id": claim_id,
645
+ "source_id": source_id,
646
+ "line_number": line_number,
647
+ "description": description,
648
+ "recommendation": recommendation,
649
+ "rule_summary": rule["rule_summary"],
650
+ "docs_anchor": rule["docs_anchor"],
651
+ "summary": description,
652
+ "evidence_ref": evidence_ref,
653
+ "metadata": metadata or {},
654
+ }
655
+
656
+
657
+ def _map_audit_finding(
658
+ *,
659
+ finding: AuditFinding,
660
+ idx: int,
661
+ gate_id: str,
662
+ strict: bool,
663
+ stages: list[dict[str, Any]],
664
+ artifacts: list[dict[str, Any]],
665
+ ) -> dict[str, Any]:
666
+ finding_type = finding.finding_type
667
+ related_claim_id = finding.related_claim_id or None
668
+ source_stage = _stage_or_none(stages, "source-discovery")
669
+ claim_stage = _stage_or_none(stages, "claim-ledger")
670
+ editor_stage = _stage_or_none(stages, "editor")
671
+ audited_artifact = _artifact_or_none(artifacts, "audited_brief")
672
+ ledger_artifact = _artifact_or_none(artifacts, "claim_ledger")
673
+
674
+ stage_id = editor_stage
675
+ artifact_id = audited_artifact
676
+ repair_owner = "editor"
677
+ category = "unsupported_claim"
678
+ default_blocking = False
679
+
680
+ if finding_type in {"missing_source", "missing_source_date"}:
681
+ stage_id = claim_stage
682
+ artifact_id = ledger_artifact
683
+ repair_owner = "claim-ledger"
684
+ category = "missing_source" if finding_type == "missing_source" else "stale_source"
685
+ default_blocking = finding_type == "missing_source"
686
+ elif finding_type == "stale_source":
687
+ stage_id = claim_stage or source_stage
688
+ artifact_id = ledger_artifact
689
+ repair_owner = "claim-ledger" if claim_stage else "source-discovery"
690
+ category = "stale_source"
691
+ default_blocking = False
692
+ elif finding_type in {"missing_claim", "number_without_source"}:
693
+ default_blocking = True
694
+ elif finding_type in {"needs_recrawl_claim_used", "low_confidence_source_used"}:
695
+ stage_id = source_stage or claim_stage
696
+ artifact_id = ledger_artifact
697
+ repair_owner = "source-discovery" if source_stage else "claim-ledger"
698
+ default_blocking = True
699
+ elif finding_type in {"unsupported_certainty", "low_source_density"}:
700
+ default_blocking = True
701
+
702
+ blocking_level = _blocking_level(default_blocking=default_blocking, strict=strict)
703
+ severity = "high" if blocking_level == "blocking" else finding.severity
704
+ return _finding(
705
+ finding_id=f"QG_{gate_id.upper()}_{idx:03d}",
706
+ gate_id=gate_id,
707
+ finding_type=finding_type,
708
+ severity=severity if severity in {"low", "medium", "high"} else "medium",
709
+ blocking_level=blocking_level,
710
+ repair_owner=repair_owner,
711
+ stage_id=stage_id,
712
+ artifact_id=artifact_id,
713
+ claim_id=related_claim_id,
714
+ source_id=None,
715
+ line_number=finding.line_number,
716
+ description=finding.description,
717
+ recommendation=finding.recommendation,
718
+ evidence_ref=finding.evidence,
719
+ category=category,
720
+ metadata={"source_finding_type": finding_type},
721
+ )
722
+
723
+
724
+ def _material_findings(
725
+ *,
726
+ markdown: str,
727
+ ledger: ClaimLedger,
728
+ strict: bool,
729
+ stages: list[dict[str, Any]],
730
+ artifacts: list[dict[str, Any]],
731
+ ) -> list[dict[str, Any]]:
732
+ report = run_deterministic_audit(markdown, ledger)
733
+ harness = QualityHarnessAuditAgent().run_audit(markdown, ledger)
734
+ raw = [
735
+ finding
736
+ for finding in [*report.findings, *harness.findings]
737
+ if finding.finding_type
738
+ in {
739
+ "missing_claim",
740
+ "number_without_source",
741
+ "missing_source",
742
+ "needs_recrawl_claim_used",
743
+ "low_confidence_source_used",
744
+ "unsupported_certainty",
745
+ "low_source_density",
746
+ }
747
+ ]
748
+ findings = [
749
+ _map_audit_finding(
750
+ finding=finding,
751
+ idx=idx,
752
+ gate_id="material_fact",
753
+ strict=strict,
754
+ stages=stages,
755
+ artifacts=artifacts,
756
+ )
757
+ for idx, finding in enumerate(raw, start=1)
758
+ ]
759
+ findings.extend(
760
+ _unsupported_strategic_implication_findings(
761
+ markdown=markdown,
762
+ ledger=ledger,
763
+ start_idx=len(findings) + 1,
764
+ stages=stages,
765
+ artifacts=artifacts,
766
+ )
767
+ )
768
+ return findings
769
+
770
+
771
+ def _unsupported_strategic_implication_findings(
772
+ *,
773
+ markdown: str,
774
+ ledger: ClaimLedger,
775
+ start_idx: int,
776
+ stages: list[dict[str, Any]],
777
+ artifacts: list[dict[str, Any]],
778
+ ) -> list[dict[str, Any]]:
779
+ support_text = _claim_ledger_support_text(ledger)
780
+ normalized_markdown = markdown.lower()
781
+ findings: list[dict[str, Any]] = []
782
+ editor_stage = _stage_or_none(stages, "editor")
783
+ audited_artifact = _artifact_or_none(artifacts, "audited_brief")
784
+ for _phrase_id, variants in STRATEGIC_IMPLICATION_PHRASES:
785
+ matched_variant = next((variant for variant in variants if variant in normalized_markdown), "")
786
+ if not matched_variant:
787
+ continue
788
+ if any(variant in support_text for variant in variants):
789
+ continue
790
+ findings.append(
791
+ _finding(
792
+ finding_id=f"QG_MATERIAL_FACT_{start_idx + len(findings):03d}",
793
+ gate_id="material_fact",
794
+ finding_type="unsupported_strategic_implication",
795
+ severity="medium",
796
+ blocking_level="warning",
797
+ repair_owner="editor",
798
+ stage_id=editor_stage,
799
+ artifact_id=audited_artifact,
800
+ description=(
801
+ "The brief introduces a strategic implication or recommendation phrase "
802
+ f"('{matched_variant}') without matching Claim Ledger support."
803
+ ),
804
+ recommendation=(
805
+ "Downgrade or remove the implication, or add explicit Claim Ledger support through the "
806
+ "proper owner stages before presenting it as an implication."
807
+ ),
808
+ category="strategic_overreach",
809
+ line_number=_line_number_for_token(markdown, matched_variant),
810
+ evidence_ref=matched_variant,
811
+ metadata={
812
+ "matched_phrase": matched_variant,
813
+ "support_check": "lexical_phrase_absent_from_claim_ledger",
814
+ "semantic_boundary": (
815
+ "warning_only; Python flags lexical overreach risk but does not judge full strategic support"
816
+ ),
817
+ },
818
+ )
819
+ )
820
+ return findings
821
+
822
+
823
+ def _atomic_reader_projection_findings(
824
+ *,
825
+ projection: dict[str, Any],
826
+ start_idx: int,
827
+ stages: list[dict[str, Any]],
828
+ artifacts: list[dict[str, Any]],
829
+ reader_facing_mode: bool,
830
+ ) -> list[dict[str, Any]]:
831
+ residue_findings = projection.get("atom_residue_findings")
832
+ if not isinstance(residue_findings, list):
833
+ return []
834
+ stage_id = _stage_or_none(stages, "editor")
835
+ artifact_id = _artifact_or_none(artifacts, "reader_brief" if reader_facing_mode else "audited_brief")
836
+ findings: list[dict[str, Any]] = []
837
+ for item in residue_findings:
838
+ if not isinstance(item, dict):
839
+ continue
840
+ raw_type = str(item.get("finding_type") or "")
841
+ if raw_type == "atomic_graph_process_residue":
842
+ finding_type = "atomic_graph_process_residue"
843
+ description = "Reader-facing text contains Atomic Claim Graph process wording."
844
+ else:
845
+ finding_type = "atomic_atom_id_residue"
846
+ description = "Reader-facing text contains an Atomic Claim Graph atom ID."
847
+ evidence_ref = str(item.get("atom_id") or item.get("text") or "")
848
+ findings.append(
849
+ _finding(
850
+ finding_id=f"QG_MATERIAL_FACT_{start_idx + len(findings):03d}",
851
+ gate_id="material_fact",
852
+ finding_type=finding_type,
853
+ severity="medium",
854
+ blocking_level="warning",
855
+ repair_owner="editor",
856
+ stage_id=stage_id,
857
+ artifact_id=artifact_id,
858
+ claim_id=item.get("claim_id") if isinstance(item.get("claim_id"), str) else None,
859
+ description=description,
860
+ recommendation=(
861
+ "Remove Atomic Claim Graph residue from reader-facing prose and preserve only "
862
+ "`[src:<claim_id>]` Claim Ledger citations."
863
+ ),
864
+ category="atomic_reader_residue",
865
+ line_number=item.get("line") if isinstance(item.get("line"), int) else None,
866
+ evidence_ref=evidence_ref,
867
+ metadata={
868
+ "target_artifact": projection.get("target_artifact"),
869
+ "projection_status": projection.get("status"),
870
+ "semantic_boundary": projection.get("semantic_boundary"),
871
+ "raw_projection_finding": item,
872
+ },
873
+ )
874
+ )
875
+ return findings
876
+
877
+
878
+ def _claim_support_matrix_findings(
879
+ *,
880
+ projection: dict[str, Any],
881
+ start_idx: int,
882
+ stages: list[dict[str, Any]],
883
+ artifacts: list[dict[str, Any]],
884
+ reader_facing_mode: bool,
885
+ ) -> list[dict[str, Any]]:
886
+ if projection.get("status") != "valid":
887
+ return []
888
+ policy_projection = projection.get("policy_projection")
889
+ atoms = policy_projection.get("atoms") if isinstance(policy_projection, dict) else None
890
+ if not isinstance(atoms, list):
891
+ return []
892
+
893
+ findings: list[dict[str, Any]] = []
894
+ emitted_row_ids: set[str] = set()
895
+ for atom in atoms:
896
+ if not isinstance(atom, dict):
897
+ continue
898
+ for row in _row_list(atom.get("blocking_rows")):
899
+ _append_claim_support_matrix_finding(
900
+ findings,
901
+ row=row,
902
+ atom=atom,
903
+ start_idx=start_idx,
904
+ finding_type="claim_support_matrix_blocking_support",
905
+ severity="high",
906
+ blocking_level="blocking",
907
+ description="Claim-Support Matrix records a high-materiality atom with blocking support state.",
908
+ recommendation=(
909
+ "Do not release this wording as supported. Follow the matrix required_action, "
910
+ "or route repair/human review through the declared owner."
911
+ ),
912
+ stages=stages,
913
+ artifacts=artifacts,
914
+ reader_facing_mode=reader_facing_mode,
915
+ emitted_row_ids=emitted_row_ids,
916
+ projection=projection,
917
+ )
918
+ for row in [
919
+ *_row_list(atom.get("weak_rows")),
920
+ *_row_list(atom.get("downgrade_required_rows")),
921
+ *_row_list(atom.get("adjudication_required_rows")),
922
+ ]:
923
+ _append_claim_support_matrix_finding(
924
+ findings,
925
+ row=row,
926
+ atom=atom,
927
+ start_idx=start_idx,
928
+ finding_type="claim_support_matrix_weak_support",
929
+ severity="medium",
930
+ blocking_level="warning",
931
+ description="Claim-Support Matrix records weak support, downgrade, or adjudication need.",
932
+ recommendation=(
933
+ "Downgrade the wording or complete the declared adjudication/repair path before "
934
+ "treating the atom as cleanly supported."
935
+ ),
936
+ stages=stages,
937
+ artifacts=artifacts,
938
+ reader_facing_mode=reader_facing_mode,
939
+ emitted_row_ids=emitted_row_ids,
940
+ projection=projection,
941
+ )
942
+ for row in _row_list(atom.get("inference_framing_required_rows")):
943
+ _append_claim_support_matrix_finding(
944
+ findings,
945
+ row=row,
946
+ atom=atom,
947
+ start_idx=start_idx,
948
+ finding_type="claim_support_matrix_inference_framing",
949
+ severity="medium",
950
+ blocking_level="warning",
951
+ description="Claim-Support Matrix records inferential support that needs explicit framing.",
952
+ recommendation=(
953
+ "Frame this statement as an inference or clarify the inference boundary in reader-facing prose."
954
+ ),
955
+ stages=stages,
956
+ artifacts=artifacts,
957
+ reader_facing_mode=reader_facing_mode,
958
+ emitted_row_ids=emitted_row_ids,
959
+ projection=projection,
960
+ )
961
+ return findings
962
+
963
+
964
+ def _row_list(value: Any) -> list[dict[str, Any]]:
965
+ return [item for item in value if isinstance(item, dict)] if isinstance(value, list) else []
966
+
967
+
968
+ def _append_claim_support_matrix_finding(
969
+ findings: list[dict[str, Any]],
970
+ *,
971
+ row: dict[str, Any],
972
+ atom: dict[str, Any],
973
+ start_idx: int,
974
+ finding_type: str,
975
+ severity: str,
976
+ blocking_level: str,
977
+ description: str,
978
+ recommendation: str,
979
+ stages: list[dict[str, Any]],
980
+ artifacts: list[dict[str, Any]],
981
+ reader_facing_mode: bool,
982
+ emitted_row_ids: set[str],
983
+ projection: dict[str, Any],
984
+ ) -> None:
985
+ row_id = str(row.get("row_id") or "")
986
+ if row_id and row_id in emitted_row_ids:
987
+ return
988
+ if row_id:
989
+ emitted_row_ids.add(row_id)
990
+
991
+ repair_owner = str(row.get("repair_owner") or "human_review")
992
+ stage_id = _claim_support_repair_stage(repair_owner, stages)
993
+ artifact_id = _claim_support_repair_artifact(
994
+ repair_owner=repair_owner,
995
+ artifacts=artifacts,
996
+ reader_facing_mode=reader_facing_mode,
997
+ )
998
+ row_action = str(row.get("required_action") or "unknown")
999
+ row_label = str(row.get("support_label") or "unknown")
1000
+ atom_id = str(row.get("atom_id") or atom.get("atom_id") or "")
1001
+ findings.append(
1002
+ _finding(
1003
+ finding_id=f"QG_MATERIAL_FACT_{start_idx + len(findings):03d}",
1004
+ gate_id="material_fact",
1005
+ finding_type=finding_type,
1006
+ severity=severity,
1007
+ blocking_level=blocking_level,
1008
+ repair_owner=repair_owner if repair_owner else "human_review",
1009
+ stage_id=stage_id,
1010
+ artifact_id=artifact_id,
1011
+ claim_id=str(row.get("claim_id") or "") or None,
1012
+ source_id=None,
1013
+ description=f"{description} row={row_id or 'unknown'} atom={atom_id} label={row_label}.",
1014
+ recommendation=f"{recommendation} required_action={row_action}.",
1015
+ category="claim_support_matrix",
1016
+ evidence_ref=row_id,
1017
+ metadata={
1018
+ "row": row,
1019
+ "atom_id": atom_id,
1020
+ "atom_materiality": atom.get("materiality"),
1021
+ "atom_verdict": atom.get("verdict"),
1022
+ "matrix_status": projection.get("status"),
1023
+ "semantic_boundary": projection.get("semantic_boundary"),
1024
+ },
1025
+ )
1026
+ )
1027
+
1028
+
1029
+ def _claim_support_repair_stage(repair_owner: str, stages: list[dict[str, Any]]) -> str | None:
1030
+ if repair_owner in {"analyst", "editor", "auditor", "claim-ledger"}:
1031
+ return _stage_or_none(stages, repair_owner)
1032
+ return None
1033
+
1034
+
1035
+ def _claim_support_repair_artifact(
1036
+ *,
1037
+ repair_owner: str,
1038
+ artifacts: list[dict[str, Any]],
1039
+ reader_facing_mode: bool,
1040
+ ) -> str | None:
1041
+ if repair_owner == "claim-ledger":
1042
+ return _artifact_or_none(artifacts, "claim_ledger")
1043
+ if repair_owner == "editor":
1044
+ if reader_facing_mode:
1045
+ return _artifact_or_none(artifacts, "reader_brief")
1046
+ return _artifact_or_none(artifacts, "audited_brief")
1047
+ if repair_owner == "auditor":
1048
+ return _artifact_or_none(artifacts, "audit_report")
1049
+ return None
1050
+
1051
+
1052
+ def _claim_ledger_support_text(ledger: ClaimLedger) -> str:
1053
+ parts: list[str] = []
1054
+ for claim in ledger:
1055
+ parts.extend([
1056
+ claim.statement,
1057
+ claim.evidence_text,
1058
+ claim.applicability_reason,
1059
+ ])
1060
+ for value in claim.metadata.values():
1061
+ if isinstance(value, str):
1062
+ parts.append(value)
1063
+ elif isinstance(value, list):
1064
+ parts.extend(str(item) for item in value if isinstance(item, str))
1065
+ return "\n".join(part for part in parts if isinstance(part, str)).lower()
1066
+
1067
+
1068
+ HIGH_PRIORITY_SCREENING_VALUES = {"high", "critical", "blocking", "direct", "must_include", "must-include"}
1069
+ COVERAGE_LIMITATION_FIELDS = (
1070
+ "omission_reason",
1071
+ "coverage_limitation",
1072
+ "limitation",
1073
+ "limitations",
1074
+ "limitation_reason",
1075
+ "not_included_reason",
1076
+ "scope_reason",
1077
+ "defer_reason",
1078
+ "deferred_reason",
1079
+ )
1080
+ COVERAGE_LIMITATION_WORDS = (
1081
+ "limitation",
1082
+ "limitations",
1083
+ "scope",
1084
+ "scoped out",
1085
+ "not covered",
1086
+ "not included",
1087
+ "omitted",
1088
+ "deferred",
1089
+ "排除",
1090
+ "范围",
1091
+ "限制",
1092
+ "未覆盖",
1093
+ "未纳入",
1094
+ "省略",
1095
+ )
1096
+
1097
+
1098
+ def _coverage_omission_projection(
1099
+ *,
1100
+ workspace: Path | None,
1101
+ markdown: str,
1102
+ ledger: ClaimLedger,
1103
+ reader_facing_mode: bool = False,
1104
+ ) -> dict[str, Any]:
1105
+ base: dict[str, Any] = {
1106
+ "status": "not_available",
1107
+ "semantic_boundary": (
1108
+ "deterministic_selected_candidate_continuity_only; not full-world recall, semantic proof, "
1109
+ "or source-discovery completeness"
1110
+ ),
1111
+ "reader_facing_mode": reader_facing_mode,
1112
+ "selected_count": 0,
1113
+ "high_priority_selected_count": 0,
1114
+ "missing_from_ledger_count": 0,
1115
+ "missing_from_brief_count": 0,
1116
+ "missing_from_brief_check": (
1117
+ "skipped_reader_facing_no_internal_claim_refs"
1118
+ if reader_facing_mode
1119
+ else "internal_claim_ref_citation_continuity"
1120
+ ),
1121
+ "not_interpreted_reason": "",
1122
+ }
1123
+ if workspace is None:
1124
+ base["not_interpreted_reason"] = "workspace_not_provided"
1125
+ return base
1126
+
1127
+ path = workspace / "output" / "intermediate" / "screened_candidates.json"
1128
+ if not path.exists():
1129
+ base["status"] = "missing"
1130
+ base["not_interpreted_reason"] = "screened_candidates_missing"
1131
+ return base
1132
+ try:
1133
+ payload = json.loads(path.read_text(encoding="utf-8"))
1134
+ except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc:
1135
+ base["status"] = "invalid"
1136
+ base["not_interpreted_reason"] = f"screened_candidates_unreadable:{type(exc).__name__}"
1137
+ return base
1138
+
1139
+ artifact_status, validation_result = _validate_screened_candidates_payload(payload)
1140
+ base["screened_candidates_validation_result"] = validation_result
1141
+ if artifact_status != ARTIFACT_VALID:
1142
+ base["status"] = "invalid"
1143
+ base["not_interpreted_reason"] = validation_result
1144
+ return base
1145
+ if not isinstance(payload, dict):
1146
+ base["status"] = "legacy_not_interpreted"
1147
+ base["not_interpreted_reason"] = "legacy_list_shape_has_no_selected_bucket"
1148
+ return base
1149
+
1150
+ selected = [item for item in payload.get("selected") or [] if isinstance(item, dict)]
1151
+ high_priority = [candidate for candidate in selected if _screened_candidate_is_high_priority(candidate)]
1152
+ base["status"] = "checked"
1153
+ base["selected_count"] = len(selected)
1154
+ base["high_priority_selected_count"] = len(high_priority)
1155
+ base["trace_basis"] = "candidate_id_or_exact_statement"
1156
+
1157
+ cited_claim_ids = set(SRC_REF_PATTERN.findall(markdown))
1158
+ missing_from_ledger: list[dict[str, Any]] = []
1159
+ missing_from_brief: list[dict[str, Any]] = []
1160
+ scoped_out: list[dict[str, Any]] = []
1161
+ untraceable: list[dict[str, Any]] = []
1162
+
1163
+ for candidate in high_priority:
1164
+ trace = _screened_candidate_trace(candidate)
1165
+ if not trace["candidate_id"] and not trace["statement"]:
1166
+ untraceable.append(trace)
1167
+ continue
1168
+ limitation = _coverage_limitation_reason(candidate=candidate, markdown=markdown)
1169
+ matches = _matching_claims_for_screened_candidate(candidate, ledger)
1170
+ if not matches:
1171
+ if limitation:
1172
+ scoped_out.append({**trace, "limitation": limitation})
1173
+ continue
1174
+ missing_from_ledger.append(trace)
1175
+ continue
1176
+ cited_matches = [claim for claim in matches if claim.claim_id in cited_claim_ids]
1177
+ if reader_facing_mode:
1178
+ if limitation:
1179
+ scoped_out.append({**trace, "limitation": limitation})
1180
+ continue
1181
+ if not cited_matches and not limitation:
1182
+ missing_from_brief.append({
1183
+ **trace,
1184
+ "claim_ids": [claim.claim_id for claim in matches],
1185
+ "source_ids": [claim.source_id for claim in matches],
1186
+ })
1187
+ elif limitation:
1188
+ scoped_out.append({**trace, "limitation": limitation})
1189
+
1190
+ base.update(
1191
+ {
1192
+ "missing_from_ledger_count": len(missing_from_ledger),
1193
+ "missing_from_brief_count": len(missing_from_brief),
1194
+ "scoped_out_count": len(scoped_out),
1195
+ "untraceable_high_priority_count": len(untraceable),
1196
+ "missing_from_ledger": missing_from_ledger,
1197
+ "missing_from_brief": missing_from_brief,
1198
+ "scoped_out": scoped_out,
1199
+ "untraceable_high_priority": untraceable,
1200
+ }
1201
+ )
1202
+ return base
1203
+
1204
+
1205
+ def _coverage_omission_findings(
1206
+ *,
1207
+ projection: dict[str, Any],
1208
+ strict: bool,
1209
+ stages: list[dict[str, Any]],
1210
+ artifacts: list[dict[str, Any]],
1211
+ reader_facing_mode: bool,
1212
+ ) -> list[dict[str, Any]]:
1213
+ if projection.get("status") != "checked":
1214
+ return []
1215
+ findings: list[dict[str, Any]] = []
1216
+ blocking_level = _blocking_level(default_blocking=False, strict=strict)
1217
+ severity = "high" if blocking_level == "blocking" else "medium"
1218
+ ledger_stage = _stage_or_none(stages, "claim-ledger")
1219
+ ledger_artifact = _artifact_or_none(artifacts, "claim_ledger")
1220
+ editor_stage = _stage_or_none(stages, "editor")
1221
+ brief_artifact = _artifact_or_none(artifacts, "reader_brief" if reader_facing_mode else "audited_brief")
1222
+
1223
+ for item in _row_list(projection.get("missing_from_ledger")):
1224
+ findings.append(
1225
+ _finding(
1226
+ finding_id=f"QG_COVERAGE_OMISSION_{len(findings)+1:03d}",
1227
+ gate_id="coverage_omission",
1228
+ finding_type="selected_candidate_missing_from_ledger",
1229
+ severity=severity,
1230
+ blocking_level=blocking_level,
1231
+ repair_owner="claim-ledger",
1232
+ stage_id=ledger_stage,
1233
+ artifact_id=ledger_artifact,
1234
+ source_id=_text_or_none(item.get("source_id")),
1235
+ description=(
1236
+ "A high-priority selected screened candidate is not carried into the Claim Ledger "
1237
+ f"and has no explicit omission or limitation reason: {item.get('display') or 'unknown'}."
1238
+ ),
1239
+ recommendation=(
1240
+ "Carry the selected candidate into claim_drafts.json before freezing, or record an explicit "
1241
+ "scope/limitation reason instead of silently dropping it."
1242
+ ),
1243
+ category="coverage_gap",
1244
+ evidence_ref=_text_or_none(item.get("candidate_id")) or _text_or_none(item.get("statement")) or "",
1245
+ metadata={
1246
+ "screened_candidate": item,
1247
+ "semantic_boundary": projection.get("semantic_boundary"),
1248
+ },
1249
+ )
1250
+ )
1251
+ for item in _row_list(projection.get("missing_from_brief")):
1252
+ findings.append(
1253
+ _finding(
1254
+ finding_id=f"QG_COVERAGE_OMISSION_{len(findings)+1:03d}",
1255
+ gate_id="coverage_omission",
1256
+ finding_type="selected_candidate_missing_from_brief",
1257
+ severity=severity,
1258
+ blocking_level=blocking_level,
1259
+ repair_owner="editor",
1260
+ stage_id=editor_stage,
1261
+ artifact_id=brief_artifact,
1262
+ claim_id=_first_text(item.get("claim_ids")),
1263
+ source_id=_first_text(item.get("source_ids")) or _text_or_none(item.get("source_id")),
1264
+ description=(
1265
+ "A high-priority selected screened candidate reached the Claim Ledger but is not cited in "
1266
+ f"the brief and has no explicit omission or limitation reason: {item.get('display') or 'unknown'}."
1267
+ ),
1268
+ recommendation=(
1269
+ "Cite the corresponding Claim Ledger entry in the brief, or add an explicit scope/limitation "
1270
+ "reason for omitting the selected item."
1271
+ ),
1272
+ category="coverage_gap",
1273
+ evidence_ref=", ".join(str(claim_id) for claim_id in item.get("claim_ids") or []),
1274
+ metadata={
1275
+ "screened_candidate": item,
1276
+ "semantic_boundary": projection.get("semantic_boundary"),
1277
+ },
1278
+ )
1279
+ )
1280
+ return findings
1281
+
1282
+
1283
+ def _text_or_none(value: Any) -> str | None:
1284
+ if isinstance(value, str) and value.strip():
1285
+ return value.strip()
1286
+ return None
1287
+
1288
+
1289
+ def _first_text(value: Any) -> str | None:
1290
+ if isinstance(value, list):
1291
+ for item in value:
1292
+ text = _text_or_none(item)
1293
+ if text:
1294
+ return text
1295
+ return _text_or_none(value)
1296
+
1297
+
1298
+ def _screened_candidate_trace(candidate: dict[str, Any]) -> dict[str, Any]:
1299
+ candidate_id = _text_or_none(candidate.get("candidate_id"))
1300
+ statement = _text_or_none(candidate.get("statement")) or _text_or_none(candidate.get("claim"))
1301
+ source_id = _text_or_none(candidate.get("source_id"))
1302
+ source_title = _text_or_none(candidate.get("source_title")) or _text_or_none(candidate.get("title"))
1303
+ display = candidate_id or statement or source_title or source_id or "unknown"
1304
+ return {
1305
+ "candidate_id": candidate_id,
1306
+ "statement": statement,
1307
+ "source_id": source_id,
1308
+ "source_title": source_title,
1309
+ "display": display,
1310
+ "priority": _screened_candidate_priority_value(candidate),
1311
+ }
1312
+
1313
+
1314
+ def _screened_candidate_priority_value(candidate: dict[str, Any]) -> str:
1315
+ for container in (candidate, candidate.get("metadata") if isinstance(candidate.get("metadata"), dict) else {}):
1316
+ for key in ("priority", "importance", "materiality", "severity", "selected_priority"):
1317
+ value = container.get(key) if isinstance(container, dict) else None
1318
+ if isinstance(value, str) and value.strip():
1319
+ return value.strip().lower()
1320
+ if candidate.get("high_priority") is True:
1321
+ return "high"
1322
+ return ""
1323
+
1324
+
1325
+ def _screened_candidate_is_high_priority(candidate: dict[str, Any]) -> bool:
1326
+ return _screened_candidate_priority_value(candidate) in HIGH_PRIORITY_SCREENING_VALUES
1327
+
1328
+
1329
+ def _matching_claims_for_screened_candidate(candidate: dict[str, Any], ledger: ClaimLedger) -> list[Any]:
1330
+ candidate_id = _text_or_none(candidate.get("candidate_id"))
1331
+ explicit_claim_id = _text_or_none(candidate.get("claim_id"))
1332
+ normalized_statement = _normalize_candidate_statement(
1333
+ _text_or_none(candidate.get("statement")) or _text_or_none(candidate.get("claim")) or ""
1334
+ )
1335
+ matches: list[Any] = []
1336
+ for claim in ledger:
1337
+ metadata = claim.metadata if isinstance(claim.metadata, dict) else {}
1338
+ metadata_candidate_ids = _metadata_candidate_ids(metadata)
1339
+ if explicit_claim_id and claim.claim_id == explicit_claim_id:
1340
+ matches.append(claim)
1341
+ continue
1342
+ if candidate_id and candidate_id in metadata_candidate_ids:
1343
+ matches.append(claim)
1344
+ continue
1345
+ if not candidate_id and normalized_statement and _normalize_candidate_statement(claim.statement) == normalized_statement:
1346
+ matches.append(claim)
1347
+ return matches
1348
+
1349
+
1350
+ def _metadata_candidate_ids(metadata: dict[str, Any]) -> set[str]:
1351
+ values: set[str] = set()
1352
+ for key in ("candidate_id", "screened_candidate_id", "candidate_ids", "screened_candidate_ids"):
1353
+ value = metadata.get(key)
1354
+ if isinstance(value, str) and value.strip():
1355
+ values.add(value.strip())
1356
+ elif isinstance(value, list):
1357
+ values.update(str(item).strip() for item in value if str(item).strip())
1358
+ return values
1359
+
1360
+
1361
+ def _normalize_candidate_statement(value: str) -> str:
1362
+ return " ".join(value.lower().split()).strip(".,;:()[]{}")
1363
+
1364
+
1365
+ def _coverage_limitation_reason(*, candidate: dict[str, Any], markdown: str) -> str:
1366
+ for field in COVERAGE_LIMITATION_FIELDS:
1367
+ value = candidate.get(field)
1368
+ if isinstance(value, str) and value.strip():
1369
+ return f"{field}:{value.strip()}"
1370
+ if isinstance(value, list):
1371
+ joined = "; ".join(str(item).strip() for item in value if str(item).strip())
1372
+ if joined:
1373
+ return f"{field}:{joined}"
1374
+ tokens = [
1375
+ _text_or_none(candidate.get("candidate_id")),
1376
+ _text_or_none(candidate.get("source_id")),
1377
+ _text_or_none(candidate.get("source_title")),
1378
+ _text_or_none(candidate.get("title")),
1379
+ ]
1380
+ tokens = [token.lower() for token in tokens if token]
1381
+ if not tokens:
1382
+ return ""
1383
+ for line in markdown.splitlines():
1384
+ lower = line.lower()
1385
+ if any(word in lower for word in COVERAGE_LIMITATION_WORDS) and any(token in lower for token in tokens):
1386
+ return f"brief_limitation:{line.strip()}"
1387
+ return ""
1388
+
1389
+
1390
+ def _freshness_findings(
1391
+ *,
1392
+ markdown: str,
1393
+ ledger: ClaimLedger,
1394
+ report_date: str,
1395
+ max_source_age_days: int | None,
1396
+ strict: bool,
1397
+ stages: list[dict[str, Any]],
1398
+ artifacts: list[dict[str, Any]],
1399
+ ) -> list[dict[str, Any]]:
1400
+ report = run_deterministic_audit(
1401
+ markdown,
1402
+ ledger,
1403
+ report_date=report_date,
1404
+ max_source_age_days=max_source_age_days,
1405
+ fail_on_stale_source=strict,
1406
+ )
1407
+ raw = [
1408
+ finding
1409
+ for finding in report.findings
1410
+ if finding.finding_type in {"stale_source", "missing_source_date"}
1411
+ ]
1412
+ findings = [
1413
+ _map_audit_finding(
1414
+ finding=finding,
1415
+ idx=idx,
1416
+ gate_id="freshness",
1417
+ strict=strict,
1418
+ stages=stages,
1419
+ artifacts=artifacts,
1420
+ )
1421
+ for idx, finding in enumerate(raw, start=1)
1422
+ ]
1423
+ findings.extend(
1424
+ _market_quote_metadata_findings(
1425
+ ledger=ledger,
1426
+ strict=strict,
1427
+ stages=stages,
1428
+ artifacts=artifacts,
1429
+ start_idx=len(findings) + 1,
1430
+ )
1431
+ )
1432
+ return findings
1433
+
1434
+
1435
+ def _normalize_fact_token(value: str) -> str:
1436
+ return " ".join(value.strip().split()).strip(".,;:()[]{}").lower()
1437
+
1438
+
1439
+ def _token_map(pattern: re.Pattern[str], text: str) -> dict[str, str]:
1440
+ tokens: dict[str, str] = {}
1441
+ for match in pattern.finditer(text):
1442
+ raw = match.group(0).strip()
1443
+ normalized = _normalize_fact_token(raw.replace(",", ""))
1444
+ if normalized:
1445
+ tokens.setdefault(normalized, raw)
1446
+ return tokens
1447
+
1448
+
1449
+ def _claim_ref_map(text: str) -> dict[str, str]:
1450
+ return {claim_id.lower(): claim_id for claim_id in SRC_REF_PATTERN.findall(text)}
1451
+
1452
+
1453
+ def _entity_map(text: str) -> dict[str, str]:
1454
+ entities: dict[str, str] = {}
1455
+ in_code_block = False
1456
+ for line in text.splitlines():
1457
+ stripped = line.strip()
1458
+ if stripped.startswith("```") or stripped.startswith("~~~"):
1459
+ in_code_block = not in_code_block
1460
+ continue
1461
+ if in_code_block:
1462
+ continue
1463
+ if not stripped or stripped.startswith("#"):
1464
+ continue
1465
+ line_body = re.sub(r"^(?:[-*+]|\d+[.)])\s+", "", stripped)
1466
+ entities.update(_token_map(ENTITY_RE, line_body))
1467
+ stop = {_normalize_fact_token(item): item for item in ENTITY_STOP_PHRASES}
1468
+ return {key: value for key, value in entities.items() if key not in stop}
1469
+
1470
+
1471
+ def _line_number_for_token(text: str, token: str) -> int | None:
1472
+ normalized_token = token.lower()
1473
+ for idx, line in enumerate(text.splitlines(), start=1):
1474
+ if normalized_token in line.lower():
1475
+ return idx
1476
+ return None
1477
+
1478
+
1479
+ def _editor_introduced_new_fact_findings(
1480
+ *,
1481
+ markdown: str,
1482
+ analyst_markdown: str | None,
1483
+ config: dict[str, Any],
1484
+ user_text: str,
1485
+ strict: bool,
1486
+ stages: list[dict[str, Any]],
1487
+ artifacts: list[dict[str, Any]],
1488
+ ) -> list[dict[str, Any]]:
1489
+ if analyst_markdown is None:
1490
+ return []
1491
+
1492
+ introduced_numbers = sorted(
1493
+ set(_token_map(FACT_NUMBER_RE, markdown)) - set(_token_map(FACT_NUMBER_RE, analyst_markdown))
1494
+ )
1495
+ introduced_claim_ids = sorted(set(_claim_ref_map(markdown)) - set(_claim_ref_map(analyst_markdown)))
1496
+ allowed_metadata_entities = _declared_metadata_entity_tokens(config=config, user_text=user_text)
1497
+ introduced_entities = sorted(
1498
+ set(_entity_map(markdown)) - set(_entity_map(analyst_markdown)) - allowed_metadata_entities
1499
+ )
1500
+ if not introduced_numbers and not introduced_claim_ids and not introduced_entities:
1501
+ return []
1502
+
1503
+ number_values = _token_map(FACT_NUMBER_RE, markdown)
1504
+ claim_values = _claim_ref_map(markdown)
1505
+ entity_values = _entity_map(markdown)
1506
+ samples = {
1507
+ "numbers": [number_values[item] for item in introduced_numbers[:5]],
1508
+ "claim_ids": [claim_values[item] for item in introduced_claim_ids[:5]],
1509
+ "entities": [entity_values[item] for item in introduced_entities[:5]],
1510
+ }
1511
+ sample_text = ", ".join(value for values in samples.values() for value in values)
1512
+ first_sample = next((value for values in samples.values() for value in values), "")
1513
+ blocking_level = _blocking_level(default_blocking=False, strict=strict)
1514
+ return [
1515
+ _finding(
1516
+ finding_id="QG_EDITOR_NEW_FACT_001",
1517
+ gate_id="editor_new_fact",
1518
+ finding_type="editor_introduced_new_fact",
1519
+ severity="high" if blocking_level == "blocking" else "medium",
1520
+ blocking_level=blocking_level,
1521
+ repair_owner="editor",
1522
+ stage_id=_stage_or_none(stages, "editor"),
1523
+ artifact_id=_artifact_or_none(artifacts, "audited_brief"),
1524
+ line_number=_line_number_for_token(markdown, first_sample) if first_sample else None,
1525
+ description=(
1526
+ "Delivery Editor introduced factual tokens that were absent from the Analyst draft"
1527
+ + (f": {sample_text}." if sample_text else ".")
1528
+ ),
1529
+ recommendation=(
1530
+ "Remove the editor-introduced fact, or route the intended factual addition back through "
1531
+ "Analyst and Claim Ledger before editing."
1532
+ ),
1533
+ category="editorial_governance",
1534
+ metadata={
1535
+ "analyst_draft_snapshot": ANALYST_DRAFT_SNAPSHOT_FILE,
1536
+ "introduced_numbers": samples["numbers"],
1537
+ "introduced_claim_ids": samples["claim_ids"],
1538
+ "introduced_entities": samples["entities"],
1539
+ "ignored_declared_metadata_entities": sorted(allowed_metadata_entities),
1540
+ "strict": strict,
1541
+ },
1542
+ )
1543
+ ]
1544
+
1545
+
1546
+ def _final_abstract_quality_findings(
1547
+ *,
1548
+ markdown: str,
1549
+ config: dict[str, Any],
1550
+ reader_facing_mode: bool,
1551
+ stages: list[dict[str, Any]],
1552
+ artifacts: list[dict[str, Any]],
1553
+ ) -> list[dict[str, Any]]:
1554
+ """Surface deterministic final-quality risks as warning-only findings."""
1555
+
1556
+ stage_id = _stage_or_none(stages, "editor")
1557
+ artifact_id = _artifact_or_none(artifacts, "reader_brief" if reader_facing_mode else "audited_brief")
1558
+ findings: list[dict[str, Any]] = []
1559
+
1560
+ def append_finding(
1561
+ *,
1562
+ finding_type: str,
1563
+ description: str,
1564
+ recommendation: str,
1565
+ category: str,
1566
+ line_number: int | None = None,
1567
+ evidence_ref: str = "",
1568
+ metadata: dict[str, Any] | None = None,
1569
+ ) -> None:
1570
+ finding = _finding(
1571
+ finding_id=f"QG_FINAL_ABSTRACT_QUALITY_{len(findings)+1:03d}",
1572
+ gate_id="final_abstract_quality",
1573
+ finding_type=finding_type,
1574
+ severity="medium",
1575
+ blocking_level="warning",
1576
+ repair_owner="none",
1577
+ stage_id=stage_id,
1578
+ artifact_id=artifact_id,
1579
+ description=description,
1580
+ recommendation=recommendation,
1581
+ category=category,
1582
+ line_number=line_number,
1583
+ evidence_ref=evidence_ref,
1584
+ metadata={
1585
+ "semantic_boundary": (
1586
+ "warning_only_deterministic_pattern_surface; not a prose-quality score, "
1587
+ "truth proof, release authority, delivery approval, or repair authority"
1588
+ ),
1589
+ "repair_boundary": "advisory_non_routable",
1590
+ **(metadata or {}),
1591
+ },
1592
+ )
1593
+ finding["repair_stage_id"] = None
1594
+ finding["repair_artifact_id"] = None
1595
+ findings.append(finding)
1596
+
1597
+ title = _first_markdown_h1(markdown)
1598
+ expected_cadence = _configured_report_cadence(config)
1599
+ title_cadence = _title_cadence(title)
1600
+ if expected_cadence and title_cadence and expected_cadence != title_cadence:
1601
+ append_finding(
1602
+ finding_type="final_scope_title_mismatch",
1603
+ description=(
1604
+ f"Report title cadence appears to be {title_cadence}, but workspace config expects "
1605
+ f"{expected_cadence}."
1606
+ ),
1607
+ recommendation="Align the title with the configured report cadence or update config/report_spec before delivery.",
1608
+ category="final_abstract_quality",
1609
+ line_number=_line_number_for_token(markdown, title) if title else None,
1610
+ evidence_ref=title,
1611
+ metadata={"expected_cadence": expected_cadence, "title_cadence": title_cadence},
1612
+ )
1613
+
1614
+ comparison_line = _first_body_line_matching(markdown, FINAL_ABSTRACT_COMPARISON_RE)
1615
+ has_comparison = comparison_line is not None
1616
+ if has_comparison and not _has_markdown_heading(markdown, FINAL_ABSTRACT_BASIS_HEADING_RE):
1617
+ append_finding(
1618
+ finding_type="final_missing_comparison_basis",
1619
+ description="The brief uses comparison framing without an explicit basis, method, benchmark, or scope section.",
1620
+ recommendation="Add a comparison basis/methodology/scope section or downgrade the comparison wording.",
1621
+ category="final_abstract_quality",
1622
+ line_number=comparison_line[0],
1623
+ evidence_ref=comparison_line[1],
1624
+ metadata={"matched_pattern": "comparison_without_basis_section"},
1625
+ )
1626
+
1627
+ risk_line = _first_body_line_matching(
1628
+ markdown,
1629
+ re.compile(
1630
+ "|".join(
1631
+ [
1632
+ FINAL_ABSTRACT_RECOMMENDATION_RE.pattern,
1633
+ FINAL_ABSTRACT_COMPARISON_RE.pattern,
1634
+ FINAL_ABSTRACT_SUPERLATIVE_RE.pattern,
1635
+ ]
1636
+ ),
1637
+ re.IGNORECASE,
1638
+ ),
1639
+ )
1640
+ if risk_line and not _has_markdown_heading(markdown, FINAL_ABSTRACT_LIMITATION_HEADING_RE):
1641
+ append_finding(
1642
+ finding_type="final_missing_limitation_section",
1643
+ description=(
1644
+ "The brief uses recommendation, forecast, comparison, or superlative framing without a "
1645
+ "limitations, assumptions, or scope section."
1646
+ ),
1647
+ recommendation="Add a limitations/scope/assumptions section or soften the abstract framing.",
1648
+ category="final_abstract_quality",
1649
+ line_number=risk_line[0],
1650
+ evidence_ref=risk_line[1],
1651
+ metadata={"matched_pattern": "risk_framing_without_limitation_section"},
1652
+ )
1653
+
1654
+ for line_number, line in _key_case_lines(markdown):
1655
+ missing = [
1656
+ field
1657
+ for field, pattern in FINAL_ABSTRACT_CASE_FIELD_PATTERNS.items()
1658
+ if not pattern.search(line)
1659
+ ]
1660
+ if missing:
1661
+ append_finding(
1662
+ finding_type="final_incomplete_key_case_fields",
1663
+ description=f"Key-case entry is missing required deterministic fields: {', '.join(missing)}.",
1664
+ recommendation="Add date/period, source reference, and impact/relevance fields to key-case entries.",
1665
+ category="final_abstract_quality",
1666
+ line_number=line_number,
1667
+ evidence_ref=line,
1668
+ metadata={"missing_fields": missing},
1669
+ )
1670
+
1671
+ for line_number, line in _unsupported_superlative_lines(markdown):
1672
+ append_finding(
1673
+ finding_type="final_unsupported_superlative",
1674
+ description="Superlative wording appears without a local citation or source reference on the same line.",
1675
+ recommendation="Attach explicit local support for the superlative or downgrade the wording.",
1676
+ category="final_abstract_quality",
1677
+ line_number=line_number,
1678
+ evidence_ref=line,
1679
+ metadata={"matched_pattern": "superlative_without_local_reference"},
1680
+ )
1681
+
1682
+ return findings
1683
+
1684
+
1685
+ def _configured_report_cadence(config: dict[str, Any]) -> str:
1686
+ candidates: list[Any] = []
1687
+ report = config.get("report")
1688
+ if isinstance(report, dict):
1689
+ candidates.append(report.get("cadence"))
1690
+ candidates.append(config.get("cadence"))
1691
+ for value in candidates:
1692
+ normalized = _normalize_cadence(value)
1693
+ if normalized:
1694
+ return normalized
1695
+ return ""
1696
+
1697
+
1698
+ def _normalize_cadence(value: Any) -> str:
1699
+ if not isinstance(value, str):
1700
+ return ""
1701
+ normalized = value.strip().lower().replace("_", "-")
1702
+ if normalized in {"weekly", "week", "周报", "weekly-report"}:
1703
+ return "weekly"
1704
+ if normalized in {"monthly", "month", "月报", "monthly-report"}:
1705
+ return "monthly"
1706
+ return ""
1707
+
1708
+
1709
+ def _title_cadence(title: str) -> str:
1710
+ lower = title.lower()
1711
+ if "weekly" in lower or "周报" in title:
1712
+ return "weekly"
1713
+ if "monthly" in lower or "月报" in title:
1714
+ return "monthly"
1715
+ return ""
1716
+
1717
+
1718
+ def _first_markdown_h1(markdown: str) -> str:
1719
+ for line in markdown.splitlines():
1720
+ stripped = line.strip()
1721
+ if stripped.startswith("# ") and not stripped.startswith("## "):
1722
+ return stripped[2:].strip(" #")
1723
+ return ""
1724
+
1725
+
1726
+ def _has_markdown_heading(markdown: str, pattern: re.Pattern[str]) -> bool:
1727
+ for line in markdown.splitlines():
1728
+ stripped = line.strip()
1729
+ if not stripped.startswith("#"):
1730
+ continue
1731
+ heading = stripped.lstrip("#").strip()
1732
+ if pattern.search(heading):
1733
+ return True
1734
+ return False
1735
+
1736
+
1737
+ def _first_body_line_matching(markdown: str, pattern: re.Pattern[str]) -> tuple[int, str] | None:
1738
+ for line_number, line in _body_lines(markdown):
1739
+ if pattern.search(line):
1740
+ return line_number, line
1741
+ return None
1742
+
1743
+
1744
+ def _body_lines(markdown: str) -> list[tuple[int, str]]:
1745
+ lines: list[tuple[int, str]] = []
1746
+ in_code_block = False
1747
+ in_source_section = False
1748
+ for line_number, line in enumerate(markdown.splitlines(), start=1):
1749
+ stripped = line.strip()
1750
+ if stripped.startswith("```") or stripped.startswith("~~~"):
1751
+ in_code_block = not in_code_block
1752
+ continue
1753
+ if in_code_block:
1754
+ continue
1755
+ if stripped.startswith("#"):
1756
+ heading = stripped.lstrip("#").strip()
1757
+ in_source_section = bool(FINAL_ABSTRACT_SOURCE_HEADING_RE.search(heading))
1758
+ continue
1759
+ if in_source_section or not stripped:
1760
+ continue
1761
+ lines.append((line_number, stripped))
1762
+ return lines
1763
+
1764
+
1765
+ def _key_case_lines(markdown: str) -> list[tuple[int, str]]:
1766
+ results: list[tuple[int, str]] = []
1767
+ in_case_section = False
1768
+ case_level: int | None = None
1769
+ for line_number, line in enumerate(markdown.splitlines(), start=1):
1770
+ stripped = line.strip()
1771
+ if not stripped:
1772
+ continue
1773
+ heading_level = _markdown_heading_level(stripped)
1774
+ if heading_level is not None:
1775
+ heading = stripped.lstrip("#").strip()
1776
+ if FINAL_ABSTRACT_CASE_HEADING_RE.search(heading):
1777
+ in_case_section = True
1778
+ case_level = heading_level
1779
+ elif in_case_section and case_level is not None and heading_level <= case_level:
1780
+ in_case_section = False
1781
+ continue
1782
+ if not in_case_section:
1783
+ continue
1784
+ if re.match(r"^(?:[-*+]|\d+[.)])\s+", stripped):
1785
+ results.append((line_number, stripped))
1786
+ return results
1787
+
1788
+
1789
+ def _markdown_heading_level(stripped_line: str) -> int | None:
1790
+ if not stripped_line.startswith("#"):
1791
+ return None
1792
+ marker = stripped_line.split(maxsplit=1)[0]
1793
+ if set(marker) == {"#"}:
1794
+ return len(marker)
1795
+ return None
1796
+
1797
+
1798
+ def _unsupported_superlative_lines(markdown: str) -> list[tuple[int, str]]:
1799
+ findings: list[tuple[int, str]] = []
1800
+ for line_number, line in _body_lines(markdown):
1801
+ if not FINAL_ABSTRACT_SUPERLATIVE_RE.search(line):
1802
+ continue
1803
+ if _line_has_local_source_reference(line):
1804
+ continue
1805
+ findings.append((line_number, line))
1806
+ if len(findings) >= 3:
1807
+ break
1808
+ return findings
1809
+
1810
+
1811
+ def _line_has_local_source_reference(line: str) -> bool:
1812
+ return bool(
1813
+ SRC_REF_PATTERN.search(line)
1814
+ or re.search(r"\[S\d+\]", line)
1815
+ or re.search(r"https?://", line, re.IGNORECASE)
1816
+ )
1817
+
1818
+
1819
+ def _market_quote_metadata_findings(
1820
+ *,
1821
+ ledger: ClaimLedger,
1822
+ strict: bool,
1823
+ stages: list[dict[str, Any]],
1824
+ artifacts: list[dict[str, Any]],
1825
+ start_idx: int,
1826
+ ) -> list[dict[str, Any]]:
1827
+ findings: list[dict[str, Any]] = []
1828
+ stage_id = _stage_or_none(stages, "claim-ledger")
1829
+ artifact_id = _artifact_or_none(artifacts, "claim_ledger")
1830
+ for claim in ledger:
1831
+ metadata = claim.metadata or {}
1832
+ has_quote = any(key in metadata for key in ("ticker", "price", "as_of", "quote_source"))
1833
+ if not has_quote:
1834
+ continue
1835
+ missing = [
1836
+ key
1837
+ for key in ("ticker", "price", "as_of")
1838
+ if metadata.get(key) in {None, ""}
1839
+ ]
1840
+ if not (metadata.get("source") or metadata.get("quote_source")):
1841
+ missing.append("source")
1842
+ if not missing:
1843
+ continue
1844
+ blocking_level = _blocking_level(default_blocking=False, strict=strict)
1845
+ findings.append(
1846
+ _finding(
1847
+ finding_id=f"QG_FRESHNESS_{start_idx + len(findings):03d}",
1848
+ gate_id="freshness",
1849
+ finding_type="market_quote_metadata_incomplete",
1850
+ severity="high",
1851
+ blocking_level=blocking_level,
1852
+ repair_owner="claim-ledger",
1853
+ stage_id=stage_id,
1854
+ artifact_id=artifact_id,
1855
+ claim_id=claim.claim_id,
1856
+ source_id=claim.source_id,
1857
+ description=f"Market quote metadata is incomplete for claim {claim.claim_id}: missing {', '.join(missing)}.",
1858
+ recommendation="Populate ticker, price, as_of, and source metadata before treating the quote as current.",
1859
+ category="stale_source",
1860
+ metadata={"missing_fields": missing},
1861
+ )
1862
+ )
1863
+ return findings
1864
+
1865
+
1866
+ def _section_between(content: str, start_patterns: tuple[str, ...]) -> str:
1867
+ lines = content.splitlines()
1868
+ start_idx: int | None = None
1869
+ for idx, line in enumerate(lines):
1870
+ lower = line.strip().lower()
1871
+ if any(pattern in lower for pattern in start_patterns):
1872
+ start_idx = idx + 1
1873
+ break
1874
+ if start_idx is None:
1875
+ return ""
1876
+ end_idx = len(lines)
1877
+ for idx in range(start_idx, len(lines)):
1878
+ if lines[idx].startswith("## "):
1879
+ end_idx = idx
1880
+ break
1881
+ return "\n".join(lines[start_idx:end_idx])
1882
+
1883
+
1884
+ def _target_terms(config: dict[str, Any], *, user_text: str = "") -> list[str]:
1885
+ terms: list[str] = []
1886
+ project = config.get("project") or {}
1887
+ if isinstance(project, dict):
1888
+ for key in ("name", "target", "company", "organization"):
1889
+ value = project.get(key)
1890
+ if isinstance(value, str) and value.strip():
1891
+ terms.append(value.strip())
1892
+ for key in ("target", "company", "organization"):
1893
+ value = config.get(key)
1894
+ if isinstance(value, str) and value.strip():
1895
+ terms.append(value.strip())
1896
+ if user_text:
1897
+ for marker in ("Target:", "Company:", "Organization:", "目标:", "公司:"):
1898
+ for line in user_text.splitlines():
1899
+ if marker in line:
1900
+ value = line.split(marker, 1)[1].strip(" #:-")
1901
+ if value:
1902
+ terms.append(value)
1903
+ seen: set[str] = set()
1904
+ result: list[str] = []
1905
+ for term in terms:
1906
+ normalized = " ".join(term.split()).lower()
1907
+ if normalized and normalized not in seen:
1908
+ seen.add(normalized)
1909
+ result.append(term)
1910
+ return result
1911
+
1912
+
1913
+ def _declared_metadata_entity_tokens(*, config: dict[str, Any], user_text: str) -> set[str]:
1914
+ tokens: set[str] = set()
1915
+ for term in _target_terms(config, user_text=user_text):
1916
+ tokens.update(_entity_map(term))
1917
+ return tokens
1918
+
1919
+
1920
+ def _mentions_any(text: str, terms: list[str]) -> bool:
1921
+ lower = text.lower()
1922
+ return any(term.lower() in lower for term in terms if term)
1923
+
1924
+
1925
+ def _target_relevance_findings(
1926
+ *,
1927
+ markdown: str,
1928
+ ledger: ClaimLedger,
1929
+ config: dict[str, Any],
1930
+ user_text: str,
1931
+ reader_facing_mode: bool,
1932
+ strict: bool,
1933
+ stages: list[dict[str, Any]],
1934
+ artifacts: list[dict[str, Any]],
1935
+ ) -> list[dict[str, Any]]:
1936
+ stage_id = _stage_or_none(stages, "editor")
1937
+ artifact_id = _artifact_or_none(artifacts, "audited_brief")
1938
+ terms = _target_terms(config, user_text=user_text)
1939
+ if not terms:
1940
+ blocking_level = "blocking" if strict else "warning"
1941
+ return [
1942
+ _finding(
1943
+ finding_id="QG_TARGET_RELEVANCE_001",
1944
+ gate_id="target_relevance",
1945
+ finding_type="target_mapping_ambiguous",
1946
+ severity="high" if strict else "medium",
1947
+ blocking_level=blocking_level,
1948
+ repair_owner="human",
1949
+ stage_id=stage_id,
1950
+ artifact_id=artifact_id,
1951
+ description="Target entity or topic could not be derived from workspace config or user context.",
1952
+ recommendation="Ask the Orchestrator or human reviewer to clarify the target before enforcing relevance.",
1953
+ category="audience_mismatch",
1954
+ metadata={"strict": strict},
1955
+ )
1956
+ ]
1957
+
1958
+ summary = _section_between(markdown, ("executive summary", "摘要", "summary"))
1959
+ findings: list[dict[str, Any]] = []
1960
+ if strict and not summary:
1961
+ findings.append(
1962
+ _finding(
1963
+ finding_id="QG_TARGET_RELEVANCE_001",
1964
+ gate_id="target_relevance",
1965
+ finding_type="target_relevance_gap",
1966
+ severity="high",
1967
+ blocking_level="blocking",
1968
+ repair_owner="editor",
1969
+ stage_id=stage_id,
1970
+ artifact_id=artifact_id,
1971
+ description="Executive summary section is missing, so configured target visibility cannot be verified.",
1972
+ recommendation="Add an executive summary that makes the configured target visible in reader-facing context.",
1973
+ category="audience_mismatch",
1974
+ metadata={"target_terms": terms, "strict": strict},
1975
+ )
1976
+ )
1977
+ if summary and not _mentions_any(summary, terms):
1978
+ findings.append(
1979
+ _finding(
1980
+ finding_id=f"QG_TARGET_RELEVANCE_{len(findings)+1:03d}",
1981
+ gate_id="target_relevance",
1982
+ finding_type="target_relevance_gap",
1983
+ severity="high",
1984
+ blocking_level="blocking",
1985
+ repair_owner="editor",
1986
+ stage_id=stage_id,
1987
+ artifact_id=artifact_id,
1988
+ description="Executive summary does not mention the configured target entity or topic.",
1989
+ recommendation="Revise the summary so the target is visible in the reader-facing decision context.",
1990
+ category="audience_mismatch",
1991
+ metadata={"target_terms": terms, "strict": strict},
1992
+ )
1993
+ )
1994
+
1995
+ target_claims = [
1996
+ claim
1997
+ for claim in ledger
1998
+ if _mentions_any(f"{claim.statement}\n{claim.evidence_text}", terms)
1999
+ and str((claim.metadata or {}).get("importance", "")).lower() in {"high", "critical", "blocking", "direct"}
2000
+ ]
2001
+ if summary and target_claims and not reader_facing_mode:
2002
+ refs = set(SRC_REF_PATTERN.findall(summary))
2003
+ if not any(claim.claim_id in refs for claim in target_claims):
2004
+ findings.append(
2005
+ _finding(
2006
+ finding_id=f"QG_TARGET_RELEVANCE_{len(findings)+1:03d}",
2007
+ gate_id="target_relevance",
2008
+ finding_type="target_priority_claim_missing_from_summary",
2009
+ severity="high",
2010
+ blocking_level="blocking",
2011
+ repair_owner="editor",
2012
+ stage_id=stage_id,
2013
+ artifact_id=artifact_id,
2014
+ claim_id=target_claims[0].claim_id,
2015
+ source_id=target_claims[0].source_id,
2016
+ description="A high-priority target-specific claim is not represented in the executive summary.",
2017
+ recommendation="Include at least one high-priority target-specific claim in the summary or document why it is excluded.",
2018
+ category="coverage_gap",
2019
+ metadata={"target_terms": terms, "target_claim_ids": [claim.claim_id for claim in target_claims]},
2020
+ )
2021
+ )
2022
+ return findings
2023
+
2024
+
2025
+ def _gate_result(gate_id: str, findings: list[dict[str, Any]]) -> dict[str, Any]:
2026
+ rule = _gate_rule(gate_id)
2027
+ return {
2028
+ "gate_id": gate_id,
2029
+ "status": _gate_status(findings),
2030
+ "blocking": any(finding.get("blocking_level") == "blocking" for finding in findings),
2031
+ "finding_ids": [str(finding.get("finding_id")) for finding in findings],
2032
+ "rule_summary": rule["rule_summary"],
2033
+ "docs_anchor": rule["docs_anchor"],
2034
+ }
2035
+
2036
+
2037
+ def _reader_facing_mode(workspace: Path, brief_path: Path) -> bool:
2038
+ rel_path = _workspace_relative(workspace, brief_path)
2039
+ if rel_path == "output/brief.md":
2040
+ return True
2041
+ return rel_path.startswith("output/delivery/") and rel_path.endswith(".md")
2042
+
2043
+
2044
+ def evaluate_quality_gate_findings(
2045
+ *,
2046
+ markdown: str,
2047
+ ledger: ClaimLedger,
2048
+ config: dict[str, Any],
2049
+ user_text: str,
2050
+ analyst_markdown: str | None,
2051
+ report_date: str,
2052
+ max_source_age_days: int | None,
2053
+ strict: bool,
2054
+ reader_facing_mode: bool,
2055
+ stages: list[dict[str, Any]],
2056
+ artifacts: list[dict[str, Any]],
2057
+ policy_gate_adapter: dict[str, Any] | None = None,
2058
+ coverage_omission_projection: dict[str, Any] | None = None,
2059
+ parallel: bool = False,
2060
+ ) -> dict[str, list[dict[str, Any]]]:
2061
+ """Evaluate deterministic quality gates from preloaded inputs without writes.
2062
+
2063
+ The returned mapping is intentionally keyed by gate ID so callers can choose
2064
+ their own deterministic aggregation policy. Report writing, event emission,
2065
+ and legacy projection updates remain owned by ``check_quality_gates``.
2066
+ """
2067
+
2068
+ gate_findings: dict[str, list[dict[str, Any]]] = {gate_id: [] for gate_id in sorted(GATE_IDS)}
2069
+ gate_tasks: dict[str, Callable[[], list[dict[str, Any]]]] = {}
2070
+ material_fact_strict = policy_gate_is_strict(policy_gate_adapter, "material_fact", cli_strict=strict)
2071
+ freshness_strict = policy_gate_is_strict(policy_gate_adapter, "freshness", cli_strict=strict)
2072
+ target_relevance_strict = policy_gate_is_strict(policy_gate_adapter, "target_relevance", cli_strict=strict)
2073
+ coverage_omission_strict = policy_gate_is_strict(policy_gate_adapter, "coverage_omission", cli_strict=strict)
2074
+ coverage_projection = coverage_omission_projection or _coverage_omission_projection(
2075
+ workspace=None,
2076
+ markdown=markdown,
2077
+ ledger=ledger,
2078
+ reader_facing_mode=reader_facing_mode,
2079
+ )
2080
+ gate_tasks["coverage_omission"] = lambda: _coverage_omission_findings(
2081
+ projection=coverage_projection,
2082
+ strict=coverage_omission_strict,
2083
+ stages=stages,
2084
+ artifacts=artifacts,
2085
+ reader_facing_mode=reader_facing_mode,
2086
+ )
2087
+ gate_tasks["final_abstract_quality"] = lambda: _final_abstract_quality_findings(
2088
+ markdown=markdown,
2089
+ config=config,
2090
+ reader_facing_mode=reader_facing_mode,
2091
+ stages=stages,
2092
+ artifacts=artifacts,
2093
+ )
2094
+ if not reader_facing_mode:
2095
+ gate_tasks["material_fact"] = lambda: _material_findings(
2096
+ markdown=markdown,
2097
+ ledger=ledger,
2098
+ strict=material_fact_strict,
2099
+ stages=stages,
2100
+ artifacts=artifacts,
2101
+ )
2102
+ gate_tasks["freshness"] = lambda: _freshness_findings(
2103
+ markdown=markdown,
2104
+ ledger=ledger,
2105
+ report_date=report_date,
2106
+ max_source_age_days=max_source_age_days,
2107
+ strict=freshness_strict,
2108
+ stages=stages,
2109
+ artifacts=artifacts,
2110
+ )
2111
+ gate_tasks["editor_new_fact"] = lambda: _editor_introduced_new_fact_findings(
2112
+ markdown=markdown,
2113
+ analyst_markdown=analyst_markdown,
2114
+ config=config,
2115
+ user_text=user_text,
2116
+ strict=strict,
2117
+ stages=stages,
2118
+ artifacts=artifacts,
2119
+ )
2120
+ gate_tasks["target_relevance"] = lambda: _target_relevance_findings(
2121
+ markdown=markdown,
2122
+ ledger=ledger,
2123
+ config=config,
2124
+ user_text=user_text,
2125
+ reader_facing_mode=reader_facing_mode,
2126
+ strict=target_relevance_strict,
2127
+ stages=stages,
2128
+ artifacts=artifacts,
2129
+ )
2130
+
2131
+ if not parallel or len(gate_tasks) <= 1:
2132
+ for gate_id in sorted(gate_tasks):
2133
+ gate_findings[gate_id] = gate_tasks[gate_id]()
2134
+ return gate_findings
2135
+
2136
+ gate_errors: dict[str, str] = {}
2137
+ max_workers = min(len(gate_tasks), 4)
2138
+ with ThreadPoolExecutor(max_workers=max_workers, thread_name_prefix="mabw-quality-gate") as executor:
2139
+ futures = {executor.submit(gate_tasks[gate_id]): gate_id for gate_id in sorted(gate_tasks)}
2140
+ for future in as_completed(futures):
2141
+ gate_id = futures[future]
2142
+ try:
2143
+ gate_findings[gate_id] = future.result()
2144
+ except Exception as exc: # pragma: no cover - exercised through monkeypatch tests.
2145
+ gate_errors[gate_id] = str(exc)
2146
+ if gate_errors:
2147
+ raise RuntimeStateError(
2148
+ "Quality gate evaluation failed.",
2149
+ details={"gate_errors": {gate_id: gate_errors[gate_id] for gate_id in sorted(gate_errors)}},
2150
+ )
2151
+ return gate_findings
2152
+
2153
+
2154
+ def check_quality_gates(
2155
+ *,
2156
+ workspace: str | Path,
2157
+ brief: str | Path | None = None,
2158
+ ledger: str | Path | None = None,
2159
+ report_date: str = "",
2160
+ max_source_age_days: int | None = None,
2161
+ stage_id: str | None = None,
2162
+ strict: bool = False,
2163
+ repo_workdir: str | Path | None = None,
2164
+ actor: str = GATE_EVENT_ACTOR,
2165
+ ) -> dict[str, Any]:
2166
+ ws = _require_workspace(workspace)
2167
+ _raise_if_active_repair_open_for_gate_check(ws)
2168
+ _repo, stages, artifacts = _contracts(workspace=ws, repo_workdir=repo_workdir)
2169
+
2170
+ requested_stage_id = stage_id or "auditor"
2171
+ default_brief = "output/brief.md" if requested_stage_id == "finalize" else "output/intermediate/audited_brief.md"
2172
+ brief_path = _resolve_path(ws, brief, default_brief)
2173
+ reader_mode = _reader_facing_mode(ws, brief_path)
2174
+ gate_stage_id = stage_id or ("finalize" if reader_mode else "auditor")
2175
+ gate_artifact_id = quality_gate_report_key_for_stage(gate_stage_id)
2176
+ if not _stage_exists(stages, gate_stage_id):
2177
+ raise RuntimeStateError(
2178
+ f"Unknown gate stage: {gate_stage_id}",
2179
+ details={"stage_id": gate_stage_id},
2180
+ )
2181
+ if not _artifact_exists(artifacts, gate_artifact_id):
2182
+ raise RuntimeStateError(
2183
+ f"Unknown gate artifact: {gate_artifact_id}",
2184
+ details={"artifact_id": gate_artifact_id},
2185
+ )
2186
+ ledger_path = _resolve_path(ws, ledger, "output/intermediate/claim_ledger.json")
2187
+ markdown = _read_text(brief_path, label="Brief")
2188
+ claim_ledger = _load_ledger(ledger_path, required=not reader_mode)
2189
+ config = _load_config(ws)
2190
+ user_text = _read_optional_text(ws / "user.md")
2191
+ analyst_markdown = None if reader_mode else _read_analyst_draft_snapshot(ws)
2192
+ report_date, max_source_age_days = _config_report_defaults(
2193
+ config,
2194
+ report_date=report_date,
2195
+ max_source_age_days=max_source_age_days,
2196
+ )
2197
+ policy_gate_adapter = resolve_workspace_policy_gate_adapter(ws)
2198
+ gate_strictness = {
2199
+ "coverage_omission": policy_gate_is_strict(policy_gate_adapter, "coverage_omission", cli_strict=strict),
2200
+ "final_abstract_quality": False,
2201
+ "material_fact": policy_gate_is_strict(policy_gate_adapter, "material_fact", cli_strict=strict),
2202
+ "freshness": policy_gate_is_strict(policy_gate_adapter, "freshness", cli_strict=strict),
2203
+ "target_relevance": policy_gate_is_strict(policy_gate_adapter, "target_relevance", cli_strict=strict),
2204
+ "editor_new_fact": strict,
2205
+ }
2206
+ coverage_omission_projection = _coverage_omission_projection(
2207
+ workspace=ws,
2208
+ markdown=markdown,
2209
+ ledger=claim_ledger,
2210
+ reader_facing_mode=reader_mode,
2211
+ )
2212
+
2213
+ gate_findings = evaluate_quality_gate_findings(
2214
+ markdown=markdown,
2215
+ ledger=claim_ledger,
2216
+ config=config,
2217
+ user_text=user_text,
2218
+ analyst_markdown=analyst_markdown,
2219
+ report_date=report_date,
2220
+ max_source_age_days=max_source_age_days,
2221
+ stages=stages,
2222
+ artifacts=artifacts,
2223
+ policy_gate_adapter=policy_gate_adapter,
2224
+ coverage_omission_projection=coverage_omission_projection,
2225
+ strict=strict,
2226
+ reader_facing_mode=reader_mode,
2227
+ )
2228
+ atomic_projection = project_atomic_reader_text_from_workspace(
2229
+ workspace=ws,
2230
+ target_text=markdown,
2231
+ target_artifact=_workspace_relative(ws, brief_path),
2232
+ ledger_claims=claim_ledger.to_list(),
2233
+ )
2234
+ gate_findings["material_fact"].extend(
2235
+ _atomic_reader_projection_findings(
2236
+ projection=atomic_projection,
2237
+ start_idx=len(gate_findings["material_fact"]) + 1,
2238
+ stages=stages,
2239
+ artifacts=artifacts,
2240
+ reader_facing_mode=reader_mode,
2241
+ )
2242
+ )
2243
+ claim_support_projection = project_claim_support_matrix_from_workspace(ws)
2244
+ gate_findings["material_fact"].extend(
2245
+ _claim_support_matrix_findings(
2246
+ projection=claim_support_projection,
2247
+ start_idx=len(gate_findings["material_fact"]) + 1,
2248
+ stages=stages,
2249
+ artifacts=artifacts,
2250
+ reader_facing_mode=reader_mode,
2251
+ )
2252
+ )
2253
+ for gate_id in sorted(GATE_IDS):
2254
+ gate_findings[gate_id] = _apply_gate_context(
2255
+ gate_findings[gate_id],
2256
+ gate_stage_id=gate_stage_id,
2257
+ gate_artifact_id=gate_artifact_id,
2258
+ )
2259
+
2260
+ gate_results = [_gate_result(gate_id, gate_findings[gate_id]) for gate_id in sorted(GATE_IDS)]
2261
+ findings = [finding for gate_id in sorted(GATE_IDS) for finding in gate_findings[gate_id]]
2262
+ now = utc_now()
2263
+ payload = {
2264
+ "schema_version": QUALITY_GATE_SCHEMA,
2265
+ "created_at": now,
2266
+ "updated_at": now,
2267
+ "workspace": ".",
2268
+ "report_date": report_date,
2269
+ "policy_pack": "default",
2270
+ "status": _report_status(gate_results),
2271
+ "gate_results": gate_results,
2272
+ "findings": findings,
2273
+ "metadata": {
2274
+ "brief": _workspace_relative(ws, brief_path),
2275
+ "ledger": _workspace_relative(ws, ledger_path),
2276
+ "reader_facing_mode": reader_mode,
2277
+ "strict": strict,
2278
+ "gate_strictness": gate_strictness,
2279
+ "max_source_age_days": max_source_age_days,
2280
+ "stage_id": gate_stage_id,
2281
+ "gate_stage_id": gate_stage_id,
2282
+ "gate_artifact_id": gate_artifact_id,
2283
+ "policy_gate_adapter": policy_gate_adapter,
2284
+ "atomic_reader_projection": atomic_projection,
2285
+ "claim_support_matrix_projection": claim_support_projection,
2286
+ "coverage_omission_projection": coverage_omission_projection,
2287
+ },
2288
+ }
2289
+
2290
+ errors = validate_quality_gate_report_payload(payload, stages=stages, artifacts=artifacts)
2291
+ if errors:
2292
+ raise RuntimeStateError(
2293
+ "Generated quality gate report failed contract validation.",
2294
+ details={"errors": errors},
2295
+ )
2296
+
2297
+ report_path = quality_gate_report_path_for_stage(ws, gate_stage_id)
2298
+ legacy_report_path = quality_gate_paths(ws)["quality_gate_report"]
2299
+ frozen_record = _ensure_frozen_report_is_unchanged(
2300
+ workspace=ws,
2301
+ report_path=report_path,
2302
+ artifact_id=gate_artifact_id,
2303
+ )
2304
+ if frozen_record is not None:
2305
+ raise RuntimeStateError(
2306
+ "Stage-scoped gate report is already frozen. Read the existing report, or use repair/new run if the report must change.",
2307
+ details={
2308
+ "artifact_id": gate_artifact_id,
2309
+ "path": _workspace_relative(ws, report_path),
2310
+ "producer_stage": gate_stage_id,
2311
+ "required_action": "read_existing_report_or_repair_or_new_run",
2312
+ },
2313
+ error_code=E_FROZEN_GATE_REPORT_ALREADY_EXISTS,
2314
+ )
2315
+ existing_report = _read_json_object(report_path)
2316
+ if existing_report is not None and _quality_gate_reports_equivalent(existing_report, payload):
2317
+ legacy_report = _read_json_object(legacy_report_path)
2318
+ if legacy_report is None or not _quality_gate_reports_equivalent(legacy_report, existing_report):
2319
+ _write_json_atomic(legacy_report_path, existing_report)
2320
+ return show_quality_gates(workspace=ws, repo_workdir=repo_workdir)
2321
+ old_report = report_path.read_bytes() if report_path.exists() else None
2322
+ old_legacy_report = legacy_report_path.read_bytes() if legacy_report_path.exists() else None
2323
+ wrote_report = False
2324
+ wrote_legacy_report = False
2325
+ try:
2326
+ _write_json_atomic(report_path, payload)
2327
+ wrote_report = True
2328
+ _write_json_atomic(legacy_report_path, payload)
2329
+ wrote_legacy_report = True
2330
+ run_id = _runtime_run_id(workspace=ws, repo_workdir=repo_workdir)
2331
+ append_event(
2332
+ workspace=ws,
2333
+ run_id=run_id,
2334
+ event_type="quality_gate_checked",
2335
+ actor=actor,
2336
+ stage_id=gate_stage_id,
2337
+ artifact_id=gate_artifact_id,
2338
+ reason=f"Quality gates checked with status {payload['status']}.",
2339
+ metadata={
2340
+ "status": payload["status"],
2341
+ "report_path": _workspace_relative(ws, report_path),
2342
+ "legacy_projection_path": _workspace_relative(ws, legacy_report_path),
2343
+ "finding_count": len(findings),
2344
+ "blocking_count": sum(1 for finding in findings if finding.get("blocking_level") == "blocking"),
2345
+ },
2346
+ )
2347
+ if any(finding.get("blocking_level") == "blocking" for finding in findings):
2348
+ append_event(
2349
+ workspace=ws,
2350
+ run_id=run_id,
2351
+ event_type="quality_gate_blocked",
2352
+ actor=actor,
2353
+ stage_id=gate_stage_id,
2354
+ artifact_id=gate_artifact_id,
2355
+ reason="Quality gates produced blocking findings.",
2356
+ metadata={"finding_ids": [finding.get("finding_id") for finding in findings if finding.get("blocking_level") == "blocking"]},
2357
+ )
2358
+ else:
2359
+ append_event(
2360
+ workspace=ws,
2361
+ run_id=run_id,
2362
+ event_type="quality_gate_passed",
2363
+ actor=actor,
2364
+ stage_id=gate_stage_id,
2365
+ artifact_id=gate_artifact_id,
2366
+ reason="Quality gates produced no blocking findings.",
2367
+ metadata={},
2368
+ )
2369
+ except Exception:
2370
+ if wrote_legacy_report:
2371
+ if old_legacy_report is None:
2372
+ legacy_report_path.unlink(missing_ok=True)
2373
+ else:
2374
+ legacy_report_path.write_bytes(old_legacy_report)
2375
+ if wrote_report:
2376
+ if old_report is None:
2377
+ report_path.unlink(missing_ok=True)
2378
+ else:
2379
+ report_path.write_bytes(old_report)
2380
+ raise
2381
+
2382
+ return show_quality_gates(workspace=ws, repo_workdir=repo_workdir)
2383
+
2384
+
2385
+ def _raise_if_active_repair_open_for_gate_check(workspace: Path) -> None:
2386
+ workflow_path = runtime_state_paths(workspace)["workflow_state"]
2387
+ if not workflow_path.exists():
2388
+ return
2389
+ try:
2390
+ workflow = json.loads(workflow_path.read_text(encoding="utf-8"))
2391
+ except (OSError, json.JSONDecodeError) as exc:
2392
+ raise RuntimeStateError(
2393
+ f"workflow_state.json is unreadable before quality gate check: {exc}",
2394
+ error_code=E_TRANSACTION_INTEGRITY,
2395
+ ) from exc
2396
+ if not isinstance(workflow, dict):
2397
+ raise RuntimeStateError(
2398
+ "workflow_state.json must contain an object before quality gate check.",
2399
+ error_code=E_TRANSACTION_INTEGRITY,
2400
+ )
2401
+ raise_if_active_repair_open(workspace=workspace, workflow=workflow)
2402
+
2403
+
2404
+ def show_quality_gates(
2405
+ *,
2406
+ workspace: str | Path,
2407
+ repo_workdir: str | Path | None = None,
2408
+ ) -> dict[str, Any]:
2409
+ ws = _require_workspace(workspace)
2410
+ _repo, stages, artifacts = _contracts(workspace=ws, repo_workdir=repo_workdir)
2411
+ try:
2412
+ report = load_quality_gate_report(ws)
2413
+ except Exception:
2414
+ report = None
2415
+ stage_reports: dict[str, Any] = {}
2416
+ for stage in ("auditor", "finalize"):
2417
+ try:
2418
+ stage_report = load_quality_gate_report_for_stage(ws, stage, allow_legacy=False)
2419
+ except Exception:
2420
+ stage_report = None
2421
+ if stage_report is not None:
2422
+ stage_reports[quality_gate_report_key_for_stage(stage)] = stage_report
2423
+ validation = validate_quality_gates_workspace(
2424
+ workspace=ws,
2425
+ repo_workdir=repo_workdir,
2426
+ )
2427
+ state = {
2428
+ "ok": bool(validation.get("ok")),
2429
+ "workspace": str(ws),
2430
+ "quality_gate_state_files": QUALITY_GATE_STATE_FILES,
2431
+ "quality_gate_report": report or empty_quality_gate_report(),
2432
+ "stage_quality_gate_reports": stage_reports,
2433
+ "validation": validation,
2434
+ }
2435
+ state.update(_blocking_repair_guidance(workspace=ws, validation=validation))
2436
+ return state
2437
+
2438
+
2439
+ def validate_quality_gates_workspace(
2440
+ *,
2441
+ workspace: str | Path,
2442
+ repo_workdir: str | Path | None = None,
2443
+ ) -> dict[str, Any]:
2444
+ ws = _require_workspace(workspace)
2445
+ _repo, stages, artifacts = _contracts(workspace=ws, repo_workdir=repo_workdir)
2446
+ return validate_quality_gate_workspace(workspace=ws, stages=stages, artifacts=artifacts)
2447
+
2448
+
2449
+ def _blocking_repair_guidance(*, workspace: Path, validation: dict[str, Any]) -> dict[str, Any]:
2450
+ if int(validation.get("blocking_count") or 0) <= 0:
2451
+ return {}
2452
+
2453
+ route_command = f"multi-agent-brief repair route --workspace {workspace} --json"
2454
+ required_commands = [route_command]
2455
+ try:
2456
+ from multi_agent_brief.repair.router import route_repair
2457
+
2458
+ repair_route = route_repair(workspace=workspace)
2459
+ except Exception as exc: # pragma: no cover - defensive CLI guidance path.
2460
+ repair_route = {
2461
+ "ok": False,
2462
+ "error_code": "E_REPAIR_ROUTE_UNAVAILABLE",
2463
+ "message": str(exc),
2464
+ "workspace": str(workspace),
2465
+ }
2466
+
2467
+ if repair_route.get("ok") and repair_route.get("repair_owner") != "none":
2468
+ required_commands.extend([
2469
+ f"multi-agent-brief repair start --workspace {workspace} --json",
2470
+ f"multi-agent-brief repair complete --workspace {workspace} --reason \"<reason>\" --json",
2471
+ ])
2472
+ repair_steps = [
2473
+ "Run repair start to open an owner-stage repair transaction.",
2474
+ "Delegate only the reported repair_owner role.",
2475
+ "Allow edits only to repair_route.allowed_artifacts.",
2476
+ "Run repair complete after the owner edits.",
2477
+ "Rerun downstream stages from repair_route.must_rerun_from.",
2478
+ ]
2479
+ else:
2480
+ required_commands.extend([
2481
+ f"multi-agent-brief state decide --workspace {workspace} --stage <stage> --decision request_human_review --reason \"<reason>\" --json",
2482
+ f"multi-agent-brief state decide --workspace {workspace} --stage <stage> --decision block_run --reason \"<reason>\" --json",
2483
+ ])
2484
+ repair_steps = [
2485
+ "No deterministic owner-stage repair route is available.",
2486
+ "Use request_human_review or block_run instead of editing artifacts directly.",
2487
+ ]
2488
+
2489
+ return {
2490
+ "required_commands": required_commands,
2491
+ "repair_steps": repair_steps,
2492
+ "repair_route": repair_route,
2493
+ "repair_warnings": [
2494
+ "Do not edit frozen artifacts directly.",
2495
+ "Direct edits will mark the run contaminated and non-reference-eligible.",
2496
+ "Never manually update artifact_registry.json, runtime_manifest.json, workflow_state.json, event_log.jsonl, or SHA fields.",
2497
+ ],
2498
+ }