Coverage for src/governed_harness/delivery/approval.py: 90%

73 statements  

« prev     ^ index     » next       coverage.py v7.17.2, created at 2026-11-12 16:06 +0000

1"""``harness verify-approval``: is what gets merged what a person approved? 

2 

3The command recomputes the ChangeSet digest of a range of commits (``--base`` to ``--head``, for 

4example the base and head of a pull request) with the computation the harness applies to the 

5workspace, and looks for a human decision ``APPROVE`` or ``APPROVE_EXCEPTION`` bound to exactly 

6that digest: 

7 

8* in portable evidence bundles (``--bundle``, verified first: entries, event chain, decision 

9 records), and 

10* in the workspace's own ``.harness/state.db`` when it exists (a local or self-hosted run), with 

11 the event chain of each run verified. 

12 

13The range passes only when an approval that has not expired matches the recomputed digest and 

14the range holds nothing a ChangeSet cannot (a mode-only change, a symbolic link, a submodule). 

15Any other change in the range (a commit after the closure commit, a rebase that changed the 

16context of a hunk, a file the ChangeSet excluded) changes the digest and the range fails: the 

17approval holds for what was approved, nothing else. The ``Harness-*`` trailers of the commits 

18in the range are reported to tell which run a commit claims; a trailer alone never approves.""" 

19 

20from __future__ import annotations 

21 

22import contextlib 

23from collections.abc import Sequence 

24from datetime import datetime 

25from pathlib import Path 

26from typing import Any 

27 

28from governed_harness.delivery.bundle import decision_entries, verify_bundle 

29from governed_harness.delivery.vcs import Git, RevisionDiff, revision_diff 

30from governed_harness.domain.models import utc_now 

31from governed_harness.events.sqlite_store import SQLiteEventStore 

32 

33 

34def local_database(root: Path) -> Path: 

35 """The workspace's state database: ``.harness/state.db``, or the registry 

36 ``runtime.stateDir`` names (#55) when the workspace has a project configuration.""" 

37 config = root / ".harness" / "project.yaml" 

38 if config.is_file(): 38 ↛ 48line 38 didn't jump to line 48 because the condition on line 38 was always true

39 # An unreadable configuration keeps the 1.0.0 path. 

40 with contextlib.suppress(Exception): 

41 from governed_harness.configuration.loader import load_project_config 

42 from governed_harness.runtime.state_location import resolve_state_location 

43 

44 project = load_project_config(config) 

45 return resolve_state_location( 

46 root, project.project_id, project.runtime.state_dir, create=False 

47 ).database 

48 return root / ".harness" / "state.db" 

49 

50 

51def _local_approvals(root: Path, now: datetime) -> list[dict[str, Any]]: 

52 database = local_database(root) 

53 if not database.is_file(): 53 ↛ 54line 53 didn't jump to line 54 because the condition on line 53 was never true

54 return [] 

55 found: list[dict[str, Any]] = [] 

56 with SQLiteEventStore(database) as store: 

57 events = store.list_all() 

58 runs = sorted({event.execution_id for event in events}) 

59 for run in runs: 

60 try: 

61 store.verify_chain(run) 

62 valid, problems = True, [] 

63 except ValueError as error: 

64 valid, problems = False, [str(error)] 

65 payloads = [event.as_dict() for event in events if event.execution_id == run] 

66 for decision in decision_entries(payloads, now): 

67 found.append( 

68 { 

69 **decision, 

70 "source": "workspace", 

71 "executionId": run, 

72 "evidenceValid": valid, 

73 "problems": problems, 

74 } 

75 ) 

76 return found 

77 

78 

79def verify_approval( 

80 root: Path, 

81 base: str, 

82 head: str = "HEAD", 

83 *, 

84 bundles: Sequence[Path] = (), 

85 use_workspace: bool = True, 

86 now: datetime | None = None, 

87) -> dict[str, Any]: 

88 moment = now or utc_now() 

89 diff = revision_diff(root, base, head) 

90 approvals: list[dict[str, Any]] = [] 

91 for bundle in bundles: 

92 approvals.extend(_bundle_approvals(bundle, moment)) 

93 if use_workspace: 

94 approvals.extend(_local_approvals(root, moment)) 

95 for item in approvals: 

96 item["matches"] = _matches(item, diff.digest) 

97 matched = [item for item in approvals if item["matches"]] 

98 trailers = Git(root).trailers(diff.base, diff.head) 

99 reasons = _approval_reasons(diff, bool(matched), trailers) 

100 passed = bool(matched) and not diff.special and bool(diff.paths) 

101 return { 

102 "status": "PASSED" if passed else "FAILED", 

103 "base": diff.base, 

104 "head": diff.head, 

105 "computedDigest": diff.digest, 

106 "files": [ 

107 { 

108 "path": change.path, 

109 "status": change.status, 

110 "additions": change.additions, 

111 "deletions": change.deletions, 

112 } 

113 for change in diff.diff.changes 

114 ], 

115 "special": list(diff.special), 

116 "trailers": trailers, 

117 "approvals": approvals, 

118 "matchedApproval": matched[0] if matched else None, 

119 "reasons": reasons, 

120 } 

121 

122 

123def _bundle_approvals(bundle: Path, moment: datetime) -> list[dict[str, Any]]: 

124 """The decisions of one bundle, or one non-approval entry when it holds none.""" 

125 report = verify_bundle(bundle, moment) 

126 approvals = [ 

127 { 

128 **decision, 

129 "source": f"bundle:{bundle}", 

130 "executionId": report["executionId"], 

131 "evidenceValid": report["valid"], 

132 "problems": report["problems"], 

133 } 

134 for decision in report["decisions"] 

135 ] 

136 if not report["decisions"]: 136 ↛ 137line 136 didn't jump to line 137 because the condition on line 136 was never true

137 approvals.append( 

138 { 

139 "source": f"bundle:{bundle}", 

140 "executionId": report["executionId"], 

141 "decision": None, 

142 "approval": False, 

143 "changeSetDigest": None, 

144 "expired": False, 

145 "evidenceValid": report["valid"], 

146 "problems": report["problems"], 

147 } 

148 ) 

149 return approvals 

150 

151 

152def _matches(item: dict[str, Any], digest: str) -> bool: 

153 """A valid, unexpired approval bound to ``digest``.""" 

154 return bool( 

155 item.get("approval") 

156 and item.get("changeSetDigest") == digest 

157 and not item.get("expired") 

158 and item.get("evidenceValid") 

159 ) 

160 

161 

162def _approval_reasons( 

163 diff: RevisionDiff, matched: bool, trailers: list[dict[str, str]] 

164) -> list[str]: 

165 """Why the range fails, plus informational ChangeSet trailers that disagree with it.""" 

166 reasons: list[str] = [] 

167 if not diff.paths: 

168 reasons.append("the range changes no file: there is nothing an approval could cover") 

169 if diff.special: 169 ↛ 170line 169 didn't jump to line 170 because the condition on line 169 was never true

170 reasons.append( 

171 "the range holds changes a ChangeSet cannot hold: " + ", ".join(diff.special) 

172 ) 

173 if not matched: 

174 reasons.append( 

175 f"no valid, unexpired APPROVE or APPROVE_EXCEPTION is bound to {diff.digest}" 

176 ) 

177 for item in trailers: 

178 claimed = item.get("Harness-ChangeSet") 

179 if claimed and claimed != diff.digest: 

180 reasons.append( 

181 f"commit {item['commit'][:12]} claims ChangeSet {claimed}; the range recomputes " 

182 f"to {diff.digest} (informational)" 

183 ) 

184 return reasons