Coverage for src/governed_harness/delivery/closure.py: 87%
134 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"""The closure commit (``delivery.closureCommit``, since 2.0).
3A decision binds the digest of the workspace ChangeSet, but what a team merges is a commit. At
4CLOSURE the harness writes the approved ChangeSet as one commit whose parent is ``HEAD``:
61. every ChangeSet file must still have the approved content (its ``afterDigest``) and every
7 file it changes must have its baseline content at ``HEAD`` (its ``beforeDigest``);
82. the tree is built in a temporary index from ``HEAD`` plus the ChangeSet files, so the
9 working tree, the index and the current branch are not touched;
103. the commit carries the trailers ``Harness-Run``, ``Harness-Task``, ``Harness-ChangeSet``,
11 ``Harness-Decision`` and, for ``APPROVE_EXCEPTION``, ``Harness-Exception``;
124. its diff against ``HEAD`` is recomputed (``delivery.vcs.revision_diff``) and must equal the
13 approved digest before any ref points to it;
145. ``branch`` creates the branch (``harness/{runId}`` by default); ``head`` moves the current
15 branch to the commit and refreshes the index entries of the ChangeSet paths.
17A workspace that is not a Git repository, has no commit, or whose ``HEAD`` does not hold the
18baseline of a ChangeSet file (the run started on uncommitted changes, for example after an
19earlier run whose change is not committed yet) gets no commit: the closure records why
20(``delivery.commit.skipped``), because a commit on ``HEAD`` would carry more than what was
21approved. Any other failure (the workspace no longer holds the approved content, a branch of the
22same name that is not this run's, Git refusing an operation) stops CLOSURE: the run stays open
23with the reason, and ``run continue`` tries again (a branch already holding this run's commit is
24reused)."""
26from __future__ import annotations
28import os
29import tempfile
30from dataclasses import dataclass, field, replace
31from pathlib import Path
32from typing import Any
34from governed_harness.configuration.models import DeliveryConfig
35from governed_harness.delivery.vcs import Git, VcsError, revision_diff
36from governed_harness.domain.enums import DecisionKind
37from governed_harness.domain.models import ChangedFile, ChangeSet, HumanDecision, Task
38from governed_harness.evidence.hashing import sha256_bytes
40TRAILER_RUN = "Harness-Run"
41TRAILER_TASK = "Harness-Task"
42TRAILER_CHANGESET = "Harness-ChangeSet"
43TRAILER_DECISION = "Harness-Decision"
44TRAILER_EXCEPTION = "Harness-Exception"
45_SUBJECT_CHARS = 72
46_RATIONALE_CHARS = 200
49class ClosureCommitError(VcsError):
50 """The closure commit cannot be created; CLOSURE does not pass."""
53@dataclass(frozen=True)
54class ClosureCommit:
55 mode: str
56 status: str # CREATED, REUSED or SKIPPED
57 reason: str | None = None
58 commit: str | None = None
59 parent: str | None = None
60 branch: str | None = None
61 trailers: dict[str, str] = field(default_factory=dict)
62 author: str | None = None
63 subject: str | None = None
65 def as_dict(self) -> dict[str, Any]:
66 extra = {"author": self.author, "subject": self.subject} if self.author else {}
67 return extra | {
68 "mode": self.mode,
69 "status": self.status,
70 "reason": self.reason,
71 "commit": self.commit,
72 "parent": self.parent,
73 "branch": self.branch,
74 "trailers": self.trailers,
75 }
78def _one_line(text: str, limit: int) -> str:
79 value = " ".join(text.split())
80 return value if len(value) <= limit else value[: limit - 1].rstrip() + "…"
83def closure_trailers(
84 execution_id: str, task: Task, change_set: ChangeSet, decision: HumanDecision
85) -> dict[str, str]:
86 trailers = {
87 TRAILER_RUN: execution_id,
88 TRAILER_TASK: task.task_id,
89 TRAILER_CHANGESET: change_set.digest,
90 TRAILER_DECISION: f"{decision.decision_id} {decision.decision.value}",
91 }
92 if decision.decision is DecisionKind.APPROVE_EXCEPTION:
93 trailers[TRAILER_EXCEPTION] = _one_line(decision.rationale, _RATIONALE_CHARS)
94 return trailers
97def commit_message(
98 execution_id: str,
99 task: Task,
100 change_set: ChangeSet,
101 decision: HumanDecision,
102 trailers: dict[str, str],
103) -> str:
104 body = (
105 f"Approved ChangeSet of harness run {execution_id} (task {task.task_id}): "
106 f"{len(change_set.files)} file(s).\n"
107 f"{decision.decision.value} by {decision.actor.actor_id} at "
108 f"{decision.decided_at.isoformat()}: {_one_line(decision.rationale, _RATIONALE_CHARS)}"
109 )
110 footer = "\n".join(f"{key}: {value}" for key, value in trailers.items())
111 return f"{_one_line(task.title, _SUBJECT_CHARS)}\n\n{body}\n\n{footer}\n"
114def commit_author(git: Git, commit: str) -> tuple[str, str]:
115 """Author (``Name <email>``) and subject of ``commit``, as Git shows them."""
116 shown = git.text("show", "-s", "--format=%an <%ae>%x1f%s", commit)
117 author, _, subject = shown.partition("\x1f")
118 return author, subject
121def branch_name(config: DeliveryConfig, execution_id: str, task_id: str) -> str:
122 return config.branch_template.replace("{runId}", execution_id).replace("{taskId}", task_id)
125def _mode(git: Git, head: str, relative: str, path: Path) -> str:
126 """The mode the file has at ``HEAD`` (a ChangeSet does not record modes), or, for a new
127 file, executable when the workspace file is."""
128 listed = git.text("ls-tree", head, "--", relative)
129 mode = listed.split(" ", 1)[0] if listed else ""
130 if mode in {"100644", "100755"}:
131 return mode
132 return "100755" if os.name != "nt" and os.access(path, os.X_OK) else "100644"
135def _reused_branch(
136 git: Git,
137 mode: str,
138 branch: str,
139 execution_id: str,
140 change_set: ChangeSet,
141 trailers: dict[str, str],
142) -> ClosureCommit | None:
143 """``REUSED`` when ``branch`` already holds this run's commit, ``None`` when it does not
144 exist; any other existing branch is an error."""
145 existing = git.resolve(f"refs/heads/{branch}")
146 if existing is None: 146 ↛ 148line 146 didn't jump to line 148 because the condition on line 146 was always true
147 return None
148 parent = git.resolve(f"{existing}~1")
149 found = (
150 {key: value for item in git.trailers(parent, existing) for key, value in item.items()}
151 if parent
152 else {}
153 )
154 if found.get(TRAILER_RUN) == execution_id and found.get(TRAILER_CHANGESET) == change_set.digest:
155 return ClosureCommit(mode, "REUSED", None, existing, parent, branch, trailers)
156 raise ClosureCommitError(
157 f"branch {branch} already exists and does not hold this run's commit; "
158 "set delivery.branch or delete the branch, then run continue"
159 )
162def _work_is_stale(workspace: Path, item: ChangedFile) -> bool:
163 """The workspace no longer holds the approved content of ``item``."""
164 target = workspace / item.path
165 if item.after_digest is None: 165 ↛ 166line 165 didn't jump to line 166 because the condition on line 165 was never true
166 return target.exists()
167 return not target.is_file() or sha256_bytes(target.read_bytes()) != item.after_digest
170def _stale_paths(
171 git: Git, workspace: Path, head: str, change_set: ChangeSet
172) -> tuple[list[str], list[str]]:
173 """The paths whose baseline ``HEAD`` does not hold, and those the workspace changed since."""
174 stale_base = []
175 stale_work = []
176 for item in change_set.files:
177 current = git.blob(head, item.path)
178 if (sha256_bytes(current) if current is not None else None) != item.before_digest:
179 stale_base.append(item.path)
180 if _work_is_stale(workspace, item):
181 stale_work.append(item.path)
182 return stale_base, stale_work
185def _write_tree(git: Git, workspace: Path, head: str, change_set: ChangeSet) -> str:
186 """The tree of ``HEAD`` with the approved ChangeSet applied, built in a private index."""
187 with tempfile.TemporaryDirectory(prefix="harness-index-") as directory:
188 index = {"GIT_INDEX_FILE": str(Path(directory) / "index")}
189 git.run("read-tree", head, env=index)
190 for item in change_set.files:
191 if item.after_digest is None: 191 ↛ 192line 191 didn't jump to line 192 because the condition on line 191 was never true
192 git.run("update-index", "--force-remove", "--", item.path, env=index)
193 continue
194 path = workspace / item.path
195 blob = git.text("hash-object", "-w", "--no-filters", "--stdin", stdin=path.read_bytes())
196 git.run(
197 "update-index",
198 "--add",
199 "--cacheinfo",
200 f"{_mode(git, head, item.path, path)},{blob},{item.path}",
201 env=index,
202 )
203 return git.text("write-tree", env=index)
206def create_closure_commit(
207 workspace: Path,
208 config: DeliveryConfig,
209 *,
210 execution_id: str,
211 task: Task,
212 change_set: ChangeSet,
213 decision: HumanDecision,
214) -> ClosureCommit:
215 result = _create_closure_commit(workspace, config, execution_id, task, change_set, decision)
216 if config.record_commit_author and result.commit:
217 author, subject = commit_author(Git(workspace), result.commit)
218 result = replace(result, author=author, subject=subject)
219 return result
222def _create_closure_commit(
223 workspace: Path,
224 config: DeliveryConfig,
225 execution_id: str,
226 task: Task,
227 change_set: ChangeSet,
228 decision: HumanDecision,
229) -> ClosureCommit:
230 mode = config.mode
231 git = Git(workspace)
232 if not git.is_repository(): 232 ↛ 233line 232 didn't jump to line 233 because the condition on line 232 was never true
233 return ClosureCommit(mode, "SKIPPED", "the workspace is not a Git repository")
234 head = git.resolve("HEAD")
235 if head is None: 235 ↛ 236line 235 didn't jump to line 236 because the condition on line 235 was never true
236 return ClosureCommit(mode, "SKIPPED", "the repository has no commit to build on")
237 trailers = closure_trailers(execution_id, task, change_set, decision)
238 branch = branch_name(config, execution_id, task.task_id) if mode == "branch" else None
239 if branch is not None:
240 reused = _reused_branch(git, mode, branch, execution_id, change_set, trailers)
241 if reused is not None: 241 ↛ 242line 241 didn't jump to line 242 because the condition on line 241 was never true
242 return reused
243 stale_base, stale_work = _stale_paths(git, workspace, head, change_set)
244 if stale_work:
245 raise ClosureCommitError(
246 f"the workspace no longer holds the approved content of {', '.join(sorted(stale_work))}"
247 )
248 if stale_base:
249 # A commit on HEAD would also carry changes nobody approved in this run; the approval
250 # stays valid, so CLOSURE records why there is no commit instead of creating one.
251 return ClosureCommit(
252 mode,
253 "SKIPPED",
254 f"HEAD ({head[:12]}) does not hold the baseline of {', '.join(sorted(stale_base))} "
255 "(uncommitted changes when the run started, or HEAD moved): a commit on HEAD would "
256 "carry more than the approved ChangeSet",
257 parent=head,
258 branch=branch,
259 trailers=trailers,
260 )
261 tree = _write_tree(git, workspace, head, change_set)
262 message = commit_message(execution_id, task, change_set, decision, trailers)
263 commit = git.text(
264 "commit-tree",
265 tree,
266 "-p",
267 head,
268 "-F",
269 "-",
270 stdin=message.encode("utf-8"),
271 env=git.identity_env(),
272 )
273 recomputed = revision_diff(workspace, head, commit)
274 if recomputed.digest != change_set.digest or recomputed.special: 274 ↛ 275line 274 didn't jump to line 275 because the condition on line 274 was never true
275 raise ClosureCommitError(
276 f"the commit's diff recomputes to {recomputed.digest}, not the approved "
277 f"{change_set.digest}; no ref was updated"
278 )
279 _update_ref(git, branch, execution_id, commit, head, change_set)
280 return ClosureCommit(mode, "CREATED", None, commit, head, branch, trailers)
283def _update_ref(
284 git: Git,
285 branch: str | None,
286 execution_id: str,
287 commit: str,
288 head: str,
289 change_set: ChangeSet,
290) -> None:
291 """Create ``branch`` at ``commit``, or move ``HEAD`` to it and refresh the index."""
292 if branch is not None:
293 git.run(
294 "update-ref",
295 "-m",
296 f"harness closure {execution_id}",
297 f"refs/heads/{branch}",
298 commit,
299 "",
300 )
301 return
302 git.run("update-ref", "-m", f"harness closure {execution_id}", "HEAD", commit, head)
303 paths = [item.path for item in change_set.files]
304 if paths: 304 ↛ exitline 304 didn't return from function '_update_ref' because the condition on line 304 was always true
305 git.run("reset", "-q", "--", *paths)