agentic-project-kit 1.0.1__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 (310) hide show
  1. agentic_project_kit/__init__.py +1 -0
  2. agentic_project_kit/absolute_path_portability_audit.py +241 -0
  3. agentic_project_kit/access_level_policy.py +14 -0
  4. agentic_project_kit/access_levels.py +22 -0
  5. agentic_project_kit/action_registry.py +195 -0
  6. agentic_project_kit/action_specs.py +286 -0
  7. agentic_project_kit/agent_command_runner.py +516 -0
  8. agentic_project_kit/audit_test_matrix.py +36 -0
  9. agentic_project_kit/audit_test_matrix_cli.py +43 -0
  10. agentic_project_kit/chat_bootloader.py +257 -0
  11. agentic_project_kit/chat_entrypoint_contract.py +297 -0
  12. agentic_project_kit/checks.py +511 -0
  13. agentic_project_kit/ci_readiness.py +211 -0
  14. agentic_project_kit/cli.py +147 -0
  15. agentic_project_kit/cli_commands/__init__.py +1 -0
  16. agentic_project_kit/cli_commands/absolute_path_audit.py +25 -0
  17. agentic_project_kit/cli_commands/actions.py +21 -0
  18. agentic_project_kit/cli_commands/artifact_gc.py +240 -0
  19. agentic_project_kit/cli_commands/boot.py +55 -0
  20. agentic_project_kit/cli_commands/chat.py +34 -0
  21. agentic_project_kit/cli_commands/checks.py +305 -0
  22. agentic_project_kit/cli_commands/cockpit.py +103 -0
  23. agentic_project_kit/cli_commands/command_taxonomy.py +25 -0
  24. agentic_project_kit/cli_commands/commands.py +129 -0
  25. agentic_project_kit/cli_commands/dev.py +23 -0
  26. agentic_project_kit/cli_commands/direction.py +92 -0
  27. agentic_project_kit/cli_commands/doc_currency_audit.py +25 -0
  28. agentic_project_kit/cli_commands/doc_registry.py +126 -0
  29. agentic_project_kit/cli_commands/docs.py +223 -0
  30. agentic_project_kit/cli_commands/dpa.py +1338 -0
  31. agentic_project_kit/cli_commands/evidence.py +251 -0
  32. agentic_project_kit/cli_commands/github.py +34 -0
  33. agentic_project_kit/cli_commands/governance.py +14 -0
  34. agentic_project_kit/cli_commands/gui.py +23 -0
  35. agentic_project_kit/cli_commands/gui_readiness_gate.py +27 -0
  36. agentic_project_kit/cli_commands/handoff.py +183 -0
  37. agentic_project_kit/cli_commands/human_workflows.py +430 -0
  38. agentic_project_kit/cli_commands/init.py +132 -0
  39. agentic_project_kit/cli_commands/instruction.py +75 -0
  40. agentic_project_kit/cli_commands/mutation_lock_audit.py +24 -0
  41. agentic_project_kit/cli_commands/ns_legacy_audit.py +25 -0
  42. agentic_project_kit/cli_commands/pass_already_done.py +66 -0
  43. agentic_project_kit/cli_commands/patch_failure_discipline_audit.py +26 -0
  44. agentic_project_kit/cli_commands/patch_preflight.py +37 -0
  45. agentic_project_kit/cli_commands/path_literal_audit.py +39 -0
  46. agentic_project_kit/cli_commands/patterns.py +40 -0
  47. agentic_project_kit/cli_commands/planning_docs_audit.py +25 -0
  48. agentic_project_kit/cli_commands/pr.py +133 -0
  49. agentic_project_kit/cli_commands/pr_hygiene.py +27 -0
  50. agentic_project_kit/cli_commands/profiles.py +26 -0
  51. agentic_project_kit/cli_commands/program_redundancy_audit.py +25 -0
  52. agentic_project_kit/cli_commands/project_direction.py +25 -0
  53. agentic_project_kit/cli_commands/release.py +392 -0
  54. agentic_project_kit/cli_commands/release_publish_orchestration.py +36 -0
  55. agentic_project_kit/cli_commands/remote_branch_hygiene.py +152 -0
  56. agentic_project_kit/cli_commands/remote_next.py +57 -0
  57. agentic_project_kit/cli_commands/removed_ns_commands.py +65 -0
  58. agentic_project_kit/cli_commands/rule_registry.py +129 -0
  59. agentic_project_kit/cli_commands/rules.py +222 -0
  60. agentic_project_kit/cli_commands/scaffold.py +46 -0
  61. agentic_project_kit/cli_commands/slice.py +21 -0
  62. agentic_project_kit/cli_commands/standard_gates_audit_suite.py +27 -0
  63. agentic_project_kit/cli_commands/state.py +51 -0
  64. agentic_project_kit/cli_commands/status_current_state_audit.py +30 -0
  65. agentic_project_kit/cli_commands/todo.py +53 -0
  66. agentic_project_kit/cli_commands/transfer.py +19 -0
  67. agentic_project_kit/cli_commands/transfer_context_flow.py +398 -0
  68. agentic_project_kit/cli_commands/transfer_context_helpers.py +398 -0
  69. agentic_project_kit/cli_commands/transfer_diagnostics.py +767 -0
  70. agentic_project_kit/cli_commands/transfer_evidence_flow.py +368 -0
  71. agentic_project_kit/cli_commands/transfer_handoff_flow.py +594 -0
  72. agentic_project_kit/cli_commands/transfer_order_contract.py +74 -0
  73. agentic_project_kit/cli_commands/transfer_post_merge_complete.py +442 -0
  74. agentic_project_kit/cli_commands/transfer_post_merge_settle.py +171 -0
  75. agentic_project_kit/cli_commands/transfer_pr_closeout_complete.py +124 -0
  76. agentic_project_kit/cli_commands/transfer_pr_create_flow.py +743 -0
  77. agentic_project_kit/cli_commands/transfer_pr_merge_flow.py +547 -0
  78. agentic_project_kit/cli_commands/transfer_repo_after_pr.py +160 -0
  79. agentic_project_kit/cli_commands/transfer_repo_pre_pr.py +664 -0
  80. agentic_project_kit/cli_commands/transfer_runner_flow.py +131 -0
  81. agentic_project_kit/cli_commands/transfer_runtime_initial.py +194 -0
  82. agentic_project_kit/cli_commands/transfer_shared.py +274 -0
  83. agentic_project_kit/cli_commands/validation.py +200 -0
  84. agentic_project_kit/cli_commands/version.py +27 -0
  85. agentic_project_kit/cli_commands/work_orders.py +219 -0
  86. agentic_project_kit/cli_commands/workflow.py +471 -0
  87. agentic_project_kit/cli_commands/workflow_guard.py +26 -0
  88. agentic_project_kit/cli_commands/workspace.py +252 -0
  89. agentic_project_kit/cockpit.py +608 -0
  90. agentic_project_kit/cockpit_readiness.py +67 -0
  91. agentic_project_kit/command_authority_audit.py +192 -0
  92. agentic_project_kit/command_inbox_check.py +103 -0
  93. agentic_project_kit/command_manifest.py +591 -0
  94. agentic_project_kit/command_queue_contract.py +161 -0
  95. agentic_project_kit/command_selector.py +245 -0
  96. agentic_project_kit/command_taxonomy.py +264 -0
  97. agentic_project_kit/commit_guard.py +67 -0
  98. agentic_project_kit/communication_artifact_gc.py +495 -0
  99. agentic_project_kit/communication_rule_context.py +437 -0
  100. agentic_project_kit/communication_state.py +115 -0
  101. agentic_project_kit/composed_wrapper_invariants.py +97 -0
  102. agentic_project_kit/composite_short_circuit.py +140 -0
  103. agentic_project_kit/contract.py +251 -0
  104. agentic_project_kit/control_state.py +83 -0
  105. agentic_project_kit/doc_currency_audit.py +536 -0
  106. agentic_project_kit/doc_lifecycle.py +1179 -0
  107. agentic_project_kit/doc_lifecycle_signals.py +446 -0
  108. agentic_project_kit/doc_lifecycle_sweep.py +639 -0
  109. agentic_project_kit/doc_mesh.py +491 -0
  110. agentic_project_kit/doctor.py +379 -0
  111. agentic_project_kit/documentation_registry.py +1122 -0
  112. agentic_project_kit/documentation_system_audit.py +310 -0
  113. agentic_project_kit/dpa_current_handoff_lifecycle.py +549 -0
  114. agentic_project_kit/dpa_dp2_decision_readiness.py +362 -0
  115. agentic_project_kit/dpa_dp3_dp4_adjudication.py +604 -0
  116. agentic_project_kit/dpa_dp5_block_new_gate.py +294 -0
  117. agentic_project_kit/dpa_dp5_stage_adoption.py +615 -0
  118. agentic_project_kit/dpa_dp5_strict_gate.py +187 -0
  119. agentic_project_kit/dpa_final_closeout.py +627 -0
  120. agentic_project_kit/dpa_fixture_evidence.py +680 -0
  121. agentic_project_kit/dpa_maintainer_record_check.py +711 -0
  122. agentic_project_kit/dpa_post_dp2_scope_assessment.py +734 -0
  123. agentic_project_kit/dpa_probe_002_readiness.py +509 -0
  124. agentic_project_kit/dpa_probe_003_readiness.py +417 -0
  125. agentic_project_kit/dpa_probe_004_readiness.py +437 -0
  126. agentic_project_kit/dpa_readiness.py +505 -0
  127. agentic_project_kit/dpa_readonly_probe_execution.py +500 -0
  128. agentic_project_kit/dpa_registry_contracts.py +312 -0
  129. agentic_project_kit/dpa_renderer_readiness.py +407 -0
  130. agentic_project_kit/dpa_repo_adoption_assessment.py +574 -0
  131. agentic_project_kit/dpa_stable_readiness.py +743 -0
  132. agentic_project_kit/dpa_successor_projection.py +168 -0
  133. agentic_project_kit/dpa_workspace_init_projection.py +93 -0
  134. agentic_project_kit/dpa_wrt_ch001_evidence.py +327 -0
  135. agentic_project_kit/entrypoint_slice_runner.py +153 -0
  136. agentic_project_kit/evidence_clean.py +152 -0
  137. agentic_project_kit/evidence_commit_paths.py +214 -0
  138. agentic_project_kit/evidence_finalize_log.py +204 -0
  139. agentic_project_kit/evidence_guard.py +114 -0
  140. agentic_project_kit/evidence_inspector.py +507 -0
  141. agentic_project_kit/evidence_state_contract.py +99 -0
  142. agentic_project_kit/execution_mode_state.py +148 -0
  143. agentic_project_kit/final_summary_contract.py +85 -0
  144. agentic_project_kit/finalize_guard.py +139 -0
  145. agentic_project_kit/gatekeeper_core.py +232 -0
  146. agentic_project_kit/github.py +25 -0
  147. agentic_project_kit/governance.py +59 -0
  148. agentic_project_kit/gui_action_execution.py +105 -0
  149. agentic_project_kit/gui_action_renderer.py +81 -0
  150. agentic_project_kit/gui_action_run_intent.py +98 -0
  151. agentic_project_kit/gui_action_views.py +195 -0
  152. agentic_project_kit/gui_activity_log.py +76 -0
  153. agentic_project_kit/gui_button_catalog.py +605 -0
  154. agentic_project_kit/gui_cockpit.py +365 -0
  155. agentic_project_kit/gui_cockpit_actions.py +695 -0
  156. agentic_project_kit/gui_cockpit_common.py +172 -0
  157. agentic_project_kit/gui_cockpit_header.py +501 -0
  158. agentic_project_kit/gui_cockpit_sidebar.py +387 -0
  159. agentic_project_kit/gui_cockpit_task.py +748 -0
  160. agentic_project_kit/gui_command_projection.py +355 -0
  161. agentic_project_kit/gui_communication_modes.py +130 -0
  162. agentic_project_kit/gui_dry_run.py +219 -0
  163. agentic_project_kit/gui_gatekeeper_status.py +259 -0
  164. agentic_project_kit/gui_layout_plan.py +148 -0
  165. agentic_project_kit/gui_open_folder.py +18 -0
  166. agentic_project_kit/gui_output_status_panel.py +61 -0
  167. agentic_project_kit/gui_panel_state.py +47 -0
  168. agentic_project_kit/gui_presenter.py +62 -0
  169. agentic_project_kit/gui_readiness_gate.py +206 -0
  170. agentic_project_kit/gui_release_flow.py +59 -0
  171. agentic_project_kit/gui_task_editor.py +1077 -0
  172. agentic_project_kit/gui_tk_widgets.py +177 -0
  173. agentic_project_kit/gui_tkinter_renderer.py +87 -0
  174. agentic_project_kit/gui_tkinter_shell.py +1176 -0
  175. agentic_project_kit/gui_transfer_contract.py +28 -0
  176. agentic_project_kit/gui_viewmodel.py +698 -0
  177. agentic_project_kit/gui_window_guard.py +46 -0
  178. agentic_project_kit/handoff_freshness.py +390 -0
  179. agentic_project_kit/handoff_prompt.py +180 -0
  180. agentic_project_kit/handoff_state.py +254 -0
  181. agentic_project_kit/instruction_lint.py +455 -0
  182. agentic_project_kit/llm_context_carriers.py +66 -0
  183. agentic_project_kit/llm_execution_context.py +285 -0
  184. agentic_project_kit/local_command_stack.py +133 -0
  185. agentic_project_kit/local_feature_gate.py +82 -0
  186. agentic_project_kit/local_garbage_collector.py +269 -0
  187. agentic_project_kit/models.py +18 -0
  188. agentic_project_kit/mutation_lock_audit.py +421 -0
  189. agentic_project_kit/next_turn_evidence.py +253 -0
  190. agentic_project_kit/next_turn_merge_if_green.py +459 -0
  191. agentic_project_kit/next_turn_pr_status.py +255 -0
  192. agentic_project_kit/next_turn_result.py +183 -0
  193. agentic_project_kit/next_turn_runner.py +159 -0
  194. agentic_project_kit/next_turn_slot.py +107 -0
  195. agentic_project_kit/next_turn_status.py +274 -0
  196. agentic_project_kit/ns_legacy_reference_audit.py +258 -0
  197. agentic_project_kit/ns_slice_runner.py +16 -0
  198. agentic_project_kit/operational_handoff_projection.py +124 -0
  199. agentic_project_kit/output_contract.py +80 -0
  200. agentic_project_kit/output_repair.py +61 -0
  201. agentic_project_kit/pass_already_done.py +216 -0
  202. agentic_project_kit/patch_artifact_preflight.py +147 -0
  203. agentic_project_kit/patch_cycle_workflow.py +440 -0
  204. agentic_project_kit/patch_failure_discipline_audit.py +223 -0
  205. agentic_project_kit/patch_preflight.py +215 -0
  206. agentic_project_kit/path_literal_audit.py +612 -0
  207. agentic_project_kit/patterns.py +99 -0
  208. agentic_project_kit/planning_docs_consolidation_audit.py +313 -0
  209. agentic_project_kit/portability_shell_gate.py +40 -0
  210. agentic_project_kit/post_merge_handoff_refresh.py +56 -0
  211. agentic_project_kit/post_release.py +252 -0
  212. agentic_project_kit/post_release_closeout.py +616 -0
  213. agentic_project_kit/pr_cleanup.py +172 -0
  214. agentic_project_kit/pr_closeout.py +50 -0
  215. agentic_project_kit/pr_closeout_complete.py +344 -0
  216. agentic_project_kit/pr_create_or_skip.py +71 -0
  217. agentic_project_kit/pr_hygiene.py +210 -0
  218. agentic_project_kit/program_redundancy_audit.py +251 -0
  219. agentic_project_kit/project_direction.py +840 -0
  220. agentic_project_kit/protected_change_planner.py +194 -0
  221. agentic_project_kit/release.py +401 -0
  222. agentic_project_kit/release_doi_safety.py +24 -0
  223. agentic_project_kit/release_gate_core.py +174 -0
  224. agentic_project_kit/release_metadata_authority_gate.py +328 -0
  225. agentic_project_kit/release_metadata_prep.py +43 -0
  226. agentic_project_kit/release_notes.py +823 -0
  227. agentic_project_kit/release_prep_core.py +204 -0
  228. agentic_project_kit/release_prepare.py +369 -0
  229. agentic_project_kit/release_process_guardrails.py +247 -0
  230. agentic_project_kit/release_publish_core.py +114 -0
  231. agentic_project_kit/release_publish_orchestration.py +469 -0
  232. agentic_project_kit/release_state.py +552 -0
  233. agentic_project_kit/release_verify_core.py +175 -0
  234. agentic_project_kit/remote_branch_hygiene.py +223 -0
  235. agentic_project_kit/remote_next.py +89 -0
  236. agentic_project_kit/remote_next_closeout.py +101 -0
  237. agentic_project_kit/remote_next_order_contract.py +391 -0
  238. agentic_project_kit/removed_ns_commands.py +458 -0
  239. agentic_project_kit/removed_source_audit.py +225 -0
  240. agentic_project_kit/rendering.py +13 -0
  241. agentic_project_kit/repair_report.py +79 -0
  242. agentic_project_kit/repo_identity.py +59 -0
  243. agentic_project_kit/result_report_classifier.py +57 -0
  244. agentic_project_kit/rule_ack.py +105 -0
  245. agentic_project_kit/rule_preservation.py +58 -0
  246. agentic_project_kit/rule_refresh.py +174 -0
  247. agentic_project_kit/rule_registry_registration.py +322 -0
  248. agentic_project_kit/rule_registry_report.py +206 -0
  249. agentic_project_kit/rule_registry_validator.py +704 -0
  250. agentic_project_kit/rule_snapshot.py +98 -0
  251. agentic_project_kit/rule_source_validator.py +133 -0
  252. agentic_project_kit/run_summary.py +68 -0
  253. agentic_project_kit/run_summary_renderer.py +238 -0
  254. agentic_project_kit/runtime_validator.py +68 -0
  255. agentic_project_kit/safe_file_replace.py +35 -0
  256. agentic_project_kit/safe_patch.py +47 -0
  257. agentic_project_kit/safe_push.py +218 -0
  258. agentic_project_kit/safe_remove_diagnostic.py +51 -0
  259. agentic_project_kit/scaffold.py +69 -0
  260. agentic_project_kit/site_claims.py +444 -0
  261. agentic_project_kit/site_generator.py +1140 -0
  262. agentic_project_kit/slice_gate.py +225 -0
  263. agentic_project_kit/slice_runner.py +75 -0
  264. agentic_project_kit/standard_gates_audit_suite.py +167 -0
  265. agentic_project_kit/state_freshness.py +135 -0
  266. agentic_project_kit/status_current_state_audit.py +762 -0
  267. agentic_project_kit/successor_handoff_package.py +1763 -0
  268. agentic_project_kit/templates.py +292 -0
  269. agentic_project_kit/terminal_block_guard.py +166 -0
  270. agentic_project_kit/terminal_logging.py +275 -0
  271. agentic_project_kit/todo.py +97 -0
  272. agentic_project_kit/transfer_closeout.py +136 -0
  273. agentic_project_kit/transfer_continue.py +215 -0
  274. agentic_project_kit/transfer_local_runner.py +101 -0
  275. agentic_project_kit/transfer_operation_monitor.py +236 -0
  276. agentic_project_kit/transfer_post_merge_lifecycle.py +356 -0
  277. agentic_project_kit/transfer_post_merge_settle.py +383 -0
  278. agentic_project_kit/transfer_pr_actions.py +164 -0
  279. agentic_project_kit/transfer_remote_next.py +959 -0
  280. agentic_project_kit/transfer_repo_actions.py +2253 -0
  281. agentic_project_kit/transfer_runner.py +347 -0
  282. agentic_project_kit/transfer_safety_context.py +291 -0
  283. agentic_project_kit/transfer_state.py +483 -0
  284. agentic_project_kit/transfer_uplink.py +471 -0
  285. agentic_project_kit/transfer_workflow_next.py +148 -0
  286. agentic_project_kit/typed_work_order_evidence.py +58 -0
  287. agentic_project_kit/typed_work_order_queue.py +166 -0
  288. agentic_project_kit/typed_work_order_runner.py +168 -0
  289. agentic_project_kit/work_cycle.py +317 -0
  290. agentic_project_kit/work_discard_changes.py +129 -0
  291. agentic_project_kit/work_order_patch.py +199 -0
  292. agentic_project_kit/work_order_runner.py +120 -0
  293. agentic_project_kit/work_order_uploader.py +220 -0
  294. agentic_project_kit/work_order_validator.py +185 -0
  295. agentic_project_kit/work_orders.py +246 -0
  296. agentic_project_kit/workflow_guard.py +262 -0
  297. agentic_project_kit/workflow_summary_runner.py +124 -0
  298. agentic_project_kit/workspace.py +665 -0
  299. agentic_project_kit/workspace_adopt.py +471 -0
  300. agentic_project_kit/workspace_dpa_intake.py +406 -0
  301. agentic_project_kit/workspace_init.py +487 -0
  302. agentic_project_kit/workspace_lock.py +129 -0
  303. agentic_project_kit/workspace_remove.py +381 -0
  304. agentic_project_kit/workspace_upgrade.py +324 -0
  305. agentic_project_kit/wrapper_live_status.py +104 -0
  306. agentic_project_kit-1.0.1.dist-info/METADATA +724 -0
  307. agentic_project_kit-1.0.1.dist-info/RECORD +310 -0
  308. agentic_project_kit-1.0.1.dist-info/WHEEL +4 -0
  309. agentic_project_kit-1.0.1.dist-info/entry_points.txt +3 -0
  310. agentic_project_kit-1.0.1.dist-info/licenses/LICENSE +10 -0
@@ -0,0 +1,459 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import json
5
+ import subprocess
6
+ import time
7
+ from collections.abc import Callable
8
+ from dataclasses import dataclass
9
+ from typing import Any
10
+ from typing import Literal
11
+
12
+ from agentic_project_kit.next_turn_pr_status import (
13
+ PrStatusDecision,
14
+ attach_failed_run_logs,
15
+ classify_pr_status,
16
+ fetch_pr_payload,
17
+ )
18
+
19
+ MergeDecision = Literal["merge", "refuse"]
20
+ MainRunFetcher = Callable[[str, str], dict[str, Any]]
21
+ PrPayloadFetcher = Callable[[str], dict[str, Any]]
22
+ FailedLogFetcher = Callable[[str], tuple[int, str, str]]
23
+ Sleep = Callable[[float], None]
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class PrMergeRefs:
28
+ base_ref_name: str
29
+ base_ref_oid: str
30
+ head_ref_name: str
31
+ head_ref_oid: str
32
+
33
+
34
+ @dataclass(frozen=True)
35
+ class MergeIfGreenResult:
36
+ pr: str
37
+ decision: MergeDecision
38
+ reason: str
39
+ status_decision: PrStatusDecision
40
+ merged: bool
41
+ merge_output: str
42
+ base_ref_name: str = ""
43
+ base_ref_oid: str = ""
44
+ head_ref_name: str = ""
45
+ head_ref_oid: str = ""
46
+ expected_base_branch: str = ""
47
+ expected_head_sha: str = ""
48
+ merge_commit_sha: str = ""
49
+ main_verification_required: bool = False
50
+ main_status_decision: PrStatusDecision | None = None
51
+ main_verification_error: str = ""
52
+
53
+
54
+ def decide_merge(status: PrStatusDecision) -> tuple[MergeDecision, str]:
55
+ if status.state != "OPEN":
56
+ return "refuse", "PR is not open"
57
+ if status.decision != "green":
58
+ return "refuse", f"PR checks are not green: {status.decision}"
59
+ if status.merge_state_status != "CLEAN":
60
+ return "refuse", f"merge state is not clean: {status.merge_state_status}"
61
+ return "merge", "PR is green"
62
+
63
+
64
+ def pr_merge_refs(payload: dict[str, Any]) -> PrMergeRefs:
65
+ return PrMergeRefs(
66
+ base_ref_name=str(payload.get("baseRefName") or ""),
67
+ base_ref_oid=str(payload.get("baseRefOid") or ""),
68
+ head_ref_name=str(payload.get("headRefName") or ""),
69
+ head_ref_oid=str(payload.get("headRefOid") or ""),
70
+ )
71
+
72
+
73
+ def _is_transient_merge_state(status: PrStatusDecision) -> bool:
74
+ return (
75
+ status.state == "OPEN"
76
+ and status.decision == "green"
77
+ and status.merge_state_status in {"UNKNOWN", ""}
78
+ )
79
+
80
+
81
+ def _normalise_merge_state_for_green_pr(
82
+ status: PrStatusDecision,
83
+ *,
84
+ wait_reason: str = "",
85
+ ) -> tuple[MergeDecision, str]:
86
+ """Return an actionable refusal reason for green PRs with unstable merge state."""
87
+ merge_state = status.merge_state_status or "UNKNOWN"
88
+ if status.state == "OPEN" and status.decision == "green" and merge_state in {"UNKNOWN", ""}:
89
+ return "refuse", wait_reason or f"merge state stayed {merge_state} after timeout"
90
+ if merge_state != "CLEAN":
91
+ return "refuse", f"merge state is not clean: {merge_state}"
92
+ return "merge", "PR is green"
93
+
94
+
95
+ def wait_for_pr_merge_state(
96
+ pr: str,
97
+ *,
98
+ timeout_seconds: int = 60,
99
+ poll_seconds: int = 5,
100
+ fetcher: PrPayloadFetcher | None = None,
101
+ sleep: Sleep = time.sleep,
102
+ ) -> tuple[dict[str, Any], PrStatusDecision, PrMergeRefs, str]:
103
+ """Wait for transient GitHub mergeability before final merge decision."""
104
+ payload_fetcher = fetcher or fetch_pr_payload
105
+ attempts = max(1, int(timeout_seconds / poll_seconds) if poll_seconds > 0 else 1)
106
+ payload: dict[str, Any] | None = None
107
+ status: PrStatusDecision | None = None
108
+ refs: PrMergeRefs | None = None
109
+
110
+ for attempt in range(1, attempts + 1):
111
+ payload = payload_fetcher(pr)
112
+ status = classify_pr_status(payload, pr=pr)
113
+ refs = pr_merge_refs(payload)
114
+ if not _is_transient_merge_state(status):
115
+ return payload, status, refs, ""
116
+ if attempt < attempts and poll_seconds > 0:
117
+ sleep(poll_seconds)
118
+
119
+ if payload is None or status is None or refs is None:
120
+ payload = payload_fetcher(pr)
121
+ status = classify_pr_status(payload, pr=pr)
122
+ refs = pr_merge_refs(payload)
123
+
124
+ merge_state = status.merge_state_status or "UNKNOWN"
125
+ return payload, status, refs, f"merge state stayed {merge_state} after timeout"
126
+
127
+
128
+ def verify_merge_refs(
129
+ refs: PrMergeRefs,
130
+ *,
131
+ expected_base_branch: str,
132
+ expected_head_sha: str = "",
133
+ ) -> tuple[MergeDecision, str]:
134
+ if not refs.base_ref_name:
135
+ return "refuse", "missing PR base branch"
136
+ if expected_base_branch and refs.base_ref_name != expected_base_branch:
137
+ return "refuse", f"PR base branch is {refs.base_ref_name}, expected {expected_base_branch}"
138
+ if not refs.head_ref_oid:
139
+ return "refuse", "missing PR head SHA"
140
+ if expected_head_sha and refs.head_ref_oid != expected_head_sha:
141
+ return "refuse", f"PR head changed: {refs.head_ref_oid} != {expected_head_sha}"
142
+ return "merge", "PR base/head refs verified"
143
+
144
+
145
+ def build_merge_args(
146
+ pr: str,
147
+ *,
148
+ merge_method: str,
149
+ delete_branch: bool,
150
+ match_head_sha: str,
151
+ ) -> list[str]:
152
+ args = ["pr", "merge", pr, f"--{merge_method}", "--match-head-commit", match_head_sha]
153
+ if delete_branch:
154
+ args.append("--delete-branch")
155
+ return args
156
+
157
+
158
+ def _run_gh(args: list[str]) -> subprocess.CompletedProcess[str]:
159
+ return subprocess.run(["gh", *args], text=True, capture_output=True, check=False)
160
+
161
+
162
+ def _run_gh_json(args: list[str]) -> Any:
163
+ completed = _run_gh(args)
164
+ if completed.returncode != 0:
165
+ raise RuntimeError((completed.stderr + completed.stdout).strip())
166
+ return json.loads(completed.stdout)
167
+
168
+
169
+ def fetch_merge_commit_sha(pr: str) -> str:
170
+ payload = _run_gh_json(["pr", "view", pr, "--json", "state,mergeCommit,mergedAt"])
171
+ if not isinstance(payload, dict):
172
+ raise RuntimeError("gh pr view did not return a JSON object")
173
+ merge_commit = payload.get("mergeCommit") or {}
174
+ if not isinstance(merge_commit, dict):
175
+ return ""
176
+ return str(merge_commit.get("oid") or "")
177
+
178
+
179
+ def fetch_main_run_payload(commit_sha: str, branch: str) -> dict[str, Any]:
180
+ runs = _run_gh_json(
181
+ [
182
+ "run",
183
+ "list",
184
+ "--branch",
185
+ branch,
186
+ "--commit",
187
+ commit_sha,
188
+ "--limit",
189
+ "20",
190
+ "--json",
191
+ "databaseId,status,conclusion,name,workflowName,url",
192
+ ]
193
+ )
194
+ if not isinstance(runs, list):
195
+ raise RuntimeError("gh run list did not return a JSON array")
196
+ checks: list[dict[str, Any]] = []
197
+ for run in runs:
198
+ if not isinstance(run, dict):
199
+ continue
200
+ checks.append(
201
+ {
202
+ "name": run.get("name") or run.get("workflowName") or "workflow",
203
+ "status": run.get("status"),
204
+ "conclusion": run.get("conclusion"),
205
+ "detailsUrl": run.get("url") or "",
206
+ }
207
+ )
208
+ return {
209
+ "state": "OPEN",
210
+ "mergeStateStatus": "CLEAN",
211
+ "headRefOid": commit_sha,
212
+ "statusCheckRollup": checks,
213
+ }
214
+
215
+
216
+ def verify_main_ci(
217
+ commit_sha: str,
218
+ *,
219
+ branch: str = "main",
220
+ timeout_seconds: int = 300,
221
+ poll_seconds: int = 10,
222
+ failed_log_lines: int = 120,
223
+ fetcher: MainRunFetcher = fetch_main_run_payload,
224
+ failed_log_fetcher: FailedLogFetcher | None = None,
225
+ sleep: Sleep = time.sleep,
226
+ ) -> PrStatusDecision:
227
+ attempts = max(1, int(timeout_seconds / poll_seconds) if poll_seconds > 0 else 1)
228
+ status: PrStatusDecision | None = None
229
+ for attempt in range(1, attempts + 1):
230
+ payload = fetcher(commit_sha, branch)
231
+ status = classify_pr_status(payload, pr=f"{branch}@{commit_sha[:12]}")
232
+ if status.decision not in {"pending", "no-checks"}:
233
+ break
234
+ if attempt < attempts and poll_seconds > 0:
235
+ sleep(poll_seconds)
236
+ if status is None:
237
+ payload = fetcher(commit_sha, branch)
238
+ status = classify_pr_status(payload, pr=f"{branch}@{commit_sha[:12]}")
239
+ if status.decision == "red":
240
+ if failed_log_fetcher is None:
241
+ status = attach_failed_run_logs(status, max_lines=failed_log_lines)
242
+ else:
243
+ status = attach_failed_run_logs(status, max_lines=failed_log_lines, fetcher=failed_log_fetcher)
244
+ return status
245
+
246
+
247
+ def merge_if_green(
248
+ pr: str,
249
+ *,
250
+ merge_method: str = "squash",
251
+ delete_branch: bool = True,
252
+ dry_run: bool = False,
253
+ verify_main: bool = True,
254
+ main_branch: str = "main",
255
+ expected_base_branch: str = "",
256
+ expected_head_sha: str = "",
257
+ main_ci_timeout_seconds: int = 300,
258
+ main_ci_poll_seconds: int = 10,
259
+ merge_state_timeout_seconds: int = 60,
260
+ merge_state_poll_seconds: int = 5,
261
+ pr_payload_fetcher: PrPayloadFetcher | None = None,
262
+ sleep: Sleep = time.sleep,
263
+ ) -> MergeIfGreenResult:
264
+ payload, status, refs, merge_state_wait_reason = wait_for_pr_merge_state(
265
+ pr,
266
+ timeout_seconds=merge_state_timeout_seconds,
267
+ poll_seconds=merge_state_poll_seconds,
268
+ fetcher=pr_payload_fetcher,
269
+ sleep=sleep,
270
+ )
271
+ effective_expected_base_branch = expected_base_branch or main_branch
272
+ effective_expected_head_sha = expected_head_sha or refs.head_ref_oid
273
+ decision, reason = decide_merge(status)
274
+ if decision != "merge":
275
+ normalised_decision, normalised_reason = _normalise_merge_state_for_green_pr(
276
+ status,
277
+ wait_reason=merge_state_wait_reason,
278
+ )
279
+ if normalised_decision != "merge":
280
+ decision, reason = normalised_decision, normalised_reason
281
+ elif merge_state_wait_reason:
282
+ reason = merge_state_wait_reason
283
+ if decision == "merge":
284
+ decision, ref_reason = verify_merge_refs(
285
+ refs,
286
+ expected_base_branch=effective_expected_base_branch,
287
+ expected_head_sha=expected_head_sha,
288
+ )
289
+ if decision != "merge":
290
+ reason = ref_reason
291
+
292
+ if decision != "merge" or dry_run:
293
+ return MergeIfGreenResult(
294
+ pr=pr,
295
+ decision=decision,
296
+ reason=reason if not dry_run else f"DRY_RUN: {reason}",
297
+ status_decision=status,
298
+ merged=False,
299
+ merge_output="",
300
+ base_ref_name=refs.base_ref_name,
301
+ base_ref_oid=refs.base_ref_oid,
302
+ head_ref_name=refs.head_ref_name,
303
+ head_ref_oid=refs.head_ref_oid,
304
+ expected_base_branch=effective_expected_base_branch,
305
+ expected_head_sha=effective_expected_head_sha,
306
+ main_verification_required=False,
307
+ )
308
+
309
+ args = build_merge_args(
310
+ pr,
311
+ merge_method=merge_method,
312
+ delete_branch=delete_branch,
313
+ match_head_sha=effective_expected_head_sha,
314
+ )
315
+
316
+ completed = _run_gh(args)
317
+ if completed.returncode != 0:
318
+ raise RuntimeError((completed.stderr + completed.stdout).strip())
319
+
320
+ merge_commit_sha = ""
321
+ main_status: PrStatusDecision | None = None
322
+ main_error = ""
323
+ if verify_main:
324
+ try:
325
+ merge_commit_sha = fetch_merge_commit_sha(pr)
326
+ if not merge_commit_sha:
327
+ main_error = "merged PR did not expose mergeCommit.oid"
328
+ else:
329
+ main_status = verify_main_ci(
330
+ merge_commit_sha,
331
+ branch=main_branch,
332
+ timeout_seconds=main_ci_timeout_seconds,
333
+ poll_seconds=main_ci_poll_seconds,
334
+ )
335
+ except RuntimeError as exc:
336
+ main_error = str(exc)
337
+
338
+ return MergeIfGreenResult(
339
+ pr=pr,
340
+ decision="merge",
341
+ reason=reason,
342
+ status_decision=status,
343
+ merged=True,
344
+ merge_output=(completed.stdout + completed.stderr).strip(),
345
+ base_ref_name=refs.base_ref_name,
346
+ base_ref_oid=refs.base_ref_oid,
347
+ head_ref_name=refs.head_ref_name,
348
+ head_ref_oid=refs.head_ref_oid,
349
+ expected_base_branch=effective_expected_base_branch,
350
+ expected_head_sha=effective_expected_head_sha,
351
+ merge_commit_sha=merge_commit_sha,
352
+ main_verification_required=verify_main,
353
+ main_status_decision=main_status,
354
+ main_verification_error=main_error,
355
+ )
356
+
357
+
358
+ def main_verification_passed(result: MergeIfGreenResult) -> bool:
359
+ if not result.main_verification_required:
360
+ return True
361
+ return result.main_status_decision is not None and result.main_status_decision.decision == "green"
362
+
363
+
364
+ def _render_failed_run_diagnostics(status: PrStatusDecision | None) -> list[str]:
365
+ if status is None:
366
+ return []
367
+ lines: list[str] = []
368
+ for diagnostic in status.failed_run_diagnostics:
369
+ lines.extend(
370
+ [
371
+ (
372
+ f"- check={diagnostic.check_name} conclusion={diagnostic.conclusion} "
373
+ f"run_id={diagnostic.run_id or '(missing)'} log_status={diagnostic.log_status}"
374
+ ),
375
+ f" command={diagnostic.command or '(unavailable)'}",
376
+ f" details_url={diagnostic.details_url or '(missing)'}",
377
+ ]
378
+ )
379
+ if diagnostic.error:
380
+ lines.append(f" error={diagnostic.error}")
381
+ if diagnostic.log_excerpt:
382
+ lines.append(" log_excerpt:")
383
+ lines.extend(f" {line}" for line in diagnostic.log_excerpt.splitlines())
384
+ return lines
385
+
386
+
387
+ def render_result(result: MergeIfGreenResult) -> str:
388
+ main_status = result.main_status_decision
389
+ main_decision = main_status.decision if main_status is not None else "not-run"
390
+ main_failed_hint = main_status.failed_run_log_hint if main_status is not None else "none"
391
+ final_marker = "### RESULT: PASS ###" if main_verification_passed(result) else "### RESULT: FAIL ###"
392
+ lines = [
393
+ "NEXT_TURN_MERGE_IF_GREEN",
394
+ f"pr={result.pr}",
395
+ f"decision={result.decision}",
396
+ f"reason={result.reason}",
397
+ f"status_decision={result.status_decision.decision}",
398
+ f"state={result.status_decision.state}",
399
+ f"merge_state_status={result.status_decision.merge_state_status}",
400
+ f"base_ref_name={result.base_ref_name or '(unknown)'}",
401
+ f"base_ref_oid={result.base_ref_oid or '(unknown)'}",
402
+ f"head_ref_name={result.head_ref_name or '(unknown)'}",
403
+ f"head_ref_oid={result.head_ref_oid or '(unknown)'}",
404
+ f"expected_base_branch={result.expected_base_branch or '(unspecified)'}",
405
+ f"expected_head_sha={result.expected_head_sha or '(unknown)'}",
406
+ f"merged={str(result.merged).lower()}",
407
+ f"merge_commit_sha={result.merge_commit_sha or '(unknown)'}",
408
+ f"main_verification_required={str(result.main_verification_required).lower()}",
409
+ f"main_verification_decision={main_decision}",
410
+ f"main_verification_passed={str(main_verification_passed(result)).lower()}",
411
+ f"main_failed_run_log_hint={main_failed_hint}",
412
+ f"main_verification_error={result.main_verification_error or 'none'}",
413
+ "failed_checks:",
414
+ *[f"- {item}" for item in result.status_decision.failed_checks],
415
+ "pending_checks:",
416
+ *[f"- {item}" for item in result.status_decision.pending_checks],
417
+ "unknown_checks:",
418
+ *[f"- {item}" for item in result.status_decision.unknown_checks],
419
+ "main_failed_run_diagnostics:",
420
+ *_render_failed_run_diagnostics(main_status),
421
+ final_marker,
422
+ ]
423
+ return "\n".join(lines)
424
+
425
+
426
+ def main() -> int:
427
+ parser = argparse.ArgumentParser(prog="next-turn-merge-if-green")
428
+ parser.add_argument("pr")
429
+ parser.add_argument("--merge-method", choices=["squash", "merge", "rebase"], default="squash")
430
+ parser.add_argument("--keep-branch", action="store_true")
431
+ parser.add_argument("--dry-run", action="store_true")
432
+ parser.add_argument("--skip-main-verification", action="store_true")
433
+ parser.add_argument("--main-branch", default="main")
434
+ parser.add_argument("--expected-base-branch", default="")
435
+ parser.add_argument("--expected-head-sha", default="")
436
+ parser.add_argument("--main-ci-timeout-seconds", type=int, default=300)
437
+ parser.add_argument("--main-ci-poll-seconds", type=int, default=10)
438
+ args = parser.parse_args()
439
+
440
+ result = merge_if_green(
441
+ args.pr,
442
+ merge_method=args.merge_method,
443
+ delete_branch=not args.keep_branch,
444
+ dry_run=args.dry_run,
445
+ verify_main=not args.skip_main_verification,
446
+ main_branch=args.main_branch,
447
+ expected_base_branch=args.expected_base_branch,
448
+ expected_head_sha=args.expected_head_sha,
449
+ main_ci_timeout_seconds=args.main_ci_timeout_seconds,
450
+ main_ci_poll_seconds=args.main_ci_poll_seconds,
451
+ )
452
+ print(render_result(result))
453
+ if args.dry_run:
454
+ return 0
455
+ return 0 if result.decision == "merge" and main_verification_passed(result) else 1
456
+
457
+
458
+ if __name__ == "__main__":
459
+ raise SystemExit(main())