Coverage for src/governed_harness/application/waits.py: 93%
123 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"""The waits for a person before DECISION, as inbox entries (#73).
3A run that stops before DECISION to wait for a person exits 6, and before #73 the inbox listed
4only the clarification questions, the deferred verifications and the preflight among them: a plan
5waiting at the plan-approval checkpoint, a proposed decomposition, proposed acceptance tests, the
6architecture options or inferred layer rules and an operational contract to confirm were missing.
7Each of them is an entry here with its kind, the digest the answer binds to and the command that
8answers it. The entries read what the run recorded; nothing is evaluated or changed."""
10from __future__ import annotations
12import json
13from collections.abc import Callable
14from datetime import datetime
15from typing import TYPE_CHECKING, Any
17from governed_harness.domain.enums import PhaseId, ResultStatus
18from governed_harness.domain.models import Execution, Task, utc_now
19from governed_harness.intake import task_digest
20from governed_harness.orchestration.acceptance_dispute import (
21 DISPUTE_FLAG,
22 DISPUTE_KIND,
23 decide_command,
24)
25from governed_harness.orchestration.architecture import conflicts_summary
26from governed_harness.orchestration.architecture import read_state as architecture_state
27from governed_harness.orchestration.friction import PLAN_APPROVAL_FLAG
28from governed_harness.orchestration.verification_checks import RISK_ACK_FLAG
30if TYPE_CHECKING:
31 from governed_harness.orchestration.engine import EngineServices
33DECOMPOSITION_FLAG = "decomposition"
34ACCEPTANCE_FLAG = "acceptance"
35RATIONALE = '--rationale "..."'
37Wait = Callable[["EngineServices", Execution, Task], dict[str, Any] | None]
40def _flag(services: EngineServices, key: str) -> dict[str, Any] | None:
41 raw = services.state.get_flag(key)
42 if not raw:
43 return None
44 value = json.loads(raw)
45 return value if isinstance(value, dict) else None
48def _decide(command: str, run: str, digest: str, choice: str = "--decision APPROVE") -> str:
49 return f"harness {command} decide --run {run} {choice} --digest {digest} {RATIONALE}"
52def _plan(services: EngineServices, execution: Execution, task: Task) -> dict[str, Any] | None:
53 """The plan-approval checkpoint (``friction.planApproval``) waits for a person."""
54 if execution.current_phase is not PhaseId.PLANNING:
55 return None
56 state = _flag(services, f"{PLAN_APPROVAL_FLAG}:{execution.execution_id}")
57 if not state or state.get("status") != "PENDING":
58 return None
59 digest = str(state.get("digest"))
60 return {
61 "kind": "plan",
62 "digest": digest,
63 "summary": "plan approval: " + "; ".join(str(item) for item in state.get("reasons") or []),
64 "next": _decide("plan", execution.execution_id, digest),
65 }
68def _decomposition(
69 services: EngineServices, execution: Execution, task: Task
70) -> dict[str, Any] | None:
71 """A decomposition PLANNING proposed (``planning.decomposition``) waits for a person."""
72 if execution.current_phase is not PhaseId.PLANNING:
73 return None
74 state = _flag(services, f"{DECOMPOSITION_FLAG}:{execution.execution_id}")
75 if not state or state.get("status") != "PROPOSED":
76 return None
77 if state.get("taskDigest") != task_digest(task): 77 ↛ 78line 77 didn't jump to line 78 because the condition on line 77 was never true
78 return None
79 digest = str(state.get("digest"))
80 return {
81 "kind": "decomposition",
82 "digest": digest,
83 "summary": f"{len(state.get('subtasks') or [])} sub-task(s) proposed",
84 "next": _decide("plan", execution.execution_id, digest),
85 }
88def _acceptance(
89 services: EngineServices, execution: Execution, task: Task
90) -> dict[str, Any] | None:
91 """Acceptance tests SPECIFICATION proposed (``verification.acceptanceTests``) wait."""
92 if execution.current_phase is not PhaseId.SPECIFICATION:
93 return None
94 state = _flag(services, f"{ACCEPTANCE_FLAG}:{execution.execution_id}")
95 if not state or state.get("status") != "PROPOSED": 95 ↛ 96line 95 didn't jump to line 96 because the condition on line 95 was never true
96 return None
97 digest = str(state.get("digest"))
98 return {
99 "kind": "acceptance",
100 "digest": digest,
101 "summary": f"{len(state.get('tests') or [])} acceptance test file(s) proposed",
102 "next": _decide("acceptance", execution.execution_id, digest),
103 }
106def _acceptance_dispute(
107 services: EngineServices, execution: Execution, task: Task
108) -> dict[str, Any] | None:
109 """Frozen acceptance tests the agent disputes, the only thing that failed in VERIFICATION
110 (``verification.acceptanceTests.disputes``, #94), wait for a person."""
111 if execution.current_phase is not PhaseId.VERIFICATION:
112 return None
113 state = _flag(services, f"{DISPUTE_FLAG}:{execution.execution_id}")
114 if not state or state.get("status") != "OPEN": 114 ↛ 115line 114 didn't jump to line 115 because the condition on line 114 was never true
115 return None
116 if state.get("changeSetDigest") != execution.change_set_digest: 116 ↛ 117line 116 didn't jump to line 117 because the condition on line 116 was never true
117 return None
118 digest = str(state.get("digest"))
119 disputed = state.get("disputed") or []
120 shown = "; ".join(f"{item['test']}: {item['reason']}" for item in disputed[:5])
121 return {
122 "kind": DISPUTE_KIND,
123 "digest": digest,
124 "summary": f"{len(disputed)} frozen acceptance test(s) disputed by the agent ({shown})",
125 "disputed": disputed,
126 "next": f"{decide_command(execution.execution_id, digest)} {RATIONALE}",
127 }
130def _recommended_hint(state: dict[str, Any]) -> str:
131 """The recommended option of a catalogue proposal (its options carry ``supports``)."""
132 marked = [
133 str(item.get("id"))
134 for item in state.get("options") or []
135 if item.get("recommended") and "supports" in item
136 ]
137 return f" (recommended: {marked[0]})" if marked else ""
140def _architecture(
141 services: EngineServices, execution: Execution, task: Task
142) -> dict[str, Any] | None:
143 """Architecture options (a new project, INTENT) or inferred layer rules (an existing
144 project, DISCOVERY) wait for a person."""
145 state = architecture_state(services.paths.harness_dir)
146 if not state:
147 return None
148 status = state.get("status")
149 digest = str(state.get("digest"))
150 run = execution.execution_id
151 if status == "OPTIONS" and execution.current_phase is PhaseId.INTENT:
152 options = [str(item.get("id")) for item in state.get("options") or []]
153 hint = _recommended_hint(state)
154 return {
155 "kind": "architecture",
156 "digest": digest,
157 "summary": f"{len(options)} architecture option(s): {', '.join(options)}{hint}",
158 "next": _decide("architecture", run, digest, "--option <id>"),
159 }
160 if status == "PROPOSED" and execution.current_phase is PhaseId.DISCOVERY: 160 ↛ 173line 160 didn't jump to line 173 because the condition on line 160 was always true
161 layers = (state.get("rules") or {}).get("layers") or []
162 conflicts = conflicts_summary(state)
163 entry = {
164 "kind": "architecture",
165 "digest": digest,
166 "summary": f"{len(layers)} inferred layer rule(s) to approve"
167 + (f"; {conflicts}" if conflicts else ""),
168 "next": _decide("architecture", run, digest),
169 }
170 if conflicts:
171 entry["baselineConflicts"] = state["baselineConflicts"]
172 return entry
173 return None
176def _contract(services: EngineServices, execution: Execution, task: Task) -> dict[str, Any] | None:
177 """An operational contract waits for its confirmation (``intake.operationalContract:
178 enforce``); a contract with items not settled waits for answers (a clarification) instead."""
179 intake = services.resolved.project.intake
180 if execution.current_phase is not PhaseId.INTENT or not intake:
181 return None
182 if intake.operational_contract != "enforce":
183 return None
184 current = _flag(services, f"contractcurrent:{execution.execution_id}")
185 if not current or current.get("taskDigest") != task_digest(task): 185 ↛ 186line 185 didn't jump to line 186 because the condition on line 185 was never true
186 return None
187 digest = str(current.get("digest"))
188 confirmed = _flag(services, f"contractconfirmed:{execution.execution_id}")
189 if confirmed and confirmed.get("digest") == digest:
190 return None
191 summary = json.loads(services.artifacts.get(str(current["ref"])))
192 if summary.get("missing"):
193 return None
194 return {
195 "kind": "contract",
196 "digest": digest,
197 "summary": "operational contract to confirm",
198 "next": f"harness task confirm --task {task.task_id} --digest {digest}",
199 }
202WAITS: tuple[Wait, ...] = (
203 _contract,
204 _architecture,
205 _acceptance,
206 _decomposition,
207 _plan,
208 _acceptance_dispute,
209)
212def _base(execution: Execution, task: Task, now: datetime) -> dict[str, Any]:
213 return {
214 "executionId": execution.execution_id,
215 "taskId": execution.task_id,
216 "taskTitle": task.title,
217 "waitingSince": execution.updated_at.isoformat(),
218 "waitingHours": round((now - execution.updated_at).total_seconds() / 3600, 1),
219 }
222def waiting_entries(services: EngineServices) -> list[dict[str, Any]]:
223 """The runs of the project blocked before DECISION on a wait for a person, one entry per
224 wait (kind, digest, summary and the command that answers it)."""
225 project_id = services.resolved.project.project_id
226 now = utc_now()
227 entries: list[dict[str, Any]] = []
228 for execution in services.state.list("execution", Execution, project_id=project_id):
229 if execution.status is not ResultStatus.BLOCKED:
230 continue
231 task = services.state.get("task", execution.task_id, Task)
232 for wait in WAITS:
233 entry = wait(services, execution, task)
234 if entry is not None:
235 entries.append({**_base(execution, task, now), **entry})
236 return entries
239def risk_acknowledgements(services: EngineServices, execution: Execution) -> list[str]:
240 """The risk factors of the run's ChangeSet a decision must acknowledge
241 (``verification.riskFactors`` with ``acknowledge``)."""
242 raw = services.state.get_flag(
243 f"{RISK_ACK_FLAG}:{execution.execution_id}:{execution.change_set_digest}"
244 )
245 value = json.loads(raw) if raw else None
246 return [str(item) for item in value] if isinstance(value, list) else []
249__all__ = ["risk_acknowledgements", "waiting_entries"]