Coverage for src/governed_harness/application/ladder.py: 85%

248 statements  

« prev     ^ index     » next       coverage.py v7.17.2, created at 2026-11-12 16:06 +0000

1"""Application helpers of the verification ladder and delivery hygiene (#55): what ``harness 

2verification``, ``harness task confirm``, ``harness evidence attach`` and ``harness config lint`` 

3do, and the sections the decision brief and the inbox add.""" 

4 

5from __future__ import annotations 

6 

7import mimetypes 

8from datetime import datetime, timedelta 

9from pathlib import Path 

10from typing import TYPE_CHECKING, Any 

11 

12from governed_harness.domain.enums import ActorType, PhaseId, ResultStatus 

13from governed_harness.domain.errors import ConfigurationError, NotFoundError, PolicyViolationError 

14from governed_harness.domain.ids import new_id 

15from governed_harness.domain.models import ( 

16 Actor, 

17 CertificationRecord, 

18 ClarificationRequest, 

19 DeferredVerification, 

20 Execution, 

21 HumanAttachment, 

22 HumanDecision, 

23 Task, 

24 utc_now, 

25) 

26from governed_harness.intake import task_digest 

27from governed_harness.ladder.external import EvidenceFormatError, read_evidence 

28from governed_harness.ladder.instructions import lint_instructions 

29 

30if TYPE_CHECKING: 

31 from governed_harness.orchestration.engine import EngineServices, RunEngine 

32 

33MAX_ATTACHMENT_BYTES = 50_000_000 

34_TEXT_TYPES = ("text/", "application/json", "application/xml", "application/x-ndjson") 

35 

36 

37# ----- harness verification show / decide ---------------------------------------------------- 

38def verification_state(services: EngineServices, execution_id: str) -> dict[str, Any]: 

39 """The verification plan, the preflight, the certification, the deferred items and the 

40 manual checklist of a run.""" 

41 from governed_harness.orchestration.engine import RunEngine 

42 

43 engine = RunEngine(services) 

44 execution = engine.get_execution(execution_id) 

45 task = engine.run_task(execution) 

46 ladder = engine.ladder 

47 preflight = engine.results.flag_json(f"preflight:{execution_id}") 

48 plan: dict[str, Any] | None = None 

49 if isinstance(preflight, dict) and isinstance(preflight.get("ref"), str): 49 ↛ 53line 49 didn't jump to line 53 because the condition on line 49 was always true

50 import json 

51 

52 plan = json.loads(services.artifacts.get(preflight["ref"])) 

53 certification = ladder.latest_certification(execution_id, execution.change_set_digest) 

54 return { 

55 "executionId": execution_id, 

56 "status": execution.status.value, 

57 "currentPhase": execution.current_phase.value, 

58 "changeSetDigest": execution.change_set_digest, 

59 "ladder": { 

60 "mode": ladder.config.mode if ladder.config else "off", 

61 "defaultLevel": ladder.config.required_default.value if ladder.config else None, 

62 }, 

63 "preflight": plan, 

64 "preflightDecision": ladder.preflight_decision(execution), 

65 "certification": certification.model_dump(mode="json", by_alias=True) 

66 if certification 

67 else None, 

68 "deferred": [ 

69 item.model_dump(mode="json", by_alias=True) 

70 for item in ladder.deferred_items(execution, None) 

71 ], 

72 "checklist": ladder.manual_items(task), 

73 "contract": contract_state(services, execution), 

74 "interruptions": ladder.intake.interruptions(execution), 

75 } 

76 

77 

78def decide_preflight( 

79 services: EngineServices, 

80 execution_id: str, 

81 *, 

82 actor: Actor, 

83 rationale: str, 

84) -> dict[str, Any]: 

85 """A person decides to continue a run whose preflight is UNAVAILABLE without the rungs it 

86 cannot reach: those criteria are never certified (``WAIVED``) and the unavailable probes are 

87 not run. The decision is recorded on the run's chain.""" 

88 from governed_harness.orchestration.engine import RunEngine 

89 

90 if actor.actor_type is not ActorType.HUMAN: 90 ↛ 91line 90 didn't jump to line 91 because the condition on line 90 was never true

91 raise PolicyViolationError("only a person can decide to continue uncertified") 

92 if not rationale.strip(): 

93 raise PolicyViolationError("continuing uncertified requires a rationale") 

94 engine = RunEngine(services) 

95 execution = engine.get_execution(execution_id) 

96 preflight = engine.results.flag_json(f"preflight:{execution_id}") 

97 if ( 97 ↛ 102line 97 didn't jump to line 102 because the condition on line 97 was never true

98 execution.current_phase is not PhaseId.PLANNING 

99 or not isinstance(preflight, dict) 

100 or preflight.get("status") != "UNAVAILABLE" 

101 ): 

102 raise PolicyViolationError( 

103 f"run {execution_id} is not waiting on an UNAVAILABLE preflight " 

104 f"({execution.status.value} in {execution.current_phase.value})" 

105 ) 

106 import json 

107 

108 plan = json.loads(services.artifacts.get(preflight["ref"])) 

109 criteria = sorted( 

110 item["criterionId"] 

111 for item in plan.get("criteria", []) 

112 if item.get("route") == "unreachable" and item.get("declared") 

113 ) 

114 probes = sorted( 

115 probe_id 

116 for probe_id, value in (plan.get("probes") or {}).items() 

117 if value.get("readiness") == "UNAVAILABLE" 

118 ) 

119 decision = { 

120 "decisionId": new_id("preflightdecision"), 

121 "decision": "CONTINUE_UNCERTIFIED", 

122 "actorId": actor.actor_id, 

123 "rationale": rationale.strip(), 

124 "criteria": criteria, 

125 "probes": probes, 

126 "preflightRef": preflight["ref"], 

127 "decidedAt": utc_now().isoformat(), 

128 } 

129 engine.results.set_flag_json(f"preflightdecision:{execution_id}", decision) 

130 services.events.append(execution_id, "verification.preflight.decided", decision, actor=actor) 

131 engine.anchor_chain(execution_id) 

132 return decision 

133 

134 

135# ----- the operational contract ---------------------------------------------------------------- 

136def contract_state(services: EngineServices, execution: Execution) -> dict[str, Any] | None: 

137 import json 

138 

139 raw = services.state.get_flag(f"contractcurrent:{execution.execution_id}") 

140 if not raw: 

141 return None 

142 current = json.loads(raw) 

143 summary = json.loads(services.artifacts.get(current["ref"])) 

144 confirmed_raw = services.state.get_flag(f"contractconfirmed:{execution.execution_id}") 

145 confirmed = json.loads(confirmed_raw) if confirmed_raw else None 

146 return { 

147 **summary, 

148 "confirmed": bool(confirmed and confirmed.get("digest") == summary["digest"]), 

149 "confirmedBy": confirmed.get("actorId") if confirmed else None, 

150 } 

151 

152 

153def confirm_contract( 

154 services: EngineServices, *, task_id: str, digest: str, actor: Actor 

155) -> dict[str, Any]: 

156 """A person confirms the operational contract of a task's current revision, bound to its 

157 digest; INTENT under ``operationalContract: enforce`` then passes.""" 

158 import json 

159 

160 from governed_harness.orchestration.engine import RunEngine 

161 

162 if actor.actor_type is not ActorType.HUMAN: 162 ↛ 163line 162 didn't jump to line 163 because the condition on line 162 was never true

163 raise PolicyViolationError("only a person can confirm the operational contract") 

164 engine = RunEngine(services) 

165 task = engine.get_task(task_id) 

166 runs = [ 

167 item 

168 for item in services.state.list("execution", Execution, project_id=task.project_id) 

169 if item.task_id == task_id and item.current_phase is PhaseId.INTENT 

170 ] 

171 if not runs: 171 ↛ 172line 171 didn't jump to line 172 because the condition on line 171 was never true

172 raise NotFoundError(f"task {task_id} has no run in INTENT") 

173 execution = max(runs, key=lambda item: item.created_at) 

174 raw = services.state.get_flag(f"contractcurrent:{execution.execution_id}") 

175 if not raw: 175 ↛ 176line 175 didn't jump to line 176 because the condition on line 175 was never true

176 raise NotFoundError(f"run {execution.execution_id} has no operational contract yet") 

177 current = json.loads(raw) 

178 if current.get("taskDigest") != task_digest(engine.run_task(execution)): 178 ↛ 179line 178 didn't jump to line 179 because the condition on line 178 was never true

179 raise PolicyViolationError( 

180 "the task changed after its contract was summarized; run harness run continue first" 

181 ) 

182 if current.get("digest") != digest: 

183 raise PolicyViolationError( 

184 f"the digest does not match the current contract ({current.get('digest')})" 

185 ) 

186 record = {"digest": digest, "actorId": actor.actor_id, "confirmedAt": utc_now().isoformat()} 

187 engine.results.set_flag_json(f"contractconfirmed:{execution.execution_id}", record) 

188 services.events.append( 

189 execution.execution_id, 

190 "contract.confirmed", 

191 {"digest": digest, "taskDigest": current.get("taskDigest")}, 

192 actor=actor, 

193 ) 

194 engine.anchor_chain(execution.execution_id) 

195 return { 

196 "executionId": execution.execution_id, 

197 **record, 

198 "next": f"harness run continue --run {execution.execution_id}", 

199 } 

200 

201 

202# ----- harness evidence attach ----------------------------------------------------------------- 

203def _media_type(path: Path) -> str: 

204 guessed, _ = mimetypes.guess_type(path.name) 

205 return guessed or "application/octet-stream" 

206 

207 

208def attach_evidence( 

209 services: EngineServices, 

210 *, 

211 file: Path, 

212 actor: Actor, 

213 execution_id: str | None = None, 

214 task_id: str | None = None, 

215 item: str | None = None, 

216 manual: bool = False, 

217 evidence_format: str = "auto", 

218 case: str | None = None, 

219 commit: str | None = None, 

220 note: str | None = None, 

221) -> dict[str, Any]: 

222 """Attach evidence: close a deferred verification of a run with a JUnit, SARIF or CI 

223 status report, or store a person's attachment (``manual``) bound to a run's ChangeSet and 

224 a checklist item, or to a task revision as intake context.""" 

225 from governed_harness.orchestration.engine import RunEngine 

226 

227 if actor.actor_type is not ActorType.HUMAN: 227 ↛ 228line 227 didn't jump to line 228 because the condition on line 227 was never true

228 raise PolicyViolationError("only a person attaches evidence") 

229 if (execution_id is None) == (task_id is None): 229 ↛ 230line 229 didn't jump to line 230 because the condition on line 229 was never true

230 raise ConfigurationError("attach to a run (--run) or to a task (--task), not both") 

231 if not file.is_file(): 231 ↛ 232line 231 didn't jump to line 232 because the condition on line 231 was never true

232 raise NotFoundError(f"file not found: {file}") 

233 data = file.read_bytes() 

234 if len(data) > MAX_ATTACHMENT_BYTES: 234 ↛ 235line 234 didn't jump to line 235 because the condition on line 234 was never true

235 raise ConfigurationError(f"the file is larger than {MAX_ATTACHMENT_BYTES} bytes") 

236 engine = RunEngine(services) 

237 if task_id is not None: 

238 if not manual: 

239 raise ConfigurationError("a task takes a person's attachment: use --manual") 

240 task = engine.get_task(task_id) 

241 return _attach_manual(services, engine, task, None, file, data, actor, item, note) 

242 if execution_id is None: # not reached: exactly one of run and task is checked above 242 ↛ 243line 242 didn't jump to line 243 because the condition on line 242 was never true

243 raise ConfigurationError("attach to a run (--run) or to a task (--task)") 

244 execution = engine.get_execution(execution_id) 

245 task = engine.run_task(execution) 

246 if manual: 246 ↛ 247line 246 didn't jump to line 247 because the condition on line 246 was never true

247 return _attach_manual(services, engine, task, execution, file, data, actor, item, note) 

248 if item is None: 248 ↛ 249line 248 didn't jump to line 249 because the condition on line 248 was never true

249 raise ConfigurationError( 

250 "name the deferred item to close with --item (for example D-ac_e2e)" 

251 ) 

252 return _close_deferred( 

253 services, engine, execution, item, file, data, actor, evidence_format, case, commit 

254 ) 

255 

256 

257def _attach_manual( 

258 services: EngineServices, 

259 engine: RunEngine, 

260 task: Task, 

261 execution: Execution | None, 

262 file: Path, 

263 data: bytes, 

264 actor: Actor, 

265 item: str | None, 

266 note: str | None, 

267) -> dict[str, Any]: 

268 media = _media_type(file) 

269 if item is not None: 269 ↛ 270line 269 didn't jump to line 270 because the condition on line 269 was never true

270 known = {entry["itemId"] for entry in engine.ladder.manual_items(task)} 

271 if item not in known: 

272 raise ConfigurationError( 

273 f"unknown checklist item {item}; the task's items are " 

274 + (", ".join(sorted(known)) or "none") 

275 ) 

276 ref = services.artifacts.put( 

277 data, 

278 media_type=media, 

279 metadata={"kind": "human-attachment", "fileName": file.name}, 

280 redact=media.startswith(_TEXT_TYPES), 

281 ) 

282 attachment = HumanAttachment( 

283 attachment_id=new_id("attachment"), 

284 project_id=task.project_id, 

285 task_id=task.task_id, 

286 task_digest=task_digest(task) if execution is None else None, 

287 execution_id=execution.execution_id if execution else None, 

288 change_set_digest=execution.change_set_digest if execution else None, 

289 item_id=item, 

290 artifact_ref=ref.uri, 

291 digest=ref.digest, 

292 media_type=media, 

293 size_bytes=ref.size_bytes, 

294 file_name=file.name, 

295 note=note, 

296 actor=actor, 

297 ) 

298 services.state.put( 

299 "human_attachment", 

300 attachment.attachment_id, 

301 attachment, 

302 execution_id=execution.execution_id if execution else None, 

303 project_id=task.project_id, 

304 ) 

305 if execution is not None: 305 ↛ 306line 305 didn't jump to line 306 because the condition on line 305 was never true

306 engine._record_evidence( 

307 execution, 

308 execution.current_phase, 

309 _evidence_kind(), 

310 ref, 

311 f"Attachment {file.name}" + (f" for {item}" if item else ""), 

312 supports=(item,) if item else (), 

313 ) 

314 services.events.append( 

315 execution.execution_id, 

316 "evidence.attached", 

317 attachment.model_dump(mode="json", by_alias=True), 

318 actor=actor, 

319 ) 

320 engine.anchor_chain(execution.execution_id) 

321 return attachment.model_dump(mode="json", by_alias=True) 

322 

323 

324def _evidence_kind() -> Any: 

325 from governed_harness.domain.enums import EvidenceKind 

326 

327 return EvidenceKind.HUMAN_DECISION 

328 

329 

330def _close_deferred( 

331 services: EngineServices, 

332 engine: RunEngine, 

333 execution: Execution, 

334 item_id: str, 

335 file: Path, 

336 data: bytes, 

337 actor: Actor, 

338 evidence_format: str, 

339 case: str | None, 

340 commit: str | None, 

341) -> dict[str, Any]: 

342 items = [ 

343 entry for entry in engine.ladder.deferred_items(execution, None) if entry.item_id == item_id 

344 ] 

345 if not items: 

346 raise NotFoundError(f"run {execution.execution_id} has no deferred item {item_id}") 

347 current = [entry for entry in items if entry.change_set_digest == execution.change_set_digest] 

348 deferred = max(current or items, key=lambda entry: entry.created_at) 

349 if deferred.status == "EXPIRED": 

350 _expire(services, execution, deferred) 

351 raise PolicyViolationError( 

352 f"deferred item {item_id} expired at {deferred.expires_at.isoformat()}; the " 

353 "criterion is not certified. Run the task again to verify it" 

354 ) 

355 if deferred.status != "PENDING": 

356 raise PolicyViolationError(f"deferred item {item_id} is already {deferred.status}") 

357 try: 

358 verdict = read_evidence(data, evidence_format, case) 

359 except EvidenceFormatError as error: 

360 raise ConfigurationError(f"{file.name}: {error}") from error 

361 claimed = commit or verdict.commit 

362 if ( 

363 deferred.commit 

364 and claimed 

365 and not deferred.commit.startswith(claimed) 

366 and not claimed.startswith(deferred.commit) 

367 ): 

368 raise PolicyViolationError( 

369 f"the evidence is about commit {claimed}, the item is bound to {deferred.commit}" 

370 ) 

371 ref = services.artifacts.put( 

372 data, 

373 media_type="application/xml" if verdict.kind == "junit" else "application/json", 

374 metadata={"kind": f"deferred-evidence-{verdict.kind}", "fileName": file.name}, 

375 ) 

376 closed = deferred.model_copy( 

377 update={ 

378 "status": "PASSED" if verdict.passed else "FAILED", 

379 "closed_at": utc_now(), 

380 "evidence_kind": verdict.kind, 

381 "evidence_ref": ref.uri, 

382 "evidence_digest": ref.digest, 

383 "summary": verdict.summary, 

384 "closed_by": actor, 

385 "commit": deferred.commit or claimed, 

386 } 

387 ) 

388 services.state.put( 

389 "deferred_verification", 

390 closed.deferred_id, 

391 closed, 

392 execution_id=execution.execution_id, 

393 project_id=execution.project_id, 

394 ) 

395 from governed_harness.domain.enums import EvidenceKind 

396 

397 engine._record_evidence( 

398 execution, 

399 PhaseId.CLOSURE if execution.status is ResultStatus.PASSED else execution.current_phase, 

400 EvidenceKind.TEST_REPORT, 

401 ref, 

402 f"Deferred {item_id}: {verdict.summary}", 

403 supports=(deferred.criterion_id,), 

404 ) 

405 services.events.append( 

406 execution.execution_id, 

407 "verification.deferred.closed", 

408 { 

409 "deferredId": closed.deferred_id, 

410 "itemId": item_id, 

411 "status": closed.status, 

412 "evidenceKind": verdict.kind, 

413 "evidenceRef": ref.uri, 

414 "summary": verdict.summary, 

415 "commit": closed.commit, 

416 }, 

417 actor=actor, 

418 ) 

419 certification = engine.ladder.after_evidence(engine.get_execution(execution.execution_id)) 

420 engine.anchor_chain(execution.execution_id) 

421 return { 

422 "deferred": closed.model_dump(mode="json", by_alias=True), 

423 "certification": certification.status if certification else None, 

424 } 

425 

426 

427def _expire(services: EngineServices, execution: Execution, deferred: DeferredVerification) -> None: 

428 stored = services.state.get("deferred_verification", deferred.deferred_id, DeferredVerification) 

429 if stored.status != "PENDING": 429 ↛ 430line 429 didn't jump to line 430 because the condition on line 429 was never true

430 return 

431 services.state.put( 

432 "deferred_verification", 

433 stored.deferred_id, 

434 stored.model_copy(update={"status": "EXPIRED"}), 

435 execution_id=execution.execution_id, 

436 project_id=execution.project_id, 

437 ) 

438 services.events.append( 

439 execution.execution_id, 

440 "verification.deferred.expired", 

441 {"deferredId": stored.deferred_id, "itemId": stored.item_id}, 

442 ) 

443 

444 

445# ----- the brief and the inbox ----------------------------------------------------------------- 

446def brief_sections(services: EngineServices, execution: Execution) -> dict[str, Any]: 

447 """The sections the ladder settings add to the decision brief; empty for a run that 

448 recorded none of them, so the brief of other runs keeps its form.""" 

449 from governed_harness.orchestration.engine import RunEngine 

450 

451 engine = RunEngine(services) 

452 ladder = engine.ladder 

453 if not ladder.active: 

454 return {} 

455 sections: dict[str, Any] = {} 

456 certification = ladder.latest_certification(execution.execution_id, execution.change_set_digest) 

457 if certification is not None: 

458 sections["certification"] = { 

459 "status": certification.status, 

460 "trigger": certification.trigger, 

461 "changeSetDigest": certification.change_set_digest, 

462 "criteria": [ 

463 { 

464 "criterionId": item.criterion_id, 

465 "required": item.required.value, 

466 "achieved": item.achieved.value if item.achieved else None, 

467 "declared": item.declared, 

468 "status": item.status, 

469 "reason": item.reason, 

470 "evidence": [entry.source for entry in item.evidence], 

471 "pending": list(item.pending), 

472 } 

473 for item in certification.criteria 

474 ], 

475 } 

476 preflight = engine.results.flag_json(f"preflight:{execution.execution_id}") 

477 if isinstance(preflight, dict): 

478 sections["preflight"] = { 

479 "status": preflight.get("status"), 

480 "reasons": preflight.get("reasons") or [], 

481 "decision": ladder.preflight_decision(execution), 

482 } 

483 deferred = ladder.deferred_items(execution, execution.change_set_digest) 

484 if deferred: 

485 sections["deferred"] = [ 

486 { 

487 "itemId": item.item_id, 

488 "criterionId": item.criterion_id, 

489 "where": item.where, 

490 "status": item.status, 

491 "commit": item.commit, 

492 "expiresAt": item.expires_at.isoformat(), 

493 "next": f"harness evidence attach --run {execution.execution_id} --item " 

494 f"{item.item_id} --file REPORT", 

495 } 

496 for item in deferred 

497 ] 

498 task = engine.run_task(execution) 

499 checklist = ladder.manual_items(task) 

500 if checklist: 

501 decisions = [ 

502 item 

503 for item in services.state.list( 

504 "decision", HumanDecision, execution_id=execution.execution_id 

505 ) 

506 if item.change_set_digest == execution.change_set_digest 

507 ] 

508 ticked = ( 

509 set(max(decisions, key=lambda item: item.decided_at).checked_items) 

510 if decisions 

511 else set() 

512 ) 

513 attachments = services.state.list( 

514 "human_attachment", HumanAttachment, execution_id=execution.execution_id 

515 ) 

516 sections["checklist"] = [ 

517 { 

518 **item, 

519 "checked": item["itemId"] in ticked, 

520 "attachments": [ 

521 entry.file_name for entry in attachments if entry.item_id == item["itemId"] 

522 ], 

523 } 

524 for item in checklist 

525 ] 

526 contract = contract_state(services, execution) 

527 if contract is not None: 

528 sections["contract"] = contract 

529 interruptions = ladder.intake.interruptions(execution) 

530 if interruptions is not None: 

531 sections["interruptions"] = interruptions 

532 return sections 

533 

534 

535def not_verified_lines(sections: dict[str, Any]) -> list[str]: 

536 lines: list[str] = [] 

537 certification = sections.get("certification") 

538 if certification: 

539 for item in certification["criteria"]: 

540 if item["status"] != "CERTIFIED": 

541 lines.append( 

542 f"criterion {item['criterionId']} is {item['status']} on the ladder: " 

543 f"{item['reason']}" 

544 ) 

545 for item in sections.get("checklist") or []: 

546 if not item["checked"]: 546 ↛ 545line 546 didn't jump to line 545 because the condition on line 546 was always true

547 lines.append(f"checklist item {item['itemId']} needs a person: {item['text']}") 

548 return lines 

549 

550 

551def inbox_entries(services: EngineServices) -> list[dict[str, Any]]: 

552 """Deferred verifications waiting for evidence (and the ones that expired), and runs whose 

553 preflight waits for a person.""" 

554 project_id = services.resolved.project.project_id 

555 now = utc_now() 

556 entries: list[dict[str, Any]] = [] 

557 for item in services.state.list( 

558 "deferred_verification", DeferredVerification, project_id=project_id 

559 ): 

560 if item.status != "PENDING": 560 ↛ 561line 560 didn't jump to line 561 because the condition on line 560 was never true

561 continue 

562 execution = services.state.get("execution", item.execution_id, Execution) 

563 if item.change_set_digest == execution.change_set_digest: 563 ↛ 557line 563 didn't jump to line 557 because the condition on line 563 was always true

564 entries.append(_deferred_entry(services, item, now)) 

565 for execution in services.state.list("execution", Execution, project_id=project_id): 

566 if _preflight_waits(services, execution): 

567 entries.append( 

568 { 

569 "executionId": execution.execution_id, 

570 "taskId": execution.task_id, 

571 "taskTitle": services.state.get("task", execution.task_id, Task).title, 

572 "kind": "preflight", 

573 "waitingSince": execution.updated_at.isoformat(), 

574 "waitingHours": round((now - execution.updated_at).total_seconds() / 3600, 1), 

575 "next": f"harness verification show --run {execution.execution_id}", 

576 } 

577 ) 

578 return entries 

579 

580 

581def _expiry_warning(item: DeferredVerification, now: datetime) -> str | None: 

582 """Expired, expiring within two days, or nothing to warn about.""" 

583 if item.expires_at <= now: 

584 return f"expired at {item.expires_at.isoformat()}" 

585 if item.expires_at - now <= timedelta(days=2): 

586 return f"expires within {(item.expires_at - now).days + 1} day(s)" 

587 return None 

588 

589 

590def _deferred_entry( 

591 services: EngineServices, item: DeferredVerification, now: datetime 

592) -> dict[str, Any]: 

593 return { 

594 "executionId": item.execution_id, 

595 "taskId": item.task_id, 

596 "taskTitle": services.state.get("task", item.task_id, Task).title, 

597 "kind": "deferred", 

598 "itemId": item.item_id, 

599 "where": item.where, 

600 "status": "EXPIRED" if item.expires_at <= now else "PENDING", 

601 "warning": _expiry_warning(item, now), 

602 "waitingSince": item.created_at.isoformat(), 

603 "waitingHours": round((now - item.created_at).total_seconds() / 3600, 1), 

604 "next": f"harness evidence attach --run {item.execution_id} --item {item.item_id} " 

605 "--file REPORT", 

606 } 

607 

608 

609def _preflight_waits(services: EngineServices, execution: Execution) -> bool: 

610 """The run is blocked in PLANNING on an unavailable preflight nobody decided yet.""" 

611 if ( 

612 execution.current_phase is not PhaseId.PLANNING 

613 or execution.status is not ResultStatus.BLOCKED 

614 ): 

615 return False 

616 raw = services.state.get_flag(f"preflight:{execution.execution_id}") 

617 if not raw or '"UNAVAILABLE"' not in raw: 

618 return False 

619 return not services.state.get_flag(f"preflightdecision:{execution.execution_id}") 

620 

621 

622def open_contract_requests(services: EngineServices, task: Task) -> list[ClarificationRequest]: 

623 digest = task_digest(task) 

624 return [ 

625 item 

626 for item in services.state.list( 

627 "clarification_request", ClarificationRequest, project_id=task.project_id 

628 ) 

629 if item.task_id == task.task_id and item.task_digest == digest and item.contract 

630 ] 

631 

632 

633# ----- harness config lint ------------------------------------------------------------------ 

634def config_lint(services_or_root: Any) -> dict[str, Any]: 

635 """Contradictions between the harness configuration and the agent instruction files.""" 

636 from governed_harness.configuration.ladder import DEFAULT_INSTRUCTION_FILES 

637 

638 resolved = services_or_root 

639 project = resolved.project 

640 instructions = project.instructions 

641 files = list( 

642 instructions.files if instructions and instructions.files else DEFAULT_INSTRUCTION_FILES 

643 ) 

644 precedence = list( 

645 instructions.precedence 

646 if instructions and instructions.precedence 

647 else ("harness", *DEFAULT_INSTRUCTION_FILES) 

648 ) 

649 verification = project.verification 

650 coverage = ( 

651 verification.test_quality.diff_coverage 

652 if verification and verification.test_quality and verification.test_quality.diff_coverage 

653 else None 

654 ) 

655 report = lint_instructions( 

656 resolved.workspace_root, files, precedence, coverage_threshold=coverage 

657 ) 

658 return {"projectId": project.project_id, "workspace": str(resolved.workspace_root), **report} 

659 

660 

661def certification_of(services: EngineServices, execution_id: str) -> CertificationRecord | None: 

662 records = services.state.list("certification", CertificationRecord, execution_id=execution_id) 

663 return max(records, key=lambda item: item.created_at) if records else None 

664 

665 

666__all__ = [ 

667 "attach_evidence", 

668 "brief_sections", 

669 "certification_of", 

670 "config_lint", 

671 "confirm_contract", 

672 "contract_state", 

673 "decide_preflight", 

674 "inbox_entries", 

675 "not_verified_lines", 

676 "verification_state", 

677]