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

1"""What the engine's helpers need from the objects that own them (#69). 

2 

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. 

10 

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.""" 

14 

15from __future__ import annotations 

16 

17from typing import TYPE_CHECKING, Any, Protocol 

18 

19if TYPE_CHECKING: 

20 from collections.abc import Callable 

21 from datetime import datetime 

22 from pathlib import Path 

23 

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 

70 

71 

72class EngineHost(Protocol): 

73 """The :class:`RunEngine` as its helpers use it.""" 

74 

75 @property 

76 def friction(self) -> FrictionPort: 

77 """The friction settings of the run (#58).""" 

78 

79 @property 

80 def gate_engine(self) -> GateEngine: 

81 """The gate evaluation of DECISION.""" 

82 

83 @property 

84 def ladder(self) -> LadderPort: 

85 """The verification ladder (#55).""" 

86 

87 @property 

88 def provenance(self) -> ProvenancePort: 

89 """The provenance recorder of the ChangeSet's files.""" 

90 

91 @property 

92 def results(self) -> ResultsHost: 

93 """The agent-results settings of the run.""" 

94 

95 @property 

96 def s(self) -> EngineServices: 

97 """The project's configuration, paths and stores.""" 

98 

99 @property 

100 def sandbox_host(self) -> SandboxHost: 

101 """The host the agent sandbox is built for.""" 

102 

103 @property 

104 def snapshots(self) -> SnapshotStore: 

105 """The workspace snapshots of the run.""" 

106 

107 @property 

108 def state_machine(self) -> NormativeStateMachine: 

109 """The normative phase transitions.""" 

110 

111 @property 

112 def validators(self) -> ValidatorRegistry: 

113 """The validators available to VERIFICATION.""" 

114 

115 def baseline_digests(self, execution: Execution) -> dict[str, str]: 

116 """Path to digest of the run's baseline snapshot.""" 

117 

118 def current_change_set(self, execution_id: str) -> ChangeSet: 

119 """The run's current ChangeSet.""" 

120 

121 def get_execution(self, execution_id: str) -> Execution: 

122 """The stored run.""" 

123 

124 def is_cancelled(self, execution_id: str) -> bool: 

125 """Whether the run was cancelled.""" 

126 

127 def run_task(self, execution: Execution) -> Task: 

128 """The task revision the run works on.""" 

129 

130 def _agent_network_allowed(self) -> bool: 

131 """Whether the agent sandbox allows outbound network.""" 

132 

133 def _bounded_definition(self, definition: ValidatorDefinition) -> ValidatorDefinition: 

134 """The validator definition within the phase's time budget.""" 

135 

136 def _bounded_timeout(self, seconds: int) -> int: 

137 """A timeout within the phase's time budget.""" 

138 

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.""" 

143 

144 def _compute_owned_diff(self, execution: Execution) -> WorkspaceDiff: 

145 """The task-owned diff, without persisting unredacted content.""" 

146 

147 def _current_contract_digest(self, execution: Execution) -> str | None: 

148 """The digest of the frozen acceptance contract.""" 

149 

150 def _external_provider(self, execution_id: str) -> bool: 

151 """Whether the run uses a configured command provider.""" 

152 

153 def _feedback_applies(self, execution_id: str) -> bool: 

154 """Whether provider feedback applies to the run.""" 

155 

156 def _latest_validations(self, execution_id: str, digest: str) -> list[ValidationResult]: 

157 """The latest validation of each validator for a digest.""" 

158 

159 def _protected_paths(self, execution: Execution | None = None) -> tuple[Path, ...]: 

160 """Paths the agent sandbox keeps read-only.""" 

161 

162 def _provenance(self, execution: Execution) -> Provenance: 

163 """The provenance of the run's records.""" 

164 

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.""" 

176 

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.""" 

190 

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.""" 

200 

201 def _runner(self, execution: Execution) -> SafeProcessRunner: 

202 """The process runner of the run.""" 

203 

204 def _save_agent_result( 

205 self, execution: Execution, phase: PhaseExecution, result: AgentExecutionResult 

206 ) -> None: 

207 """Record what an agent call did.""" 

208 

209 def _save_execution(self, execution: Execution) -> None: 

210 """Store the run.""" 

211 

212 def _save_tool(self, execution: Execution, tool: ToolInvocation) -> None: 

213 """Record a tool invocation.""" 

214 

215 def _save_validator_output(self, execution: Execution, output: Any) -> None: 

216 """Record a validator's result and findings.""" 

217 

218 def _transient_cause(self, result: AgentExecutionResult) -> str | None: 

219 """The pattern that marks a failed provider call as transient.""" 

220 

221 def _wait_for_retry(self, execution_id: str, delay: float) -> bool: 

222 """Wait before a retry; ``False`` when the run is cancelled.""" 

223 

224 @staticmethod 

225 def _snapshot_from_dict(value: dict[str, Any]) -> WorkspaceSnapshot: 

226 """A workspace snapshot from its stored form.""" 

227 

228 @staticmethod 

229 def _snapshot_to_dict(snapshot: WorkspaceSnapshot) -> dict[str, Any]: 

230 """The stored form of a workspace snapshot.""" 

231 

232 

233class ResultsHost(Protocol): 

234 """The :class:`AgentResults` as its helpers use it.""" 

235 

236 @property 

237 def acceptance(self) -> AcceptancePort: 

238 """The acceptance tests (``verification.acceptanceTests``).""" 

239 

240 @property 

241 def active(self) -> bool: 

242 """Whether any agent-results setting is configured.""" 

243 

244 @property 

245 def agent_contract(self) -> AgentContractPort: 

246 """The agent contract (#97).""" 

247 

248 @property 

249 def agent_review(self) -> AgentReviewPort: 

250 """The single independent reviewer.""" 

251 

252 @property 

253 def architecture(self) -> ArchitecturePort: 

254 """The architecture flow (#56).""" 

255 

256 @property 

257 def corrections(self) -> CorrectionsPort: 

258 """The reproduce-first corrections.""" 

259 

260 @property 

261 def engine(self) -> EngineHost: 

262 """The engine that owns these settings.""" 

263 

264 @property 

265 def engineering(self) -> EngineeringPort: 

266 """The standards, principles and testing strategy (#56).""" 

267 

268 @property 

269 def panel(self) -> PanelPort: 

270 """The review panel (#57).""" 

271 

272 @property 

273 def project(self) -> ProjectConfiguration: 

274 """The project configuration.""" 

275 

276 @property 

277 def project_setup(self) -> ProjectSetupPort: 

278 """The project setup questions (#56).""" 

279 

280 @property 

281 def s(self) -> EngineServices: 

282 """The project's configuration, paths and stores.""" 

283 

284 @property 

285 def secrets_in_context(self) -> bool: 

286 """Whether secrets may reach an agent's context.""" 

287 

288 @property 

289 def stop_line(self) -> StopLinePort: 

290 """The stop-the-line checks.""" 

291 

292 @property 

293 def verification(self) -> VerificationPort: 

294 """The verification checks.""" 

295 

296 def after_agent_call( 

297 self, execution: Execution, phase: PhaseExecution, result: AgentExecutionResult 

298 ) -> None: 

299 """Account for a finished agent call.""" 

300 

301 def baseline_changes(self, execution: Execution) -> WorkspaceDiff | None: 

302 """Every change since DISCOVERY, with a unified diff.""" 

303 

304 def baseline_contents(self, execution: Execution) -> Contents | None: 

305 """The recorded bytes of the baseline's files.""" 

306 

307 def baseline_snapshot(self, execution: Execution) -> WorkspaceSnapshot | None: 

308 """The workspace as DISCOVERY recorded it.""" 

309 

310 def baseline_text(self, execution: Execution) -> Callable[[str], str | None]: 

311 """The baseline text of a path, when it had one.""" 

312 

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.""" 

317 

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``).""" 

332 

333 def change_requests(self, execution: Execution) -> list[dict[str, Any]]: 

334 """The structured change requests of the run.""" 

335 

336 def flag_json(self, key: str) -> Any: 

337 """A JSON flag of the state store.""" 

338 

339 def implement_model(self, execution: Execution, task: Task) -> str | None: 

340 """The model an implement call would use.""" 

341 

342 def provider_for(self, execution: Execution, kind: CallKind) -> str: 

343 """The provider of a call kind.""" 

344 

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.""" 

362 

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.""" 

375 

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.""" 

391 

392 def required_acknowledgements(self, execution: Execution, digest: str) -> list[str]: 

393 """The risk factors a decision must acknowledge.""" 

394 

395 def set_flag_json(self, key: str, value: Any) -> None: 

396 """Store a JSON flag.""" 

397 

398 def task_signals(self, execution: Execution, task: Task) -> TaskSignals: 

399 """Size signals of the task known before the call.""" 

400 

401 

402class AcceptancePort(Protocol): 

403 """The acceptance tests (``verification.acceptanceTests``) as siblings use them.""" 

404 

405 def state(self, execution: Execution) -> dict[str, Any] | None: 

406 """The acceptance tests' state of the run.""" 

407 

408 def validation(self, execution: Execution, change_set: ChangeSet) -> ValidatorOutput | None: 

409 """The acceptance tests as a validation of the ChangeSet.""" 

410 

411 def untouched(self, execution: Execution) -> set[str]: 

412 """The frozen files still as approved (the harness's, not the agent's edits).""" 

413 

414 

415class AgentContractPort(Protocol): 

416 """The agent contract as the review panel uses it (#149).""" 

417 

418 @property 

419 def enabled(self) -> bool: 

420 """Whether ``agentContract`` is set to ``enforce``.""" 

421 

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.""" 

424 

425 def timeout(self, default: int, limits: CallLimits) -> int: 

426 """The time a process may run under the limits.""" 

427 

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``.""" 

440 

441 

442class AgentReviewPort(Protocol): 

443 """The single independent reviewer as the review panel uses it.""" 

444 

445 def blocking_severities(self) -> set[FindingSeverity]: 

446 """The finding severities that block.""" 

447 

448 

449class ArchitecturePort(Protocol): 

450 """The architecture flow as siblings use it.""" 

451 

452 def request_extra(self) -> dict[str, Any] | None: 

453 """What the architecture adds to an agent request.""" 

454 

455 def rules(self) -> LayerRules | None: 

456 """The layer rules of the project.""" 

457 

458 

459class CorrectionsPort(Protocol): 

460 """The reproduce-first corrections as the verification checks use them.""" 

461 

462 def validation(self, execution: Execution, change_set: ChangeSet) -> ValidatorOutput | None: 

463 """The latest correction attempt as a validation.""" 

464 

465 

466class EngineeringPort(Protocol): 

467 """The engineering settings (standards, testing, TDD) as siblings use them.""" 

468 

469 @property 

470 def configured(self) -> bool: 

471 """Whether any engineering setting is configured.""" 

472 

473 def bdd_command(self) -> tuple[str, ...]: 

474 """The command that runs the feature files.""" 

475 

476 def features_directory(self) -> str: 

477 """Where the feature files live.""" 

478 

479 def review_extra(self, change_set: ChangeSet) -> tuple[dict[str, Any], str]: 

480 """The checklist the review call gains.""" 

481 

482 def setup_record(self, project_id: str) -> dict[str, Any]: 

483 """The project setup answers.""" 

484 

485 def strategy(self, project_id: str) -> Strategy: 

486 """The effective testing strategy.""" 

487 

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.""" 

496 

497 def technologies(self) -> tuple[str, ...]: 

498 """The technologies of the project.""" 

499 

500 

501class FrictionPort(Protocol): 

502 """The friction settings as the engine's helpers use them.""" 

503 

504 @property 

505 def active(self) -> bool: 

506 """Whether a friction setting that acts on a run is configured.""" 

507 

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.""" 

510 

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.""" 

513 

514 

515class LadderIntakePort(Protocol): 

516 """The ladder's intake step as the friction settings use it.""" 

517 

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.""" 

522 

523 

524class LadderPort(Protocol): 

525 """The verification ladder as the engine's helpers use it.""" 

526 

527 @property 

528 def active(self) -> bool: 

529 """Whether any ladder setting that acts on a run is configured.""" 

530 

531 @property 

532 def intake(self) -> LadderIntakePort: 

533 """The intake step of the ladder.""" 

534 

535 def after_decision(self, execution: Execution, record: HumanDecision) -> None: 

536 """Recompute the certification with the ticked items.""" 

537 

538 def located_paths(self, execution: Execution) -> list[str]: 

539 """The paths the locate call found.""" 

540 

541 def manual_items(self, task: Task) -> list[dict[str, str]]: 

542 """What only a person can verify.""" 

543 

544 

545class PanelPort(Protocol): 

546 """The review panel as the single reviewer uses it.""" 

547 

548 @property 

549 def configured(self) -> bool: 

550 """Whether the review panel is configured.""" 

551 

552 def run( 

553 self, execution: Execution, phase: PhaseExecution, change_set: ChangeSet 

554 ) -> ReviewOutcome: 

555 """Review the ChangeSet with the panel.""" 

556 

557 

558class ProjectSetupPort(Protocol): 

559 """The project setup questions as the intent review uses them.""" 

560 

561 def questions( 

562 self, execution: Execution, phase: PhaseExecution, start: int 

563 ) -> tuple[ClarificationQuestion, ...]: 

564 """The project setup questions to ask in INTENT.""" 

565 

566 

567class ProvenancePort(Protocol): 

568 """The provenance recorder as the review panel uses it.""" 

569 

570 @property 

571 def snapshots_enabled(self) -> bool: 

572 """Whether agent snapshots are recorded.""" 

573 

574 def attribute(self, execution: Execution, change_set: ChangeSet, phase_id: PhaseId) -> None: 

575 """Record who produced each file of the ChangeSet.""" 

576 

577 

578class StopLinePort(Protocol): 

579 """The stop-the-line checks as the verification checks use them.""" 

580 

581 def owned_paths_output( 

582 self, execution: Execution, change_set: ChangeSet 

583 ) -> ValidatorOutput | None: 

584 """The owned-paths check as a validation.""" 

585 

586 

587class VerificationPort(Protocol): 

588 """The verification checks as siblings use them.""" 

589 

590 def risk_actions(self) -> dict[str, str]: 

591 """The action of each risk factor.""" 

592 

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.""" 

608 

609 

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]