Coverage for src/governed_harness/application/notifications.py: 88%
117 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"""Pending-decision inbox and webhook notifications (``notifications.webhooks``).
3A webhook receives a JSON ``POST`` when a run starts waiting for a human decision on a new
4ChangeSet digest (``decision.pending``), when a run is closed, rejected or cancelled
5(``run.finished``) and, if asked, when an exception is granted (``exception.granted``). The
6payload carries identifiers, statuses and digests: never a rationale, a validator output, the
7webhook URL or an environment value. Delivery is best effort with bounded retries: a failure is
8recorded and never changes the run. Each outcome is kept as a ``notification`` record (outside
9the run's event chain, so a notification after closure does not extend a closed chain)."""
11from __future__ import annotations
13import json
14import os
15import time
16import urllib.error
17import urllib.request
18from datetime import datetime
19from typing import Any
21from governed_harness import __version__
22from governed_harness.configuration.models import WebhookConfig
23from governed_harness.domain.enums import DecisionKind, PhaseId, ResultStatus
24from governed_harness.domain.ids import new_id
25from governed_harness.domain.models import (
26 ClarificationRequest,
27 Execution,
28 Finding,
29 GateEvaluation,
30 HumanDecision,
31 Task,
32 utc_now,
33)
34from governed_harness.intake import task_digest
35from governed_harness.orchestration.engine import EngineServices
37from .waits import risk_acknowledgements
39RETRY_BASE_SECONDS = 0.5
40RETRY_MAX_SECONDS = 5.0
41_ERROR_CHARS = 200
44def awaiting_decision(execution: Execution) -> bool:
45 return execution.current_phase is PhaseId.DECISION and execution.status is ResultStatus.BLOCKED
48def finished(services: EngineServices, execution: Execution) -> bool:
49 if execution.status in {ResultStatus.PASSED, ResultStatus.CANCELLED}: 49 ↛ 51line 49 didn't jump to line 51 because the condition on line 49 was always true
50 return True
51 if execution.status is ResultStatus.FAILED and execution.human_decision_id:
52 decision = services.state.get("decision", execution.human_decision_id, HumanDecision)
53 return decision.decision is DecisionKind.REJECT
54 return False
57def payload(
58 services: EngineServices, execution: Execution, event: str, **extra: Any
59) -> dict[str, Any]:
60 gate = (
61 services.state.get("gate", execution.gate_evaluation_id, GateEvaluation)
62 if execution.gate_evaluation_id
63 else None
64 )
65 task = services.state.get("task", execution.task_id, Task)
66 body: dict[str, Any] = {
67 "schemaVersion": "1.0",
68 "event": event,
69 "occurredAt": utc_now().isoformat(),
70 "harnessVersion": __version__,
71 "projectId": execution.project_id,
72 "executionId": execution.execution_id,
73 "taskId": execution.task_id,
74 "taskTitle": task.title,
75 "status": execution.status.value,
76 "currentPhase": execution.current_phase.value,
77 "changeSetDigest": execution.change_set_digest,
78 "gateStatus": gate.status.value if gate else None,
79 "next": f"harness review --run {execution.execution_id}",
80 }
81 body.update(extra)
82 return body
85def _target(hook: WebhookConfig) -> str:
86 return f"env:{hook.url_env}" if hook.url_env else "url"
89def _post(url: str, body: bytes, timeout: float) -> int:
90 request = urllib.request.Request( # noqa: S310 - the scheme is checked to be http(s)
91 url,
92 data=body,
93 method="POST",
94 headers={
95 "Content-Type": "application/json",
96 "User-Agent": f"governed-agent-harness/{__version__}",
97 },
98 )
99 with urllib.request.urlopen(request, timeout=timeout) as response: # noqa: S310 # nosec B310
100 return int(response.status)
103def deliver(hook: WebhookConfig, body: dict[str, Any]) -> dict[str, Any]:
104 """POST ``body`` with retries; returns the outcome without the URL."""
105 url = hook.url if hook.url is not None else os.environ.get(hook.url_env or "", "")
106 outcome: dict[str, Any] = {"target": _target(hook), "attempts": 0}
107 if not url:
108 return {
109 **outcome,
110 "status": "FAILED",
111 "error": f"environment variable {hook.url_env} is not set",
112 }
113 if not url.startswith(("http://", "https://")): 113 ↛ 114line 113 didn't jump to line 114 because the condition on line 113 was never true
114 return {**outcome, "status": "FAILED", "error": "the webhook URL is not http(s)"}
115 data = json.dumps(body, sort_keys=True).encode("utf-8")
116 error = ""
117 for attempt in range(hook.retries + 1): 117 ↛ 133line 117 didn't jump to line 133 because the loop on line 117 didn't complete
118 outcome["attempts"] = attempt + 1
119 try:
120 status = _post(url, data, hook.timeout_seconds)
121 outcome["httpStatus"] = status
122 if 200 <= status < 300: 122 ↛ 124line 122 didn't jump to line 124 because the condition on line 122 was always true
123 return {**outcome, "status": "DELIVERED"}
124 error = f"HTTP {status}"
125 except urllib.error.HTTPError as failure:
126 outcome["httpStatus"] = failure.code
127 error = f"HTTP {failure.code}"
128 failure.close()
129 except (OSError, ValueError) as failure: # urllib.error.URLError is an OSError
130 error = type(failure).__name__
131 if attempt < hook.retries: 131 ↛ 117line 131 didn't jump to line 117 because the condition on line 131 was always true
132 time.sleep(min(RETRY_MAX_SECONDS, RETRY_BASE_SECONDS * 2**attempt))
133 return {**outcome, "status": "FAILED", "error": error[:_ERROR_CHARS]}
136def notify(
137 services: EngineServices, execution: Execution, event: str, **extra: Any
138) -> list[dict[str, Any]]:
139 hooks = [
140 (index, hook)
141 for index, hook in enumerate(services.resolved.project.webhooks)
142 if event in hook.events
143 ]
144 if not hooks:
145 return []
146 body = payload(services, execution, event, **extra)
147 outcomes = []
148 for index, hook in hooks:
149 outcome = {
150 "notificationId": new_id("notification"),
151 "executionId": execution.execution_id,
152 "event": event,
153 "webhook": index,
154 "recordedAt": utc_now().isoformat(),
155 **deliver(hook, body),
156 }
157 services.state.put(
158 "notification",
159 outcome["notificationId"],
160 outcome,
161 execution_id=execution.execution_id,
162 project_id=execution.project_id,
163 )
164 outcomes.append(outcome)
165 return outcomes
168def notify_transition(services: EngineServices, execution: Execution) -> list[dict[str, Any]]:
169 """Send ``decision.pending`` once per ChangeSet digest and ``run.finished`` once per run."""
170 if not services.resolved.project.webhooks:
171 return []
172 if awaiting_decision(execution) and execution.change_set_digest:
173 key = f"notified:decision.pending:{execution.execution_id}:{execution.change_set_digest}"
174 if services.state.get_flag(key) is None:
175 services.state.set_flag(key, utc_now().isoformat())
176 return notify(services, execution, "decision.pending")
177 elif finished(services, execution): 177 ↛ 182line 177 didn't jump to line 182 because the condition on line 177 was always true
178 key = f"notified:run.finished:{execution.execution_id}"
179 if services.state.get_flag(key) is None: 179 ↛ 182line 179 didn't jump to line 182 because the condition on line 179 was always true
180 services.state.set_flag(key, utc_now().isoformat())
181 return notify(services, execution, "run.finished")
182 return []
185def _waiting_since(execution: Execution) -> datetime:
186 return execution.updated_at
189def _decision_entry(
190 services: EngineServices, execution: Execution, blocking: set[str]
191) -> dict[str, Any]:
192 """What a run waiting in DECISION shows in the inbox: the gate, the digest, the blocking
193 findings and, since #73, the risk factors an APPROVE must acknowledge."""
194 gate = (
195 services.state.get("gate", execution.gate_evaluation_id, GateEvaluation)
196 if execution.gate_evaluation_id
197 else None
198 )
199 ids = {
200 ref.removeprefix("record://finding/")
201 for ref in (gate.input_refs if gate else ())
202 if ref.startswith("record://finding/")
203 }
204 blocking_count = sum(
205 1
206 for item in services.state.list("finding", Finding, execution_id=execution.execution_id)
207 if item.finding_id in ids and item.severity.value in blocking
208 )
209 return {
210 "kind": "decision",
211 "gateStatus": gate.status.value if gate else None,
212 "changeSetDigest": execution.change_set_digest,
213 "digest": execution.change_set_digest,
214 "blockingFindings": blocking_count,
215 "acknowledgeRisks": risk_acknowledgements(services, execution),
216 "next": f"harness review --run {execution.execution_id}",
217 }
220def inbox(services: EngineServices) -> list[dict[str, Any]]:
221 """Runs of the project that wait for a person: a decision in DECISION, or answers to
222 clarification questions in INTENT. Oldest first."""
223 project_id = services.resolved.project.project_id
224 names = services.resolved.effective_policies.get("findingBlockSeverities", ["HIGH", "CRITICAL"])
225 blocking = {str(name) for name in names}
226 entries: list[dict[str, Any]] = []
227 executions = services.state.list("execution", Execution, project_id=project_id)
228 requests = services.state.list(
229 "clarification_request", ClarificationRequest, project_id=project_id
230 )
231 now = utc_now()
232 for execution in executions:
233 task = services.state.get("task", execution.task_id, Task)
234 base = {
235 "executionId": execution.execution_id,
236 "taskId": execution.task_id,
237 "taskTitle": task.title,
238 "waitingSince": _waiting_since(execution).isoformat(),
239 "waitingHours": round((now - _waiting_since(execution)).total_seconds() / 3600, 1),
240 }
241 if awaiting_decision(execution):
242 entries.append({**base, **_decision_entry(services, execution, blocking)})
243 elif execution.current_phase is PhaseId.INTENT and execution.status is ResultStatus.BLOCKED:
244 current = task_digest(task)
245 open_requests = [
246 item
247 for item in requests
248 if item.task_id == task.task_id and item.task_digest == current
249 ]
250 if open_requests:
251 entries.append(
252 {
253 **base,
254 "kind": "clarification",
255 "questions": len(open_requests[-1].questions),
256 "next": f"harness task questions --task {task.task_id}",
257 }
258 )
259 return sorted(entries, key=lambda item: item["waitingSince"])