Coverage for src/governed_harness/orchestration/hosts.py: 0%
3 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"""What the engine's helpers need from the objects that own them (#69).
3The helpers of :class:`~governed_harness.orchestration.engine.RunEngine` (the agent results, the
4friction settings, the verification ladder, the exit gates, provenance) and the helpers of
5:class:`~governed_harness.orchestration.agent_results.AgentResults` (one per agent-results
6setting) type their owner against these protocols instead of importing it, so that the owner
7imports them without a module cycle. A helper that reaches a sibling through its owner (the
8engineering settings from the acceptance tests, the ladder from the friction settings) types the
9sibling against a port here for the same reason.
11Every member is one a helper uses, with the owner's signature; the underscore members are engine
12internals the helpers called before the split. The owners satisfy the protocols structurally,
13which mypy checks where they pass ``self`` to a helper."""
15from __future__ import annotations
17from typing import TYPE_CHECKING, Any, Protocol
19if TYPE_CHECKING:
20 from collections.abc import Callable
21 from datetime import datetime
22 from pathlib import Path
24 from governed_harness.agents import AgentCallResult, AgentExecutionResult, AgentProvider
25 from governed_harness.agents.requests import CallKind
26 from governed_harness.agents.routing import TaskSignals
27 from governed_harness.checks.layers import LayerRules
28 from governed_harness.checks.model import DiffFile, Issue
29 from governed_harness.configuration.models import ProjectConfiguration, ValidatorDefinition
30 from governed_harness.domain.enums import (
31 EvidenceKind,
32 FindingSeverity,
33 PhaseId,
34 ResultStatus,
35 ValidationKind,
36 )
37 from governed_harness.domain.models import (
38 Actor,
39 ChangeSet,
40 ClarificationQuestion,
41 Evidence,
42 Execution,
43 FeedbackDecision,
44 FeedbackGate,
45 FeedbackTrigger,
46 Finding,
47 HumanDecision,
48 PhaseExecution,
49 Provenance,
50 Task,
51 ToolInvocation,
52 ValidationResult,
53 )
54 from governed_harness.gates import GateEngine
55 from governed_harness.orchestration.agent_contract_types import CallLimits
56 from governed_harness.orchestration.engine_types import (
57 AgentCallOutcome,
58 EngineServices,
59 PhaseOutcome,
60 ReviewOutcome,
61 Strategy,
62 )
63 from governed_harness.orchestration.state_machine import NormativeStateMachine
64 from governed_harness.orchestration.workspace_ops import Contents
65 from governed_harness.runtime import SafeProcessRunner, WorkspaceSnapshot
66 from governed_harness.runtime.sandbox import SandboxHost, SandboxPlan
67 from governed_harness.runtime.snapshots import SnapshotStore
68 from governed_harness.runtime.workspace import WorkspaceDiff
69 from governed_harness.validators import ValidatorOutput, ValidatorRegistry
72class EngineHost(Protocol):
73 """The :class:`RunEngine` as its helpers use it."""
75 @property
76 def friction(self) -> FrictionPort:
77 """The friction settings of the run (#58)."""
79 @property
80 def gate_engine(self) -> GateEngine:
81 """The gate evaluation of DECISION."""
83 @property
84 def ladder(self) -> LadderPort:
85 """The verification ladder (#55)."""
87 @property
88 def provenance(self) -> ProvenancePort:
89 """The provenance recorder of the ChangeSet's files."""
91 @property
92 def results(self) -> ResultsHost:
93 """The agent-results settings of the run."""
95 @property
96 def s(self) -> EngineServices:
97 """The project's configuration, paths and stores."""
99 @property
100 def sandbox_host(self) -> SandboxHost:
101 """The host the agent sandbox is built for."""
103 @property
104 def snapshots(self) -> SnapshotStore:
105 """The workspace snapshots of the run."""
107 @property
108 def state_machine(self) -> NormativeStateMachine:
109 """The normative phase transitions."""
111 @property
112 def validators(self) -> ValidatorRegistry:
113 """The validators available to VERIFICATION."""
115 def baseline_digests(self, execution: Execution) -> dict[str, str]:
116 """Path to digest of the run's baseline snapshot."""
118 def current_change_set(self, execution_id: str) -> ChangeSet:
119 """The run's current ChangeSet."""
121 def get_execution(self, execution_id: str) -> Execution:
122 """The stored run."""
124 def is_cancelled(self, execution_id: str) -> bool:
125 """Whether the run was cancelled."""
127 def run_task(self, execution: Execution) -> Task:
128 """The task revision the run works on."""
130 def _agent_network_allowed(self) -> bool:
131 """Whether the agent sandbox allows outbound network."""
133 def _bounded_definition(self, definition: ValidatorDefinition) -> ValidatorDefinition:
134 """The validator definition within the phase's time budget."""
136 def _bounded_timeout(self, seconds: int) -> int:
137 """A timeout within the phase's time budget."""
139 def _build_provider(
140 self, execution: Execution, phase: PhaseExecution, provider_id: str
141 ) -> tuple[AgentProvider, Actor, SandboxPlan | None, tuple[str, ...]] | PhaseOutcome:
142 """The provider of a run, or the outcome when it cannot start."""
144 def _compute_owned_diff(self, execution: Execution) -> WorkspaceDiff:
145 """The task-owned diff, without persisting unredacted content."""
147 def _current_contract_digest(self, execution: Execution) -> str | None:
148 """The digest of the frozen acceptance contract."""
150 def _external_provider(self, execution_id: str) -> bool:
151 """Whether the run uses a configured command provider."""
153 def _feedback_applies(self, execution_id: str) -> bool:
154 """Whether provider feedback applies to the run."""
156 def _latest_validations(self, execution_id: str, digest: str) -> list[ValidationResult]:
157 """The latest validation of each validator for a digest."""
159 def _protected_paths(self, execution: Execution | None = None) -> tuple[Path, ...]:
160 """Paths the agent sandbox keeps read-only."""
162 def _provenance(self, execution: Execution) -> Provenance:
163 """The provenance of the run's records."""
165 def _record_evidence(
166 self,
167 execution: Execution,
168 phase_id: PhaseId,
169 kind: EvidenceKind,
170 artifact_ref: Any,
171 summary: str,
172 *,
173 supports: tuple[str, ...] = ...,
174 ) -> Evidence:
175 """Record an artifact as evidence of a phase."""
177 def _record_feedback(
178 self,
179 execution: Execution,
180 phase_id: PhaseId,
181 *,
182 trigger: FeedbackTrigger,
183 change_set_digest: str,
184 gate: FeedbackGate,
185 validations: list[ValidationResult],
186 findings: list[Finding],
187 decision: FeedbackDecision | None = ...,
188 ) -> str:
189 """Store the feedback for the next IMPLEMENTATION attempt."""
191 def _record_provider_retry(
192 self,
193 execution: Execution,
194 phase: PhaseExecution,
195 result: AgentExecutionResult,
196 cause: str,
197 retry: int,
198 ) -> None:
199 """Record a retry of a transient provider failure."""
201 def _runner(self, execution: Execution) -> SafeProcessRunner:
202 """The process runner of the run."""
204 def _save_agent_result(
205 self, execution: Execution, phase: PhaseExecution, result: AgentExecutionResult
206 ) -> None:
207 """Record what an agent call did."""
209 def _save_execution(self, execution: Execution) -> None:
210 """Store the run."""
212 def _save_tool(self, execution: Execution, tool: ToolInvocation) -> None:
213 """Record a tool invocation."""
215 def _save_validator_output(self, execution: Execution, output: Any) -> None:
216 """Record a validator's result and findings."""
218 def _transient_cause(self, result: AgentExecutionResult) -> str | None:
219 """The pattern that marks a failed provider call as transient."""
221 def _wait_for_retry(self, execution_id: str, delay: float) -> bool:
222 """Wait before a retry; ``False`` when the run is cancelled."""
224 @staticmethod
225 def _snapshot_from_dict(value: dict[str, Any]) -> WorkspaceSnapshot:
226 """A workspace snapshot from its stored form."""
228 @staticmethod
229 def _snapshot_to_dict(snapshot: WorkspaceSnapshot) -> dict[str, Any]:
230 """The stored form of a workspace snapshot."""
233class ResultsHost(Protocol):
234 """The :class:`AgentResults` as its helpers use it."""
236 @property
237 def acceptance(self) -> AcceptancePort:
238 """The acceptance tests (``verification.acceptanceTests``)."""
240 @property
241 def active(self) -> bool:
242 """Whether any agent-results setting is configured."""
244 @property
245 def agent_contract(self) -> AgentContractPort:
246 """The agent contract (#97)."""
248 @property
249 def agent_review(self) -> AgentReviewPort:
250 """The single independent reviewer."""
252 @property
253 def architecture(self) -> ArchitecturePort:
254 """The architecture flow (#56)."""
256 @property
257 def corrections(self) -> CorrectionsPort:
258 """The reproduce-first corrections."""
260 @property
261 def engine(self) -> EngineHost:
262 """The engine that owns these settings."""
264 @property
265 def engineering(self) -> EngineeringPort:
266 """The standards, principles and testing strategy (#56)."""
268 @property
269 def panel(self) -> PanelPort:
270 """The review panel (#57)."""
272 @property
273 def project(self) -> ProjectConfiguration:
274 """The project configuration."""
276 @property
277 def project_setup(self) -> ProjectSetupPort:
278 """The project setup questions (#56)."""
280 @property
281 def s(self) -> EngineServices:
282 """The project's configuration, paths and stores."""
284 @property
285 def secrets_in_context(self) -> bool:
286 """Whether secrets may reach an agent's context."""
288 @property
289 def stop_line(self) -> StopLinePort:
290 """The stop-the-line checks."""
292 @property
293 def verification(self) -> VerificationPort:
294 """The verification checks."""
296 def after_agent_call(
297 self, execution: Execution, phase: PhaseExecution, result: AgentExecutionResult
298 ) -> None:
299 """Account for a finished agent call."""
301 def baseline_changes(self, execution: Execution) -> WorkspaceDiff | None:
302 """Every change since DISCOVERY, with a unified diff."""
304 def baseline_contents(self, execution: Execution) -> Contents | None:
305 """The recorded bytes of the baseline's files."""
307 def baseline_snapshot(self, execution: Execution) -> WorkspaceSnapshot | None:
308 """The workspace as DISCOVERY recorded it."""
310 def baseline_text(self, execution: Execution) -> Callable[[str], str | None]:
311 """The baseline text of a path, when it had one."""
313 def before_agent_call(
314 self, execution: Execution, phase: PhaseExecution, kind: CallKind
315 ) -> PhaseOutcome | None:
316 """Fail closed before an agent call when a limit is crossed."""
318 def call_agent(
319 self,
320 execution: Execution,
321 phase: PhaseExecution,
322 kind: CallKind,
323 payload: dict[str, Any],
324 *,
325 task: Task,
326 instruction_values: dict[str, Any] | None = ...,
327 instructions_suffix: str = ...,
328 validate: Callable[[dict[str, Any]], object] | None = ...,
329 ) -> AgentCallOutcome:
330 """Send a read-only request and return its structured result (retried once when the
331 answer breaks its contract, under ``runtime.contractRetry``)."""
333 def change_requests(self, execution: Execution) -> list[dict[str, Any]]:
334 """The structured change requests of the run."""
336 def flag_json(self, key: str) -> Any:
337 """A JSON flag of the state store."""
339 def implement_model(self, execution: Execution, task: Task) -> str | None:
340 """The model an implement call would use."""
342 def provider_for(self, execution: Execution, kind: CallKind) -> str:
343 """The provider of a call kind."""
345 def record_finding(
346 self,
347 execution: Execution,
348 *,
349 validator_id: str,
350 rule_id: str,
351 category: str,
352 severity: FindingSeverity,
353 message: str,
354 path: str | None = ...,
355 line: int | None = ...,
356 evidence_refs: tuple[str, ...] = ...,
357 recommendation: str | None = ...,
358 introduced: bool | None = ...,
359 actor: Actor | None = ...,
360 ) -> Finding:
361 """Record a finding of the run."""
363 def record_json(
364 self,
365 execution: Execution,
366 phase_id: PhaseId,
367 value: Any,
368 *,
369 kind: str,
370 summary: str,
371 evidence_kind: EvidenceKind = ...,
372 supports: tuple[str, ...] = ...,
373 ) -> str:
374 """Store a JSON artifact as evidence of a phase."""
376 def record_validation(
377 self,
378 execution: Execution,
379 *,
380 validator_id: str,
381 digest: str,
382 status: ResultStatus,
383 kind: ValidationKind,
384 mandatory: bool,
385 summary: str,
386 findings: tuple[Finding, ...] = ...,
387 evidence_refs: tuple[str, ...],
388 started_at: Any = ...,
389 ) -> ValidationResult:
390 """Record a validation of a ChangeSet digest."""
392 def required_acknowledgements(self, execution: Execution, digest: str) -> list[str]:
393 """The risk factors a decision must acknowledge."""
395 def set_flag_json(self, key: str, value: Any) -> None:
396 """Store a JSON flag."""
398 def task_signals(self, execution: Execution, task: Task) -> TaskSignals:
399 """Size signals of the task known before the call."""
402class AcceptancePort(Protocol):
403 """The acceptance tests (``verification.acceptanceTests``) as siblings use them."""
405 def state(self, execution: Execution) -> dict[str, Any] | None:
406 """The acceptance tests' state of the run."""
408 def validation(self, execution: Execution, change_set: ChangeSet) -> ValidatorOutput | None:
409 """The acceptance tests as a validation of the ChangeSet."""
411 def untouched(self, execution: Execution) -> set[str]:
412 """The frozen files still as approved (the harness's, not the agent's edits)."""
415class AgentContractPort(Protocol):
416 """The agent contract as the review panel uses it (#149)."""
418 @property
419 def enabled(self) -> bool:
420 """Whether ``agentContract`` is set to ``enforce``."""
422 def limits(self, execution: Execution, task: Task, kind: str | None = ...) -> CallLimits:
423 """The token budget and the time limit of a call for the task's size."""
425 def timeout(self, default: int, limits: CallLimits) -> int:
426 """The time a process may run under the limits."""
428 def settle_reviewer(
429 self,
430 execution: Execution,
431 phase: PhaseExecution,
432 reviewer: str,
433 answer: AgentCallResult,
434 *,
435 request: dict[str, Any],
436 request_ref: str | None,
437 limits: CallLimits,
438 ) -> str | None:
439 """Judge and record one reviewer answer; the reason to discard it, else ``None``."""
442class AgentReviewPort(Protocol):
443 """The single independent reviewer as the review panel uses it."""
445 def blocking_severities(self) -> set[FindingSeverity]:
446 """The finding severities that block."""
449class ArchitecturePort(Protocol):
450 """The architecture flow as siblings use it."""
452 def request_extra(self) -> dict[str, Any] | None:
453 """What the architecture adds to an agent request."""
455 def rules(self) -> LayerRules | None:
456 """The layer rules of the project."""
459class CorrectionsPort(Protocol):
460 """The reproduce-first corrections as the verification checks use them."""
462 def validation(self, execution: Execution, change_set: ChangeSet) -> ValidatorOutput | None:
463 """The latest correction attempt as a validation."""
466class EngineeringPort(Protocol):
467 """The engineering settings (standards, testing, TDD) as siblings use them."""
469 @property
470 def configured(self) -> bool:
471 """Whether any engineering setting is configured."""
473 def bdd_command(self) -> tuple[str, ...]:
474 """The command that runs the feature files."""
476 def features_directory(self) -> str:
477 """Where the feature files live."""
479 def review_extra(self, change_set: ChangeSet) -> tuple[dict[str, Any], str]:
480 """The checklist the review call gains."""
482 def setup_record(self, project_id: str) -> dict[str, Any]:
483 """The project setup answers."""
485 def strategy(self, project_id: str) -> Strategy:
486 """The effective testing strategy."""
488 def tdd_validation(
489 self,
490 execution: Execution,
491 change_set: ChangeSet,
492 diff: list[DiffFile],
493 outputs_so_far: list[ValidatorOutput],
494 ) -> ValidatorOutput | None:
495 """The TDD check as a validation of the ChangeSet."""
497 def technologies(self) -> tuple[str, ...]:
498 """The technologies of the project."""
501class FrictionPort(Protocol):
502 """The friction settings as the engine's helpers use them."""
504 @property
505 def active(self) -> bool:
506 """Whether a friction setting that acts on a run is configured."""
508 def skips(self, execution: Execution, step: str, phase_id: PhaseId | None = ...) -> bool:
509 """Whether the fast lane leaves a step out of the run."""
511 def tests_exempt(self, execution: Execution, change_set: ChangeSet, check: str) -> str | None:
512 """Why a test requirement does not apply to the ChangeSet."""
515class LadderIntakePort(Protocol):
516 """The ladder's intake step as the friction settings use it."""
518 def defaults(
519 self, execution: Execution | None = ..., task: Task | None = ...
520 ) -> dict[str, Any]:
521 """What the configuration says about a contract's open items."""
524class LadderPort(Protocol):
525 """The verification ladder as the engine's helpers use it."""
527 @property
528 def active(self) -> bool:
529 """Whether any ladder setting that acts on a run is configured."""
531 @property
532 def intake(self) -> LadderIntakePort:
533 """The intake step of the ladder."""
535 def after_decision(self, execution: Execution, record: HumanDecision) -> None:
536 """Recompute the certification with the ticked items."""
538 def located_paths(self, execution: Execution) -> list[str]:
539 """The paths the locate call found."""
541 def manual_items(self, task: Task) -> list[dict[str, str]]:
542 """What only a person can verify."""
545class PanelPort(Protocol):
546 """The review panel as the single reviewer uses it."""
548 @property
549 def configured(self) -> bool:
550 """Whether the review panel is configured."""
552 def run(
553 self, execution: Execution, phase: PhaseExecution, change_set: ChangeSet
554 ) -> ReviewOutcome:
555 """Review the ChangeSet with the panel."""
558class ProjectSetupPort(Protocol):
559 """The project setup questions as the intent review uses them."""
561 def questions(
562 self, execution: Execution, phase: PhaseExecution, start: int
563 ) -> tuple[ClarificationQuestion, ...]:
564 """The project setup questions to ask in INTENT."""
567class ProvenancePort(Protocol):
568 """The provenance recorder as the review panel uses it."""
570 @property
571 def snapshots_enabled(self) -> bool:
572 """Whether agent snapshots are recorded."""
574 def attribute(self, execution: Execution, change_set: ChangeSet, phase_id: PhaseId) -> None:
575 """Record who produced each file of the ChangeSet."""
578class StopLinePort(Protocol):
579 """The stop-the-line checks as the verification checks use them."""
581 def owned_paths_output(
582 self, execution: Execution, change_set: ChangeSet
583 ) -> ValidatorOutput | None:
584 """The owned-paths check as a validation."""
587class VerificationPort(Protocol):
588 """The verification checks as siblings use them."""
590 def risk_actions(self) -> dict[str, str]:
591 """The action of each risk factor."""
593 def _output(
594 self,
595 execution: Execution,
596 change_set: ChangeSet,
597 validator_id: str,
598 policy: str,
599 issues: list[Issue],
600 label: str,
601 *,
602 started: datetime,
603 extra_evidence: tuple[str, ...] = ...,
604 mandatory: bool | None = ...,
605 report: dict[str, Any] | None = ...,
606 ) -> ValidatorOutput:
607 """A verification check's result as a validator output."""
610__all__ = [
611 "AcceptancePort",
612 "AgentReviewPort",
613 "ArchitecturePort",
614 "CorrectionsPort",
615 "EngineHost",
616 "EngineeringPort",
617 "FrictionPort",
618 "LadderIntakePort",
619 "LadderPort",
620 "PanelPort",
621 "ProjectSetupPort",
622 "ProvenancePort",
623 "ResultsHost",
624 "StopLinePort",
625 "VerificationPort",
626]