Coverage for src/governed_harness/ladder/contract.py: 98%

84 statements  

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

1"""The operational contract of a task (#55, item 7). 

2 

3Before work starts, the person and the harness agree on one summary: the objective, 

4reproducible examples, the scope (and what is out of it), the definition of done, the 

5verification level required, the branch, whether to push, create a pull request and comment on 

6it, and the coverage threshold. Each item comes from the task's ``contract`` when it declares 

7it, else from the rest of the task (intent, requirements, criteria) or the project 

8configuration; an item nobody settled is ``missing``. The summary has a digest and is bound to 

9the task digest it was derived from: a revision of the task gives another summary. 

10 

11Under ``intake.operationalContract: batch`` the items are added to the one clarification 

12request INTENT sends anyway; under ``enforce`` INTENT also asks for every missing item and 

13waits for a person to confirm the summary (``harness task confirm``).""" 

14 

15from __future__ import annotations 

16 

17import re 

18from dataclasses import dataclass 

19from typing import Any 

20 

21from governed_harness.domain.models import Task 

22from governed_harness.evidence.hashing import sha256_json 

23 

24_ANCHOR = re.compile( 

25 r"\d|[`'\"]|\w+\(|\b[a-z]+_[a-z_]+\b|\b(returns?|raises?|rejects?|equals?|contains?|prints?|" 

26 r"exits?|responds?|lists?|stores?)\b", 

27 re.IGNORECASE, 

28) 

29 

30CONTRACT_FIELDS: tuple[str, ...] = ( 

31 "objective", 

32 "examples", 

33 "scope", 

34 "outOfScope", 

35 "definitionOfDone", 

36 "verificationLevel", 

37 "branch", 

38 "push", 

39 "createPullRequest", 

40 "comment", 

41 "coverageThreshold", 

42) 

43 

44QUESTIONS: dict[str, str] = { 

45 "objective": "What is the objective of the task, in one sentence?", 

46 "examples": ( 

47 "Which reproducible examples show the expected behaviour (input or action -> exact " 

48 "result), one per line?" 

49 ), 

50 "scope": "Which behaviours or paths are in scope, one per line?", 

51 "outOfScope": "What is explicitly out of scope, one per line?", 

52 "definitionOfDone": "What must hold for the task to be done (the definition of done)?", 

53 "verificationLevel": ( 

54 "Which verification level is required (L0 static, L1 unit, L2 integration, L3 " 

55 "executable behaviour, L4 external environment, L5 human)?" 

56 ), 

57 "branch": "On which branch should the change be delivered?", 

58 "push": "May the harness push the approved change (yes or no)?", 

59 "createPullRequest": "Should the harness create a pull request for it (yes or no)?", 

60 "comment": "Should the harness comment the decision brief on the pull request (yes or no)?", 

61 "coverageThreshold": "Which coverage of the changed lines is required (0 to 100)?", 

62} 

63 

64 

65@dataclass(frozen=True) 

66class ContractItem: 

67 field: str 

68 value: Any 

69 source: str # task, derived, project, missing 

70 question: str 

71 

72 def as_dict(self) -> dict[str, Any]: 

73 return { 

74 "field": self.field, 

75 "value": self.value, 

76 "source": self.source, 

77 "question": self.question, 

78 } 

79 

80 

81@dataclass(frozen=True) 

82class ContractSummary: 

83 task_digest: str 

84 items: tuple[ContractItem, ...] 

85 assumptions: tuple[dict[str, Any], ...] = () 

86 """Since #79: the points the agent review left open, recorded as assumptions of the task 

87 revision (``metadata.assumptions``); part of the summary and its digest only when there 

88 are any.""" 

89 

90 @property 

91 def missing(self) -> tuple[str, ...]: 

92 return tuple(item.field for item in self.items if item.source == "missing") 

93 

94 @property 

95 def values(self) -> dict[str, Any]: 

96 return {item.field: item.value for item in self.items} 

97 

98 @property 

99 def digest(self) -> str: 

100 value: dict[str, Any] = {"taskDigest": self.task_digest, "values": self.values} 

101 if self.assumptions: 

102 value["assumptions"] = list(self.assumptions) 

103 return sha256_json(value) 

104 

105 def as_dict(self) -> dict[str, Any]: 

106 value: dict[str, Any] = { 

107 "digest": self.digest, 

108 "taskDigest": self.task_digest, 

109 "items": [item.as_dict() for item in self.items], 

110 "missing": list(self.missing), 

111 } 

112 if self.assumptions: 

113 value["assumptions"] = list(self.assumptions) 

114 return value 

115 

116 

117def _item(field: str, value: Any, source: str) -> ContractItem: 

118 empty = value is None or value == [] or value == "" 

119 return ContractItem( 

120 field, None if empty else value, "missing" if empty else source, QUESTIONS[field] 

121 ) 

122 

123 

124_SETTINGS = ( 

125 ("verificationLevel", "verification_level"), 

126 ("branch", "branch"), 

127 ("push", "push"), 

128 ("createPullRequest", "create_pull_request"), 

129 ("comment", "comment"), 

130 ("coverageThreshold", "coverage_threshold"), 

131) 

132 

133 

134def _declared_value(declared: Any, name: str) -> Any: 

135 """A field of the task's contract declaration: an empty list is ``None``, an enum its 

136 value.""" 

137 if declared is None: 

138 return None 

139 value = getattr(declared, name) 

140 if isinstance(value, tuple): 

141 return list(value) or None 

142 if hasattr(value, "value"): 

143 return value.value 

144 return value 

145 

146 

147def _examples_item(task: Task, examples: Any) -> ContractItem: 

148 if examples: 

149 return _item("examples", examples, "task") 

150 anchored = [ 

151 item.verification_hint or item.text 

152 for item in task.acceptance_criteria 

153 if item.verification_hint or _ANCHOR.search(item.text) 

154 ] 

155 return _item("examples", anchored, "derived") 

156 

157 

158def _scope_item(task: Task, scope: Any, paths: Any) -> ContractItem: 

159 if scope or paths: 

160 return _item("scope", [*(scope or []), *(paths or [])], "task") 

161 derived = [item.text for item in task.requirements] or list( 

162 task.metadata.get("ownedPaths") or [] 

163 ) 

164 return _item("scope", derived, "derived") 

165 

166 

167def _out_of_scope_item(task: Task, out_of_scope: Any) -> ContractItem: 

168 if out_of_scope: 168 ↛ 169line 168 didn't jump to line 169 because the condition on line 168 was never true

169 return _item("outOfScope", out_of_scope, "task") 

170 derived_out = [ 

171 item.removeprefix("Out of scope: ") 

172 for item in task.constraints 

173 if item.startswith("Out of scope: ") 

174 ] 

175 # Saying nothing about what is out of scope is a choice, not a gap. 

176 return ContractItem("outOfScope", derived_out, "derived", QUESTIONS["outOfScope"]) 

177 

178 

179def _setting_item(name: str, value: Any, defaults: dict[str, Any]) -> ContractItem: 

180 if value is not None: 

181 return _item(name, value, "task") 

182 if defaults.get(name) is not None: 

183 return _item(name, defaults[name], "project") 

184 return _item(name, None, "missing") 

185 

186 

187def derive_contract(task: Task, task_digest: str, defaults: dict[str, Any]) -> ContractSummary: 

188 """The contract summary of ``task``: its declaration first, then the task, then the 

189 project ``defaults`` (``branch``, ``push``, ``createPullRequest``, ``comment``, 

190 ``coverageThreshold``, ``verificationLevel``).""" 

191 declared = task.contract 

192 objective = _declared_value(declared, "objective") 

193 done = _declared_value(declared, "definition_of_done") 

194 items = [ 

195 _item("objective", objective, "task") 

196 if objective 

197 else _item("objective", task.intent, "derived"), 

198 _examples_item(task, _declared_value(declared, "examples")), 

199 _scope_item( 

200 task, _declared_value(declared, "scope"), _declared_value(declared, "scope_paths") 

201 ), 

202 _out_of_scope_item(task, _declared_value(declared, "out_of_scope")), 

203 _item("definitionOfDone", done, "task") 

204 if done 

205 else _item("definitionOfDone", [item.text for item in task.acceptance_criteria], "derived"), 

206 ] 

207 items.extend( 

208 _setting_item(name, _declared_value(declared, attribute), defaults) 

209 for name, attribute in _SETTINGS 

210 ) 

211 assumptions = task.metadata.get("assumptions") 

212 recorded = tuple(item for item in assumptions or () if isinstance(item, dict)) 

213 return ContractSummary(task_digest, tuple(items), recorded) 

214 

215 

216__all__ = ["CONTRACT_FIELDS", "QUESTIONS", "ContractItem", "ContractSummary", "derive_contract"]