Coverage for src/governed_harness/orchestration/ladder_delivery.py: 84%
150 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-12 16:06 +0000
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-12 16:06 +0000
1"""Complete delivery at CLOSURE (#55, item 13).
3After the closure commit (``delivery.closureCommit``), what leaves the machine follows the
4operational contract (the task's ``contract``, else ``delivery``):
6* **push** (``push``): the closure commit's branch is pushed to the remote with ``git push`` and
7 the repository's hooks run (never ``--no-verify``, never a forced push). A refusal stops
8 CLOSURE with the reason; ``run continue`` tries again;
9* **pull request** (``pullRequest.create``): after the push, the forge layer of #56
10 (``create_on_forge``: GitHub, GitLab, Bitbucket, Azure DevOps or Gitea, detected from
11 ``origin`` unless ``delivery.forge`` names it) creates the pull or merge request into
12 ``delivery.forge.baseBranch`` (else the remote's default branch) with the repository's
13 template followed by the decision brief, ``delivery.forge.labels`` and ``pullRequest.draft``
14 (else ``delivery.forge.draft``); it is created once per run, a retry reuses the recorded one;
15* **comment** (``comment``): the brief is commented (created or updated, one per run) on that
16 pull request through the same forge when the run is not
17 clean (``notClean``: a gate that did not pass, an exception, a blocking finding, a
18 certification that is not ``CERTIFIED``), always, or never;
19* **stage** (``stage``): when the change is not pushed, only the run's files are staged in the
20 workspace's index (``git add -- <paths>``, ``git rm --cached`` for deleted ones; never
21 ``add -A``), so the change waits there for the person.
23Each step is recorded as CLOSURE evidence and an event; nothing is repeated on a retry."""
25from __future__ import annotations
27from collections.abc import Callable
28from pathlib import Path
29from typing import TYPE_CHECKING, Any
31from governed_harness.delivery.closure import ClosureCommit
32from governed_harness.delivery.publisher import render_brief_markdown
33from governed_harness.delivery.vcs import Git, VcsError
34from governed_harness.domain.enums import DecisionKind, PhaseId, ResultStatus
35from governed_harness.domain.models import ChangeSet, Execution, HumanDecision, PhaseExecution, Task
36from governed_harness.orchestration.engine_types import PhaseOutcome
38if TYPE_CHECKING:
39 from governed_harness.forges import BaseForge, Transport
40 from governed_harness.orchestration.ladder_host import LadderHost
42TRANSPORT: dict[str, Transport | None] = {"override": None}
43"""A transport that replaces the forge's network transport (tests talk to a fake forge)."""
46class LadderDelivery:
47 def __init__(self, ladder: LadderHost) -> None:
48 self.ladder = ladder
50 def authorisation(self, task: Task) -> dict[str, Any]:
51 delivery = self.ladder.project.delivery_settings
52 contract = task.contract
53 pull = delivery.pull_request
55 def chosen(name: str, configured: Any) -> Any:
56 value = getattr(contract, name) if contract is not None else None
57 return configured if value is None else value
59 comment = chosen("comment", None)
60 if comment is None: 60 ↛ 63line 60 didn't jump to line 63 because the condition on line 60 was always true
61 comment_policy = delivery.comment or "never"
62 else:
63 comment_policy = "always" if comment else "never"
64 return {
65 "push": bool(chosen("push", delivery.push)),
66 "pullRequest": bool(chosen("create_pull_request", pull.create if pull else None)),
67 "comment": comment_policy,
68 "stage": bool(delivery.stage),
69 "branch": contract.branch if contract and contract.branch else None,
70 }
72 def deliver(
73 self,
74 execution: Execution,
75 phase: PhaseExecution,
76 decision: HumanDecision,
77 commit: ClosureCommit,
78 change_set: ChangeSet,
79 ) -> PhaseOutcome | None:
80 hub = self.ladder
81 results = hub.engine.results
82 task = hub.engine.run_task(execution)
83 allowed = self.authorisation(task)
84 state_key = f"delivered:{execution.execution_id}"
85 state: dict[str, Any] = results.flag_json(state_key) or {}
86 git = Git(hub.s.paths.workspace)
87 report: dict[str, Any] = {"authorisation": allowed, "commit": commit.commit}
88 branch = commit.branch
89 if commit.commit and branch is None and git.is_repository(): 89 ↛ 90line 89 didn't jump to line 90 because the condition on line 89 was never true
90 current = git.run("symbolic-ref", "--quiet", "--short", "HEAD", check=False)
91 branch = current.stdout.decode("utf-8", "replace").strip() or None
92 if not allowed["push"] or not commit.commit or not branch:
93 self._stage_only(execution, phase, git, change_set, allowed, state, report)
94 results.set_flag_json(state_key, state)
95 self._record(execution, report, "Delivery: change staged, not pushed")
96 return None
97 remote = self._remote()
98 steps: tuple[Callable[[], PhaseOutcome | None], ...] = (
99 lambda: self._push(execution, phase, git, remote, branch, commit, state),
100 lambda: self._pull_request(execution, task, git, remote, branch, allowed, state),
101 lambda: self._comment(execution, phase, decision, allowed, state),
102 )
103 for step in steps:
104 before = dict(state)
105 outcome = step()
106 if outcome is not None:
107 return outcome
108 if state != before: 108 ↛ 103line 108 didn't jump to line 103 because the condition on line 108 was always true
109 results.set_flag_json(state_key, state)
110 report["pushed"] = state["pushed"]
111 report["pullRequest"] = state.get("pullRequest")
112 report["comment"] = state.get("commented")
113 self._record(execution, report, f"Delivery: {branch} pushed to {remote}")
114 return None
116 # ----- the steps ------------------------------------------------------------------------------
117 def _stage_only(
118 self,
119 execution: Execution,
120 phase: PhaseExecution,
121 git: Git,
122 change_set: ChangeSet,
123 allowed: dict[str, Any],
124 state: dict[str, Any],
125 report: dict[str, Any],
126 ) -> None:
127 """When the change is not pushed: stage the run's files once, if the contract says so."""
128 if not allowed["stage"] or not git.is_repository() or state.get("staged"):
129 return
130 staged = self._stage(git, self.ladder.s.paths.workspace, change_set)
131 state["staged"] = staged
132 report["staged"] = staged
133 self.ladder.s.events.append(
134 execution.execution_id,
135 "delivery.staged",
136 {"paths": staged, "reason": "the contract does not authorise a push"},
137 phase_execution_id=phase.phase_execution_id,
138 )
140 def _push(
141 self,
142 execution: Execution,
143 phase: PhaseExecution,
144 git: Git,
145 remote: str,
146 branch: str,
147 commit: ClosureCommit,
148 state: dict[str, Any],
149 ) -> PhaseOutcome | None:
150 """Push the closure commit's branch once; a refusal stops CLOSURE with the reason."""
151 if state.get("pushed"): 151 ↛ 152line 151 didn't jump to line 152 because the condition on line 151 was never true
152 return None
153 events = self.ladder.s.events
154 try:
155 git.run("push", remote, f"{branch}:{branch}")
156 except VcsError as error:
157 events.append(
158 execution.execution_id,
159 "delivery.push.failed",
160 {"remote": remote, "branch": branch, "reason": str(error)[:500]},
161 phase_execution_id=phase.phase_execution_id,
162 )
163 return PhaseOutcome(ResultStatus.BLOCKED, f"Push of {branch} refused: {error}")
164 state["pushed"] = {"remote": remote, "branch": branch, "commit": commit.commit}
165 events.append(
166 execution.execution_id,
167 "delivery.pushed",
168 state["pushed"],
169 phase_execution_id=phase.phase_execution_id,
170 )
171 return None
173 def _pull_request(
174 self,
175 execution: Execution,
176 task: Task,
177 git: Git,
178 remote: str,
179 branch: str,
180 allowed: dict[str, Any],
181 state: dict[str, Any],
182 ) -> PhaseOutcome | None:
183 """Create the pull request once, when the contract authorises it."""
184 if not allowed["pullRequest"] or state.get("pullRequest"): 184 ↛ 185line 184 didn't jump to line 185 because the condition on line 184 was never true
185 return None
186 from governed_harness.application.forges import create_on_forge, forge_settings
188 hub = self.ladder
189 pull = hub.project.delivery_settings.pull_request
190 try:
191 # The forge layer of #56 records delivery.pull-request.created itself.
192 created = create_on_forge(
193 hub.s,
194 execution.execution_id,
195 head=branch,
196 base=forge_settings(hub.s).base_branch or self._base(git, remote),
197 title=task.title,
198 draft=pull.draft if pull else None,
199 transport_override=TRANSPORT["override"],
200 )
201 except Exception as error: # noqa: BLE001 # the reason is reported, CLOSURE waits
202 return PhaseOutcome(
203 ResultStatus.BLOCKED, f"The pull request of {branch} was not created: {error}"
204 )
205 state["pullRequest"] = {
206 **created["pullRequest"],
207 "forge": created["forge"]["kind"],
208 "repository": created["forge"]["repository"],
209 "head": created["head"],
210 "base": created["base"],
211 "labels": created["labels"],
212 "template": created["template"],
213 }
214 return None
216 def _comment(
217 self,
218 execution: Execution,
219 phase: PhaseExecution,
220 decision: HumanDecision,
221 allowed: dict[str, Any],
222 state: dict[str, Any],
223 ) -> PhaseOutcome | None:
224 """Comment the brief on the pull request once, as the comment policy says."""
225 number = (state.get("pullRequest") or {}).get("number")
226 if not isinstance(number, int) or state.get("commented"): 226 ↛ 227line 226 didn't jump to line 227 because the condition on line 226 was never true
227 return None
228 policy = allowed["comment"]
229 reasons = self.not_clean(execution, decision)
230 if policy != "always" and not (policy == "notClean" and reasons): 230 ↛ 231line 230 didn't jump to line 231 because the condition on line 230 was never true
231 return None
232 try:
233 posted = self._forge().upsert_comment(
234 number, execution.execution_id, self._brief(execution)
235 )
236 except Exception as error: # noqa: BLE001 # the reason is reported, CLOSURE waits
237 return PhaseOutcome(
238 ResultStatus.BLOCKED, f"The comment on #{number} was not posted: {error}"
239 )
240 state["commented"] = {**posted, "reasons": reasons}
241 self.ladder.s.events.append(
242 execution.execution_id,
243 "delivery.comment.posted",
244 state["commented"],
245 phase_execution_id=phase.phase_execution_id,
246 )
247 return None
249 # ----- helpers --------------------------------------------------------------------------------
250 def _stage(self, git: Git, workspace: Path, change_set: ChangeSet) -> list[str]:
251 present = [item.path for item in change_set.files if (workspace / item.path).exists()]
252 gone = [item.path for item in change_set.files if not (workspace / item.path).exists()]
253 if present: 253 ↛ 255line 253 didn't jump to line 255 because the condition on line 253 was always true
254 git.run("add", "--", *present)
255 if gone: 255 ↛ 256line 255 didn't jump to line 256 because the condition on line 255 was never true
256 git.run("rm", "--cached", "--quiet", "--ignore-unmatch", "--", *gone)
257 return sorted([*present, *gone])
259 def _remote(self) -> str:
260 isolation = self.ladder.project.workspace.isolation
261 return (isolation.remote if isolation and isolation.remote else None) or "origin"
263 @staticmethod
264 def _base(git: Git, remote: str) -> str:
265 value = git.run(
266 "symbolic-ref", "--quiet", "--short", f"refs/remotes/{remote}/HEAD", check=False
267 )
268 head = value.stdout.decode("utf-8", "replace").strip()
269 return head.split("/", 1)[1] if "/" in head else "main"
271 def _forge(self) -> BaseForge:
272 """The forge of the workspace (#56): ``delivery.forge``, else the ``origin`` remote."""
273 from governed_harness.application.forges import forge_settings
274 from governed_harness.forges import open_forge, resolve_forge
276 services = self.ladder.s
277 resolved = resolve_forge(services.paths.workspace, forge_settings(services))
278 return open_forge(resolved, TRANSPORT["override"])
280 def _brief(self, execution: Execution) -> str:
281 from governed_harness.application.exceptions import brief_exceptions
282 from governed_harness.application.review import build_brief
284 services = self.ladder.s
285 brief = build_brief(
286 services,
287 execution.execution_id,
288 exceptions=brief_exceptions(
289 services, self.ladder.engine.get_execution(execution.execution_id)
290 ),
291 )
292 return render_brief_markdown(brief)
294 def not_clean(self, execution: Execution, decision: HumanDecision) -> list[str]:
295 """Why a run is not clean: what a reviewer of the pull request should look at."""
296 from governed_harness.domain.models import GateEvaluation
298 reasons: list[str] = []
299 if decision.decision is DecisionKind.APPROVE_EXCEPTION: 299 ↛ 301line 299 didn't jump to line 301 because the condition on line 299 was always true
300 reasons.append("approved with an exception")
301 latest = self.ladder.engine.get_execution(execution.execution_id)
302 if latest.gate_evaluation_id: 302 ↛ 306line 302 didn't jump to line 306 because the condition on line 302 was always true
303 gate = self.ladder.s.state.get("gate", latest.gate_evaluation_id, GateEvaluation)
304 if gate.status is not ResultStatus.PASSED: 304 ↛ 305line 304 didn't jump to line 305 because the condition on line 304 was never true
305 reasons.append(f"gate {gate.status.value}")
306 certification = self.ladder.latest_certification(
307 execution.execution_id, decision.change_set_digest
308 )
309 if certification is not None and certification.status != "CERTIFIED": 309 ↛ 310line 309 didn't jump to line 310 because the condition on line 309 was never true
310 reasons.append(f"certification {certification.status}")
311 return reasons
313 def _record(self, execution: Execution, report: dict[str, Any], summary: str) -> None:
314 self.ladder.engine.results.record_json(
315 execution, PhaseId.CLOSURE, report, kind="delivery-report", summary=summary
316 )
319__all__ = ["TRANSPORT", "LadderDelivery"]