Coverage for src/governed_harness/application/task_loader.py: 83%

83 statements  

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

1from __future__ import annotations 

2 

3import json 

4from pathlib import Path 

5from typing import Any, Literal, cast 

6 

7import yaml 

8 

9from governed_harness.configuration.models import CriteriaPolicy 

10from governed_harness.domain.errors import ConfigurationError 

11from governed_harness.domain.ids import new_id 

12from governed_harness.domain.models import ( 

13 AcceptanceCriterion, 

14 ChecklistItem, 

15 CriterionVerification, 

16 FilePatch, 

17 ImplementationInstruction, 

18 OperationalContract, 

19 ProbeDefinition, 

20 Requirement, 

21 Task, 

22) 

23 

24 

25def _verification(item: dict[str, Any], where: str) -> CriterionVerification | None: 

26 """The ``verification`` of a criterion (since #55): its rung and how it is reached.""" 

27 raw = item.get("verification") 

28 if raw is None: 

29 return None 

30 if not isinstance(raw, dict): 30 ↛ 31line 30 didn't jump to line 31 because the condition on line 30 was never true

31 raise ConfigurationError(f"{where}: verification must be an object with a level") 

32 try: 

33 return CriterionVerification.model_validate(raw) 

34 except Exception as error: 

35 raise ConfigurationError(f"{where}: invalid verification: {error}") from error 

36 

37 

38def _ladder_fields(raw: dict[str, Any]) -> dict[str, Any]: 

39 """The probes, checklist and operational contract of a task file (since #55).""" 

40 fields: dict[str, Any] = {} 

41 try: 

42 if raw.get("probes"): 42 ↛ 43line 42 didn't jump to line 43 because the condition on line 42 was never true

43 fields["probes"] = tuple( 

44 ProbeDefinition.model_validate(item) for item in raw["probes"] or [] 

45 ) 

46 if raw.get("checklist"): 

47 fields["checklist"] = tuple( 

48 ChecklistItem.model_validate( 

49 {"id": f"CL-{index}", "text": item} if isinstance(item, str) else item 

50 ) 

51 for index, item in enumerate(raw["checklist"] or [], start=1) 

52 ) 

53 if raw.get("contract"): 

54 fields["contract"] = OperationalContract.model_validate(raw["contract"]) 

55 except Exception as error: 

56 raise ConfigurationError(f"invalid task definition: {error}") from error 

57 return fields 

58 

59 

60_KNOWN_FIELDS = frozenset( 

61 { 

62 "taskId", 

63 "task_id", 

64 "projectId", 

65 "project_id", 

66 "title", 

67 "intent", 

68 "constraints", 

69 "requirements", 

70 "acceptanceCriteria", 

71 "acceptance_criteria", 

72 "implementation", 

73 "metadata", 

74 "probes", 

75 "checklist", 

76 "contract", 

77 } 

78) 

79 

80 

81def _first(value: dict[str, Any], *names: str, default: Any = None) -> Any: 

82 for name in names: 

83 if name in value: 

84 return value[name] 

85 return default 

86 

87 

88def _required_text(value: dict[str, Any], name: str, where: str) -> str: 

89 """A required text field: missing, null or blank values are rejected instead of being 

90 stored as the text 'None'.""" 

91 text = value.get(name) 

92 if text is None or not str(text).strip(): 

93 raise ConfigurationError(f"{where} requires a non-empty {name!r}") 

94 return str(text) 

95 

96 

97def _parse_task_file(path: Path) -> Any: 

98 try: 

99 if path.suffix.lower() == ".json": 99 ↛ 100line 99 didn't jump to line 100 because the condition on line 99 was never true

100 return json.loads(path.read_text(encoding="utf-8")) 

101 return yaml.safe_load(path.read_text(encoding="utf-8")) 

102 except Exception as error: 

103 raise ConfigurationError(f"cannot parse task file {path}: {error}") from error 

104 

105 

106def _requirement(item: Any) -> Requirement: 

107 if isinstance(item, str): 

108 return Requirement(requirement_id=new_id("req"), text=item, source="human") 

109 if isinstance(item, dict): 109 ↛ 117line 109 didn't jump to line 117 because the condition on line 109 was always true

110 return Requirement( 

111 requirement_id=_first( 

112 item, "requirementId", "requirement_id", "id", default=new_id("req") 

113 ), 

114 text=_required_text(item, "text", "a requirement"), 

115 source=str(_first(item, "source", default="human")), 

116 ) 

117 raise ConfigurationError("requirements must be strings or objects") 

118 

119 

120def _criterion(item: Any) -> AcceptanceCriterion: 

121 if isinstance(item, str): 

122 return AcceptanceCriterion(criterion_id=new_id("ac"), text=item) 

123 if isinstance(item, dict): 123 ↛ 134line 123 didn't jump to line 134 because the condition on line 123 was always true

124 return AcceptanceCriterion( 

125 criterion_id=_first(item, "criterionId", "criterion_id", "id", default=new_id("ac")), 

126 text=_required_text(item, "text", "an acceptance criterion"), 

127 verification_hint=_first(item, "verificationHint", "verification_hint"), 

128 priority=cast( 

129 Literal["MUST", "SHOULD", "COULD"], 

130 str(_first(item, "priority", default="MUST")).upper(), 

131 ), 

132 verification=_verification(item, "an acceptance criterion"), 

133 ) 

134 raise ConfigurationError("acceptance criteria must be strings or objects") 

135 

136 

137def _implementation(raw: dict[str, Any]) -> ImplementationInstruction: 

138 implementation_raw = _first(raw, "implementation", default={}) or {} 

139 patches = [ 

140 FilePatch( 

141 path=str(_first(patch, "path")), 

142 operation=cast( 

143 Literal["create", "replace", "append", "delete"], 

144 str(_first(patch, "operation")), 

145 ), 

146 content=_first(patch, "content"), 

147 expected_sha256=_first(patch, "expectedSha256", "expected_sha256"), 

148 ) 

149 for patch in _first(implementation_raw, "patches", default=[]) or [] 

150 ] 

151 return ImplementationInstruction( 

152 mode=cast( 

153 Literal["none", "patch", "command"], 

154 str(_first(implementation_raw, "mode", default="none")), 

155 ), 

156 patches=tuple(patches), 

157 argv=tuple(str(item) for item in (_first(implementation_raw, "argv", default=[]) or [])), 

158 cwd=str(_first(implementation_raw, "cwd", default=".")), 

159 ) 

160 

161 

162def load_task_file( 

163 path: Path, *, project_id: str, criteria_policy: CriteriaPolicy | None = None 

164) -> Task: 

165 """Read a task file (YAML or JSON) into a task. 

166 

167 A task needs at least one acceptance criterion. Only when ``criteria_policy`` is 

168 ``enforce`` is a task without criteria accepted: it is marked ``criteria_pending`` and 

169 INTENT asks for its criteria (rule ``C0``). Any other policy, or none, keeps the refusal.""" 

170 raw = _parse_task_file(path) 

171 if not isinstance(raw, dict): 171 ↛ 172line 171 didn't jump to line 172 because the condition on line 171 was never true

172 raise ConfigurationError("task file must contain an object") 

173 unknown = sorted(set(raw) - _KNOWN_FIELDS) 

174 if unknown: 

175 raise ConfigurationError(f"unknown task field(s): {', '.join(unknown)}") 

176 title = _required_text(raw, "title", "a task") 

177 intent = _required_text(raw, "intent", "a task") 

178 requirements = [_requirement(item) for item in _first(raw, "requirements", default=[]) or []] 

179 criteria = [ 

180 _criterion(item) 

181 for item in _first(raw, "acceptanceCriteria", "acceptance_criteria", default=[]) or [] 

182 ] 

183 implementation = _implementation(raw) 

184 try: 

185 return Task( 

186 task_id=str(_first(raw, "taskId", "task_id", default=new_id("task"))), 

187 project_id=str(_first(raw, "projectId", "project_id", default=project_id)), 

188 title=title, 

189 intent=intent, 

190 constraints=tuple(str(item) for item in (_first(raw, "constraints", default=[]) or [])), 

191 requirements=tuple(requirements), 

192 criteria_pending=not criteria and criteria_policy == "enforce", 

193 acceptance_criteria=tuple(criteria), 

194 implementation=implementation, 

195 metadata=dict(_first(raw, "metadata", default={}) or {}), 

196 **_ladder_fields(raw), 

197 ) 

198 except ConfigurationError: 

199 raise 

200 except Exception as error: 

201 raise ConfigurationError(f"invalid task definition: {error}") from error