Coverage for src/governed_harness/application/friction.py: 79%
119 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"""Low friction for small changes (#58) in the application layer: ``harness do``, the
2pre-authorised approval at the contract confirmation, batch decisions from the inbox, the
3plan-approval checkpoint (#8) and the ``friction`` summary of ``harness config validate``."""
5from __future__ import annotations
7import re
8import secrets
9from dataclasses import dataclass
10from typing import TYPE_CHECKING, Any
12from governed_harness.configuration.friction import (
13 DEFAULT_FRICTION_TARGETS,
14 FrictionConfig,
15)
16from governed_harness.domain.enums import DecisionKind, PhaseId, ResultStatus
17from governed_harness.domain.errors import ConfigurationError, NotFoundError, PolicyViolationError
18from governed_harness.domain.models import (
19 AcceptanceCriterion,
20 Actor,
21 ClarificationRequest,
22 Execution,
23 Task,
24)
25from governed_harness.intake import task_digest
27if TYPE_CHECKING:
28 from governed_harness.configuration.models import ProjectConfiguration
29 from governed_harness.orchestration.engine import EngineServices
31MAX_TEXT = 16000
34def _fast_lane_summary(lane: Any) -> dict[str, Any]:
35 verification = lane.verification if lane else None
36 return {
37 "mode": (lane.mode if lane else None) or "off",
38 "skip": list(lane.skipped) if lane and lane.enabled else [],
39 "affectedTestsFirst": bool(verification and verification.affected_tests_first),
40 "parallel": bool(verification and verification.parallel),
41 "cache": bool(verification and verification.cache),
42 }
45def _pre_authorization_summary(pre: Any) -> dict[str, Any]:
46 enabled = bool(pre and pre.enabled)
47 return {
48 "mode": (pre.mode if pre else None) or "off",
49 "defaultHours": pre.hours if enabled else None,
50 "maxHours": pre.limit_hours if enabled else None,
51 }
54def friction_summary(project: ProjectConfiguration) -> dict[str, Any]:
55 """The effective friction settings (absent keys resolve to the 1.0.0 behaviour)."""
56 config = project.friction or FrictionConfig()
57 return {
58 "fastLane": _fast_lane_summary(config.fast_lane),
59 "preAuthorization": _pre_authorization_summary(config.pre_authorization),
60 "changeTypes": bool(config.change_types),
61 "planApproval": config.plan_approval or "off",
62 "targets": {
63 size: target.model_dump(mode="json", by_alias=True)
64 for size, target in sorted((config.targets or {}).items())
65 }
66 or {size: dict(values) for size, values in DEFAULT_FRICTION_TARGETS.items()},
67 "targetsSource": "configured" if config.targets else "default",
68 }
71# ----- harness do ---------------------------------------------------------------------------------
72def _slug(text: str) -> str:
73 words = re.sub(r"[^a-z0-9]+", "_", text.lower()).strip("_")
74 return words[:40].strip("_") or "change"
77def task_from_text(
78 text: str,
79 *,
80 project_id: str,
81 criteria: tuple[str, ...] = (),
82 owned_paths: tuple[str, ...] = (),
83 title: str | None = None,
84 task_id: str | None = None,
85) -> Task:
86 """A task from one sentence, with sensible defaults: the text is the intent and, without
87 ``criteria``, the acceptance criterion; the title is its first line."""
88 body = text.strip()
89 if not body: 89 ↛ 90line 89 didn't jump to line 90 because the condition on line 89 was never true
90 raise ConfigurationError("harness do needs the change to make, as text")
91 if len(body) > MAX_TEXT: 91 ↛ 92line 91 didn't jump to line 92 because the condition on line 91 was never true
92 raise ConfigurationError(f"the text is longer than {MAX_TEXT} characters")
93 first = body.splitlines()[0].strip()
94 chosen_title = (title or first)[:300]
95 identifier = task_id or f"task_do_{_slug(first)}_{secrets.token_hex(3)}"
96 stated = tuple(item.strip() for item in criteria if item.strip()) or (body,)
97 metadata: dict[str, Any] = {"source": "harness do"}
98 if owned_paths: 98 ↛ 99line 98 didn't jump to line 99 because the condition on line 98 was never true
99 metadata["ownedPaths"] = list(dict.fromkeys(owned_paths))
100 return Task(
101 task_id=identifier,
102 project_id=project_id,
103 title=chosen_title,
104 intent=body,
105 acceptance_criteria=tuple(
106 AcceptanceCriterion(criterion_id=f"ac_{index}", text=item)
107 for index, item in enumerate(stated, start=1)
108 ),
109 metadata=metadata,
110 )
113def open_questions(services: EngineServices, execution: Execution) -> list[dict[str, Any]]:
114 """The questions INTENT asked about the current revision of the run's task."""
115 task = services.state.get("task", execution.task_id, Task)
116 current = task_digest(task)
117 requests = sorted(
118 (
119 item
120 for item in services.state.list(
121 "clarification_request", ClarificationRequest, execution_id=execution.execution_id
122 )
123 if item.task_digest == current
124 ),
125 key=lambda item: item.created_at,
126 )
127 if not requests:
128 return []
129 return [
130 {"questionId": item.question_id, "text": item.text, "ruleId": item.rule_id}
131 for item in requests[-1].questions
132 ]
135def preauthorize_run(
136 services: EngineServices,
137 execution: Execution,
138 actor: Actor,
139 *,
140 hours: int | None,
141 rationale: str,
142 identity_source: str | None,
143 with_contract: bool,
144) -> dict[str, Any]:
145 from governed_harness.orchestration.engine import RunEngine
147 engine = RunEngine(services)
148 record = engine.friction.preauthorize(
149 execution,
150 actor,
151 hours=hours,
152 rationale=rationale,
153 identity_source=identity_source,
154 with_contract=with_contract,
155 )
156 engine.anchor_chain(execution.execution_id)
157 return record.model_dump(mode="json", by_alias=True)
160def latest_intent_run(services: EngineServices, task_id: str) -> Execution:
161 task = services.state.get("task", task_id, Task)
162 runs = [
163 item
164 for item in services.state.list("execution", Execution, project_id=task.project_id)
165 if item.task_id == task_id and item.current_phase is PhaseId.INTENT
166 ]
167 if not runs: 167 ↛ 168line 167 didn't jump to line 168 because the condition on line 167 was never true
168 raise NotFoundError(f"task {task_id} has no run in INTENT")
169 return max(runs, key=lambda item: item.created_at)
172# ----- batch decisions ----------------------------------------------------------------------------
173@dataclass(frozen=True)
174class BatchItem:
175 """One decision of a batch: a run, the decision and the digest the person saw."""
177 run: str
178 decision: DecisionKind
179 digest: str
180 rationale: str | None = None
181 acknowledged_risks: tuple[str, ...] = ()
182 """Risk factors the person acknowledges with an APPROVE (``acknowledgeRisks``, #73)."""
185def parse_batch_item(value: str, decision: DecisionKind) -> BatchItem:
186 """``RUN=DIGEST`` of ``--approve``, ``--reject`` or ``--request-changes``."""
187 run, separator, digest = value.partition("=")
188 if not separator or not run.strip() or not digest.strip().startswith("sha256:"):
189 raise ConfigurationError(f"expected RUN=sha256:DIGEST, got {value!r}")
190 return BatchItem(run.strip(), decision, digest.strip())
193def load_batch_file(raw: Any) -> list[BatchItem]:
194 """The decisions of a batch file: a list of ``run``, ``decision``, ``changeSetDigest``, an
195 optional ``rationale`` and optional ``acknowledgeRisks`` (or the same under a top-level
196 ``decisions`` key)."""
197 if isinstance(raw, dict): 197 ↛ 198line 197 didn't jump to line 198 because the condition on line 197 was never true
198 raw = raw.get("decisions")
199 if not isinstance(raw, list) or not raw: 199 ↛ 200line 199 didn't jump to line 200 because the condition on line 199 was never true
200 raise ConfigurationError("a batch file is a non-empty list of decisions")
201 items = []
202 for index, entry in enumerate(raw, start=1):
203 if not isinstance(entry, dict): 203 ↛ 204line 203 didn't jump to line 204 because the condition on line 203 was never true
204 raise ConfigurationError(f"decision {index} must be an object")
205 try:
206 decision = DecisionKind(str(entry.get("decision", "")).upper())
207 except ValueError as error:
208 raise ConfigurationError(f"decision {index}: unknown decision") from error
209 run = str(entry.get("run") or entry.get("executionId") or "").strip()
210 digest = str(entry.get("changeSetDigest") or entry.get("digest") or "").strip()
211 if not run or not digest.startswith("sha256:"): 211 ↛ 212line 211 didn't jump to line 212 because the condition on line 211 was never true
212 raise ConfigurationError(f"decision {index} needs run and changeSetDigest")
213 rationale = entry.get("rationale")
214 items.append(
215 BatchItem(
216 run,
217 decision,
218 digest,
219 str(rationale) if rationale else None,
220 _risks(entry.get("acknowledgeRisks"), index),
221 )
222 )
223 return items
226def _risks(value: Any, index: int) -> tuple[str, ...]:
227 """The ``acknowledgeRisks`` of a batch decision: a list of risk factor names."""
228 if value is None: 228 ↛ 229line 228 didn't jump to line 229 because the condition on line 228 was never true
229 return ()
230 if not isinstance(value, list) or not all(isinstance(item, str) for item in value): 230 ↛ 231line 230 didn't jump to line 231 because the condition on line 230 was never true
231 raise ConfigurationError(f"decision {index}: acknowledgeRisks must be a list of names")
232 return tuple(value)
235def plan_state(services: EngineServices, execution_id: str) -> dict[str, Any] | None:
236 """The plan waiting at (or past) the plan-approval checkpoint of a run."""
237 from governed_harness.orchestration.engine import RunEngine
239 engine = RunEngine(services)
240 execution = engine.get_execution(execution_id)
241 state = engine.friction.plan_approval_state(execution)
242 if state is None:
243 return None
244 return {"executionId": execution_id, **state}
247def decide_plan_checkpoint(
248 services: EngineServices,
249 execution_id: str,
250 *,
251 decision: DecisionKind,
252 digest: str,
253 actor: Actor,
254 rationale: str,
255 continue_after: bool,
256) -> dict[str, Any]:
257 from governed_harness.orchestration.engine import RunEngine
259 engine = RunEngine(services)
260 execution = engine.get_execution(execution_id)
261 if execution.current_phase is not PhaseId.PLANNING: 261 ↛ 262line 261 didn't jump to line 262 because the condition on line 261 was never true
262 raise PolicyViolationError(
263 f"run {execution_id} is in {execution.current_phase.value}, not PLANNING"
264 )
265 record = engine.friction.decide_plan(
266 execution, decision=decision, digest=digest, actor=actor, rationale=rationale
267 )
268 result: dict[str, Any] = {"executionId": execution_id, "planApproval": record}
269 if continue_after and decision is DecisionKind.APPROVE:
270 result["execution"] = engine.continue_execution(execution_id).model_dump(
271 mode="json", by_alias=True
272 )
273 else:
274 engine.anchor_chain(execution_id)
275 result["execution"] = engine.get_execution(execution_id).model_dump(
276 mode="json", by_alias=True
277 )
278 return result
281def run_summary(execution: Execution) -> dict[str, Any]:
282 return {
283 "executionId": execution.execution_id,
284 "status": execution.status.value,
285 "currentPhase": execution.current_phase.value,
286 "changeSetDigest": execution.change_set_digest,
287 "awaitingDecision": execution.current_phase is PhaseId.DECISION
288 and execution.status is ResultStatus.BLOCKED,
289 }
292__all__ = [
293 "BatchItem",
294 "decide_plan_checkpoint",
295 "friction_summary",
296 "latest_intent_run",
297 "load_batch_file",
298 "open_questions",
299 "parse_batch_item",
300 "plan_state",
301 "preauthorize_run",
302 "run_summary",
303 "task_from_text",
304]