Coverage for src/governed_harness/application/service.py: 91%

979 statements  

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

1from __future__ import annotations 

2 

3import json 

4import os 

5import shutil 

6import sys 

7from collections.abc import Iterator 

8from contextlib import contextmanager 

9from datetime import UTC, datetime 

10from pathlib import Path 

11from typing import Any 

12 

13from governed_harness import __version__ 

14from governed_harness.configuration import ( 

15 ConfigurationResolver, 

16 GovernanceConfig, 

17 RuntimeConfig, 

18 initialize_project, 

19) 

20from governed_harness.configuration.declared import declared_settings_report 

21from governed_harness.configuration.loader import find_project_config, load_yaml 

22from governed_harness.configuration.models import ProjectConfiguration, PublisherConfig 

23from governed_harness.delivery.approval import verify_approval 

24from governed_harness.delivery.bundle import export_bundle, verify_bundle 

25from governed_harness.delivery.publisher import ( 

26 GitHubPublisher, 

27 Transport, 

28 render_brief_markdown, 

29 transport_for, 

30) 

31from governed_harness.delivery.vcs import Git, repository_from_remote 

32from governed_harness.domain.actors import ( 

33 DEFAULT_CLI_ACTOR, 

34 IdentitySource, 

35 actor_id_from_identity, 

36 identity_display_name, 

37 require_human_actor, 

38) 

39from governed_harness.domain.enums import ( 

40 ActorType, 

41 DecisionKind, 

42 MemoryLevel, 

43 PhaseId, 

44 RecommendationDecision, 

45 ResultStatus, 

46) 

47from governed_harness.domain.errors import ( 

48 ConfigurationError, 

49 HarnessError, 

50 IntegrityError, 

51 NotFoundError, 

52 PolicyViolationError, 

53) 

54from governed_harness.domain.ids import new_id 

55from governed_harness.domain.models import ( 

56 Actor, 

57 ClarificationRecord, 

58 ClarificationRequest, 

59 Execution, 

60 Finding, 

61 GateEvaluation, 

62 HumanDecision, 

63 MemoryRecord, 

64 OutcomeRecord, 

65 PhaseExecution, 

66 Provenance, 

67 Retrospective, 

68 RetrospectiveTrigger, 

69 Task, 

70 ValidationResult, 

71 utc_now, 

72) 

73from governed_harness.forges import render_code_quality 

74from governed_harness.intake import task_digest 

75from governed_harness.memory import APPROVAL_REQUIRED, MemoryStore 

76from governed_harness.orchestration.acceptance_dispute import DisputeDecision 

77from governed_harness.orchestration.engine import EngineServices, RunEngine, run_is_open 

78from governed_harness.orchestration.gate_contract import run_check 

79from governed_harness.orchestration.retention import RetentionCollector 

80from governed_harness.orchestration.verification import RunVerifier 

81from governed_harness.profiles import detect_profiles 

82from governed_harness.reporting import TraceReporter 

83from governed_harness.runtime import GitAdapter 

84from governed_harness.runtime.lease import WorkspaceLease, interruptible 

85from governed_harness.runtime.process_runner import resolve_executable 

86from governed_harness.telemetry import MetricsProjector 

87 

88from .agent_contract import agent_calls 

89from .agent_results import ( 

90 acceptance_state, 

91 agent_results_summary, 

92 budget_state, 

93 decide_acceptance, 

94 decide_acceptance_dispute, 

95 decide_plan, 

96 parse_change_requests, 

97 plan_state, 

98 quarantine_run, 

99 raise_budget, 

100 routing_calibration, 

101) 

102from .clarification_loader import load_clarification_file 

103from .engineering import ( 

104 architecture_report, 

105 decide_architecture, 

106 engineering_summary, 

107 project_report, 

108 refresh_architecture, 

109 standards_report, 

110) 

111from .exceptions import ( 

112 ExceptionOptions, 

113 brief_exceptions, 

114 list_exceptions, 

115 parse_expiry, 

116 parse_scope, 

117 record_exception, 

118) 

119from .forges import create_on_forge, forge_report, publish_on_forge, status_on_forge 

120from .friction import ( 

121 BatchItem, 

122 decide_plan_checkpoint, 

123 friction_summary, 

124 latest_intent_run, 

125 open_questions, 

126 preauthorize_run, 

127 run_summary, 

128 task_from_text, 

129) 

130from .friction import plan_state as checkpoint_state 

131from .health import list_outcomes, record_outcome, rule_health 

132from .hints import default_hint 

133from .isolation import ( 

134 cleanup_worktree, 

135 isolation_record, 

136 retry_isolation, 

137 start_isolated, 

138) 

139from .ladder import ( 

140 attach_evidence, 

141 config_lint, 

142 confirm_contract, 

143 decide_preflight, 

144 inbox_entries, 

145 verification_state, 

146) 

147from .notifications import inbox, notify, notify_transition 

148from .onboarding import ( 

149 EXAMPLE_TASK_NAME, 

150 GITIGNORE_FILE, 

151 IgnoreFile, 

152 ensure_ignored, 

153 git_identity, 

154 provider_checks, 

155 repository_checks, 

156 sandbox_check, 

157 validator_checks, 

158 write_example_task, 

159) 

160from .review import build_brief 

161from .review_code import ReviewCodeCommands 

162from .task_loader import load_task_file 

163from .waits import waiting_entries 

164 

165 

166def _dumped(model: Any) -> dict[str, Any] | None: 

167 """A settings model as JSON with its aliases, ``None`` when it is absent.""" 

168 return model.model_dump(mode="json", by_alias=True) if model else None 

169 

170 

171def _ladder_summary(ladder: Any) -> dict[str, Any]: 

172 return { 

173 "mode": (ladder.mode if ladder else None) or "off", 

174 "defaultLevel": ladder.required_default.value if ladder else None, 

175 "deferredExpiryDays": ladder.expiry_days if ladder else None, 

176 "preflight": bool(ladder and ladder.preflight), 

177 "capabilityDetection": bool(ladder and ladder.capability_detection), 

178 } 

179 

180 

181def _state_dir_check(project: Any, workspace: Path) -> dict[str, Any]: 

182 """Whether the run registry's directory (or its nearest existing parent) is writable.""" 

183 from governed_harness.runtime.state_location import resolve_state_location 

184 

185 location = resolve_state_location( 

186 workspace, project.project_id, project.runtime.state_dir, create=False 

187 ) 

188 root = location.root 

189 existing = next((item for item in (root, *root.parents) if item.exists()), Path(root.anchor)) 

190 writable = os.access(existing, os.W_OK) 

191 check: dict[str, Any] = {"status": "PASSED" if writable else "FAILED", "path": str(root)} 

192 if not writable: 

193 check["hint"] = f"Make {root} writable, or set runtime.stateDir." 

194 return check 

195 

196 

197def _path_length_check(project: Any, workspace: Path) -> dict[str, Any]: 

198 """Windows without long path support: whether the artifact files of the state directory 

199 stay under the path limit (a long one made ``run start`` die with a raw error).""" 

200 from governed_harness.evidence.artifact_store import ( 

201 artifact_path_too_long, 

202 path_too_long_message, 

203 ) 

204 from governed_harness.runtime.state_location import resolve_state_location 

205 

206 location = resolve_state_location( 

207 workspace, project.project_id, project.runtime.state_dir, create=False 

208 ) 

209 root = location.artifacts 

210 if not artifact_path_too_long(root): 

211 return {"status": "PASSED", "path": str(root), "length": len(str(root))} 

212 return { 

213 "status": "FAILED", 

214 "path": str(root), 

215 "length": len(str(root)), 

216 "message": path_too_long_message(root), 

217 "hint": "Set runtime.stateDir to a short path (for example C:\\h\\state) or enable " 

218 "Windows long paths, then run harness doctor again.", 

219 } 

220 

221 

222def _hooks_install_check(command: tuple[str, ...], workspace: Path) -> dict[str, Any]: 

223 """``harness doctor --install-hooks``: run the project's declared hook installation.""" 

224 import subprocess # nosec B404 - runs the project's declared hook installer 

225 

226 completed = subprocess.run( # nosec B603 - the project's own declared command 

227 [resolve_executable(command[0]), *command[1:]], 

228 cwd=workspace, 

229 capture_output=True, 

230 check=False, 

231 timeout=600, 

232 stdin=subprocess.DEVNULL, 

233 ) 

234 return { 

235 "status": "PASSED" if completed.returncode == 0 else "FAILED", 

236 "command": list(command), 

237 "message": completed.stderr.decode("utf-8", "replace").strip()[-300:], 

238 } 

239 

240 

241def _environment_check(environment: Any, workspace: Path) -> dict[str, Any]: 

242 from governed_harness.orchestration.ladder_environment import environment_checks 

243 

244 report = environment_checks(environment, workspace) 

245 problems = report["problems"] 

246 check: dict[str, Any] = { 

247 "status": "FAILED" if problems else "PASSED", 

248 "message": "; ".join(problems[:3]) if problems else None, 

249 "tools": report["tools"], 

250 "variables": report["variables"], 

251 "gitHooks": report["gitHooks"], 

252 "dirtyTree": report["dirtyTree"], 

253 } 

254 if problems: 254 ↛ 260line 254 didn't jump to line 260 because the condition on line 254 was always true

255 check["hint"] = ( 

256 "Install the tools and set the variables the project declares in " 

257 "environment; `harness doctor --install-hooks` runs the declared hook " 

258 "installation." 

259 ) 

260 return check 

261 

262 

263def _instructions_check(resolved: Any) -> dict[str, Any]: 

264 from governed_harness.application.ladder import config_lint 

265 

266 lint = config_lint(resolved) 

267 check: dict[str, Any] = { 

268 "status": "PASSED" if lint["status"] == "PASSED" else "WARNING", 

269 "message": f"{len(lint['issues'])} issue(s) in {len(lint['files'])} file(s)", 

270 } 

271 if lint["issues"]: 

272 check["hint"] = "`harness config lint` lists them." 

273 return check 

274 

275 

276class HarnessApplication(ReviewCodeCommands): 

277 def __init__(self) -> None: 

278 self.notices: list[str] = [] 

279 """Warnings for the person (the CLI prints them on standard error).""" 

280 self.last_identity_source: IdentitySource = "default" 

281 

282 def init( 

283 self, 

284 path: Path, 

285 *, 

286 force: bool = False, 

287 gitignore: bool = False, 

288 example_task: bool = False, 

289 agent_skills: bool = False, 

290 ignore_file: IgnoreFile = IgnoreFile.EXCLUDE, 

291 ) -> dict[str, Any]: 

292 """Write .harness/project.yaml. The CLI also asks for the ignore entry and the example 

293 task (``gitignore``/``example_task``); the Python API leaves the workspace untouched 

294 beyond .harness/ unless asked. The entry goes to the repository's ``info/exclude`` 

295 (``ignore_file``, #86: the tree of an existing repository stays clean), or to the 

296 ``.gitignore`` outside a Git repository or with ``IgnoreFile.GITIGNORE``. 

297 ``agent_skills`` (#56) also writes the skill of the governed flow for Claude Code and 

298 Codex.""" 

299 config = initialize_project(path, force=force) 

300 workspace = config.parent.parent 

301 skills: list[dict[str, str]] | None = None 

302 if agent_skills: 

303 from governed_harness.embedded.skills import write_agent_skills 

304 

305 skills = write_agent_skills(workspace, force=force) 

306 detections = [item for item in detect_profiles(workspace) if item.confidence > 0] 

307 result: dict[str, Any] = { 

308 "status": "PASSED", 

309 "configuration": str(config), 

310 "profiles": [ 

311 {"profileId": item.profile_id, "confidence": item.confidence} for item in detections 

312 ], 

313 } 

314 if gitignore: 

315 ignore = ensure_ignored(workspace, ignore_file) 

316 result["ignore"] = ignore 

317 if ignore["file"] == GITIGNORE_FILE: 

318 result["gitignore"] = ignore["status"] 

319 if skills is not None: 

320 result["agentSkills"] = skills 

321 example: Path | None = None 

322 if example_task: 

323 example = write_example_task( 

324 config.parent, [item.technology for item in detections], force=force 

325 ) 

326 result["exampleTask"] = str(example) if example else None 

327 task_file = f".harness/{EXAMPLE_TASK_NAME}" if example or example_task else "task.yaml" 

328 result["next"] = [ 

329 "harness doctor --path .", 

330 f"harness task create --file {task_file} (after editing it)", 

331 "harness run start --task <taskId>", 

332 ] 

333 return result 

334 

335 def inspect(self, path: Path) -> dict[str, Any]: 

336 workspace = path.resolve(strict=True) 

337 detections = detect_profiles(workspace) 

338 return { 

339 "workspace": str(workspace), 

340 "detections": [ 

341 { 

342 "profileId": item.profile_id, 

343 "technology": item.technology, 

344 "confidence": item.confidence, 

345 "evidence": list(item.evidence), 

346 "warnings": list(item.warnings), 

347 } 

348 for item in detections 

349 if item.confidence > 0 

350 ], 

351 } 

352 

353 def validate_config(self, path: Path) -> dict[str, Any]: 

354 """The resolved configuration, the settings that are declared but not applied 

355 (``declarative``) and a warning for each one this project relies on.""" 

356 resolved = ConfigurationResolver().resolve(path) 

357 declarative, warnings = declared_settings_report( 

358 resolved, load_yaml(find_project_config(path)) 

359 ) 

360 return { 

361 "status": "PASSED", 

362 "projectId": resolved.project.project_id, 

363 "workspace": str(resolved.workspace_root), 

364 "profiles": [item.profile_id for item in resolved.profiles], 

365 "workflow": resolved.workflow.workflow_id, 

366 "validators": [item.validator_id for item in resolved.effective_validators], 

367 "capabilities": [ 

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

369 for item in resolved.effective_capabilities 

370 ], 

371 "policies": resolved.effective_policies, 

372 "intake": self._intake_settings(resolved.project), 

373 "verification": self._verification(resolved.project), 

374 "review": self._review(resolved.project), 

375 "agentSandbox": { 

376 "mode": resolved.project.runtime.effective_agent_sandbox, 

377 "writePaths": list(resolved.project.runtime.sandbox_write_paths or ()), 

378 }, 

379 "feedbackLoop": self._feedback_loop(resolved.project.runtime), 

380 "governance": self._governance(resolved.project.governance_settings), 

381 "agentResults": agent_results_summary(resolved.project), 

382 **self._wave4_settings(resolved), 

383 "ladder": self._ladder_settings(resolved), 

384 "engineering": engineering_summary(resolved), 

385 "friction": friction_summary(resolved.project), 

386 "api": self._api_settings(resolved.project), 

387 "declarative": declarative, 

388 "warnings": warnings, 

389 } 

390 

391 @staticmethod 

392 def _api_settings(project: ProjectConfiguration) -> dict[str, Any]: 

393 """Effective ``harness api serve`` authentication (#18): variable names and whether 

394 they are set, never a token.""" 

395 settings = project.api_settings 

396 if not settings.enabled: 

397 return {"auth": "off"} 

398 return { 

399 "auth": "token", 

400 "tokenEnv": settings.start_token_env, 

401 "tokenSet": bool(os.environ.get(settings.start_token_env)), 

402 "tokenUser": settings.start_user, 

403 "tokenRole": settings.start_role, 

404 "users": [ 

405 { 

406 "id": user.user_id, 

407 "role": user.role, 

408 "tokenEnv": user.token_env, 

409 "tokenSet": bool(os.environ.get(user.token_env)), 

410 } 

411 for user in settings.users or () 

412 ], 

413 } 

414 

415 @staticmethod 

416 def _wave4_settings(resolved: Any) -> dict[str, Any]: 

417 """Effective workspace, toolchain, provenance and delivery settings (since 2.0; 

418 absent keys resolve to the 1.0.0 behaviour).""" 

419 project = resolved.project 

420 workspace = project.workspace 

421 toolchain = project.toolchain_settings 

422 provenance = project.provenance_settings 

423 delivery = project.delivery_settings 

424 return { 

425 "snapshots": { 

426 "snapshot": workspace.snapshot or "walk", 

427 "baseline": workspace.baseline or "text", 

428 "snapshotCache": bool(workspace.snapshot_cache), 

429 }, 

430 "toolchain": { 

431 "profileDetection": toolchain.profile_detection or "best", 

432 "interpreter": toolchain.interpreter or "system", 

433 "projectProfiles": [ 

434 item for item in resolved.source_files if not item.startswith("builtin:") 

435 ][1:], 

436 "commands": { 

437 item.validator_id: list(item.command or ()) 

438 for item in resolved.effective_validators 

439 }, 

440 }, 

441 "provenance": { 

442 "agentSnapshots": bool(provenance.agent_snapshots), 

443 "selfReport": bool(provenance.self_report), 

444 }, 

445 "delivery": { 

446 "closureCommit": delivery.mode, 

447 "branch": delivery.branch_template if delivery.mode == "branch" else None, 

448 }, 

449 } 

450 

451 @staticmethod 

452 def _ladder_settings(resolved: Any) -> dict[str, Any]: 

453 """Effective settings of the verification ladder and delivery hygiene (#55; absent 

454 keys resolve to the earlier behaviour).""" 

455 from governed_harness.runtime.state_location import resolve_state_location 

456 

457 project = resolved.project 

458 verification = project.verification 

459 ladder = verification.ladder if verification else None 

460 mutation = verification.mutation if verification else None 

461 intake = project.intake 

462 delivery = project.delivery_settings 

463 isolation = project.workspace.isolation 

464 location = resolve_state_location( 

465 resolved.workspace_root, project.project_id, project.runtime.state_dir, create=False 

466 ) 

467 context = project.context 

468 return { 

469 "ladder": _ladder_summary(ladder), 

470 "probes": [ 

471 item.probe_id for item in (verification.probes if verification else None) or () 

472 ], 

473 "mutation": (mutation.mode if mutation else None) or "off", 

474 "manualChecklist": bool(project.review and project.review.manual_checklist), 

475 "operationalContract": (intake.operational_contract if intake else None) or "off", 

476 "interruptions": _dumped(intake.interruptions if intake else None), 

477 "isolation": isolation.effective_mode if isolation else "none", 

478 "environment": _dumped(project.environment), 

479 "locate": bool(context and context.locate and context.locate.enabled), 

480 "delivery": { 

481 "stage": bool(delivery.stage), 

482 "push": bool(delivery.push), 

483 "pullRequest": bool(delivery.pull_request and delivery.pull_request.create), 

484 "comment": delivery.comment or "never", 

485 }, 

486 "state": { 

487 "stateDir": project.runtime.state_dir, 

488 "database": str(location.database), 

489 "external": location.external, 

490 }, 

491 } 

492 

493 @staticmethod 

494 def _governance(settings: GovernanceConfig) -> dict[str, Any]: 

495 """Effective governance settings (absent keys resolve to the 1.0.0 behaviour).""" 

496 return { 

497 "deciderIdentity": settings.decider_identity or "default", 

498 "confirmDecisionDigest": bool(settings.confirm_decision_digest), 

499 "trustedHosts": list(settings.trusted_hosts) if settings.trusted_hosts else None, 

500 "verifyRecords": bool(settings.verify_records), 

501 "chainAnchor": settings.chain_anchor or "off", 

502 "pinTaskRevision": bool(settings.pin_task_revision), 

503 "protectExcludedPaths": bool(settings.protect_excluded_paths), 

504 "workspaceLease": bool(settings.workspace_lease), 

505 "applyWorkflowSettings": bool(settings.apply_workflow_settings), 

506 "decisionExpiryHours": settings.decision_expiry_hours, 

507 "applyProfilePolicies": bool(settings.apply_profile_policies), 

508 "applyNetworkPolicy": bool(settings.apply_network_policy), 

509 } 

510 

511 @staticmethod 

512 def _intake_settings(project: ProjectConfiguration) -> dict[str, Any]: 

513 value: dict[str, Any] = {"criteriaPolicy": project.criteria_policy} 

514 if project.intake is not None and project.intake.language is not None: 

515 value["language"] = project.intake.language 

516 return value 

517 

518 @staticmethod 

519 def _verification(project: ProjectConfiguration) -> dict[str, Any]: 

520 value: dict[str, Any] = {"requirementTraceability": project.requirement_traceability} 

521 if project.output_parsers_enabled: 521 ↛ 523line 521 didn't jump to line 523 because the condition on line 521 was always true

522 value["outputParsers"] = True 

523 return value 

524 

525 @staticmethod 

526 def _review(project: ProjectConfiguration) -> dict[str, Any]: 

527 """Effective review settings; the URLs of webhooks are never printed.""" 

528 return { 

529 "exceptions": project.exceptions_enabled, 

530 "exceptionDays": project.exception_days if project.exceptions_enabled else None, 

531 "causalRetrospective": project.causal_retrospective, 

532 "webhooks": [ 

533 { 

534 "target": f"env:{item.url_env}" if item.url_env else "url", 

535 "events": list(item.events), 

536 "retries": item.retries, 

537 } 

538 for item in project.webhooks 

539 ], 

540 } 

541 

542 @staticmethod 

543 def _feedback_loop(runtime: RuntimeConfig) -> dict[str, Any]: 

544 """Effective values of the provider feedback loop (absent keys resolve to 'off').""" 

545 return { 

546 "verificationCorrections": runtime.correction_limit, 

547 "providerFeedback": runtime.feedback_enabled, 

548 "unsupportedClaimCheck": runtime.claim_check_enabled, 

549 "unsupportedClaimSeverity": runtime.claim_severity.value, 

550 "providerRetries": runtime.retry_limit, 

551 "providerRetryDelaySeconds": runtime.retry_delay_seconds, 

552 "providerTransientPatterns": list(runtime.transient_patterns), 

553 } 

554 

555 def create_task(self, path: Path, source: Path) -> Task: 

556 with self._services(path) as services: 

557 project = services.resolved.project 

558 task = load_task_file( 

559 source, project_id=project.project_id, criteria_policy=project.criteria_policy 

560 ) 

561 if project.governance_settings.pin_task_revision: 

562 open_runs = [ 

563 item.execution_id 

564 for item in services.state.list( 

565 "execution", Execution, project_id=project.project_id 

566 ) 

567 if item.task_id == task.task_id and run_is_open(item) 

568 ] 

569 if open_runs: 

570 raise PolicyViolationError( 

571 f"task {task.task_id} has open run(s) {', '.join(open_runs)}; its task " 

572 "cannot be replaced while they run. Create the task under a new id, " 

573 "cancel the run, or revise it with harness task clarify during INTENT" 

574 ) 

575 services.state.put( 

576 "task", 

577 task.task_id, 

578 task, 

579 project_id=task.project_id, 

580 ) 

581 return task 

582 

583 def list_tasks(self, path: Path) -> list[Task]: 

584 with self._services(path) as services: 

585 return services.state.list( 

586 "task", Task, project_id=services.resolved.project.project_id, newest_first=True 

587 ) 

588 

589 def get_task(self, path: Path, task_id: str) -> Task: 

590 with self._services(path) as services: 

591 return services.state.get("task", task_id, Task) 

592 

593 def clarify_task( 

594 self, 

595 path: Path, 

596 *, 

597 task_id: str, 

598 answers_file: Path, 

599 actor_id: str | None = None, 

600 actor_type: ActorType = ActorType.HUMAN, 

601 relayed: bool = False, 

602 ) -> dict[str, Any]: 

603 """Answer the clarification questions INTENT asked about a task. 

604 

605 ``relayed`` (embedded mode, #56): the person's answers reached the harness through an 

606 agent session (the MCP server); the record names the person and says so. 

607 

608 The answers file maps question ids to answers and may replace criteria, add criteria 

609 and add requirements. The harness stores the revised task and a clarification record 

610 (actor, questions, answers, previous and new task digest) on the event chain of the 

611 run that asked; ``continue_run`` then assesses the revised task in INTENT. 

612 

613 Only a human actor may answer. Unknown question ids and empty answers are rejected 

614 (exit code 2), as is a task with a run past INTENT (exit code 5).""" 

615 clarification = load_clarification_file(answers_file) 

616 with self._services(path) as services: 

617 decider, display_name = self._decider(services, actor_id) 

618 if relayed: 

619 display_name = f"{display_name or decider} (relayed by an agent session)" 

620 with self._leased(services, "task clarify"): 

621 record, task = RunEngine(services).clarify( 

622 task_id=task_id, 

623 clarification=clarification, 

624 actor=Actor(actor_type=actor_type, actor_id=decider, display_name=display_name), 

625 ) 

626 return { 

627 "clarification": record.model_dump(mode="json", by_alias=True), 

628 "task": task.model_dump(mode="json", by_alias=True), 

629 "next": f"harness run continue --run {record.execution_id}", 

630 } 

631 

632 def list_clarifications(self, path: Path, task_id: str) -> dict[str, Any]: 

633 """The clarification requests asked about a task, the answers recorded for them and 

634 the open request: the latest one asked about the current revision of the task.""" 

635 with self._services(path) as services: 

636 task = services.state.get("task", task_id, Task) 

637 requests = sorted( 

638 ( 

639 item 

640 for item in services.state.list( 

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

642 ) 

643 if item.task_id == task_id 

644 ), 

645 key=lambda item: item.created_at, 

646 ) 

647 current = task_digest(task) 

648 open_requests = [item for item in requests if item.task_digest == current] 

649 records = [ 

650 item 

651 for item in services.state.list( 

652 "clarification", ClarificationRecord, project_id=task.project_id 

653 ) 

654 if item.task_id == task_id 

655 ] 

656 return { 

657 "taskId": task_id, 

658 "taskDigest": current, 

659 "openRequest": open_requests[-1].model_dump(mode="json", by_alias=True) 

660 if open_requests 

661 else None, 

662 "requests": [item.model_dump(mode="json", by_alias=True) for item in requests], 

663 "clarifications": [ 

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

665 for item in sorted(records, key=lambda item: item.recorded_at) 

666 ], 

667 } 

668 

669 def start_run( 

670 self, 

671 path: Path, 

672 task_id: str, 

673 provider: str | None = None, 

674 *, 

675 isolate: str | None = None, 

676 ) -> Execution: 

677 """Create a run and execute the phases. With ``isolate`` ``worktree`` (or 

678 ``workspace.isolation.mode: worktree``) the run happens in a Git worktree of its own on a 

679 new branch (#55).""" 

680 from governed_harness.configuration.ladder import IsolationConfig 

681 

682 if isolate not in {None, "none", "worktree"}: 682 ↛ 683line 682 didn't jump to line 683 because the condition on line 682 was never true

683 raise ConfigurationError(f"--isolate is none or worktree, got {isolate!r}") 

684 with self._services(path) as services: 

685 settings = services.resolved.project.workspace.isolation 

686 mode = isolate or (settings.effective_mode if settings else "none") 

687 if mode == "worktree": 

688 engine = RunEngine(services) 

689 task = engine.get_task(task_id) 

690 execution, isolated = start_isolated( 

691 self._open_services, 

692 services, 

693 task, 

694 provider, 

695 settings or IsolationConfig(mode="worktree"), 

696 ) 

697 if isolated is None: 

698 return execution 

699 try: 

700 with self._leased(isolated, "run start") as lease: 

701 if lease is not None: 701 ↛ 703line 701 didn't jump to line 703 because the condition on line 701 was always true

702 lease.bind(execution.execution_id) 

703 result = RunEngine(isolated).continue_execution(execution.execution_id) 

704 return self._after(isolated, result) 

705 finally: 

706 isolated.close() 

707 with self._services(path) as services, self._leased(services, "run start") as lease: 

708 engine = RunEngine(services) 

709 task = engine.get_task(task_id) 

710 execution = engine.create_execution(task, provider=provider) 

711 if lease is not None: 

712 lease.bind(execution.execution_id) 

713 return self._after(services, engine.continue_execution(execution.execution_id)) 

714 

715 def continue_run(self, path: Path, execution_id: str) -> Execution: 

716 with self._run_services(path, execution_id) as (services, execution_id): 

717 record = isolation_record(services, execution_id) 

718 if record is not None and record.get("status") == "COLLISION": 

719 # The run waits for its worktree (#55): try again. 

720 execution, isolated = retry_isolation( 

721 self._open_services, 

722 services, 

723 services.state.get("execution", execution_id, Execution), 

724 ) 

725 if isolated is None: 725 ↛ 726line 725 didn't jump to line 726 because the condition on line 725 was never true

726 return execution 

727 try: 

728 with self._leased(isolated, "run continue") as lease: 

729 if lease is not None: 729 ↛ 731line 729 didn't jump to line 731 because the condition on line 729 was always true

730 lease.bind(execution_id) 

731 result = RunEngine(isolated).continue_execution(execution_id) 

732 return self._after(isolated, result) 

733 finally: 

734 isolated.close() 

735 with self._leased(services, "run continue") as lease: 

736 if lease is not None: 736 ↛ 738line 736 didn't jump to line 738 because the condition on line 736 was always true

737 lease.bind(execution_id) 

738 return self._after(services, RunEngine(services).continue_execution(execution_id)) 

739 

740 def cancel_run(self, path: Path, execution_id: str, actor_id: str | None = None) -> Execution: 

741 with self._run_services(path, execution_id) as (services, execution_id): 

742 decider = self._decider(services, actor_id)[0] 

743 return self._after(services, RunEngine(services).cancel(execution_id, decider)) 

744 

745 def cleanup_run(self, path: Path, execution_id: str) -> dict[str, Any]: 

746 """Remove the worktree of a finished isolated run (never its branch, #55).""" 

747 with self._services(path) as services: 

748 run_id = self._run_id(services, execution_id) 

749 return cleanup_worktree(services, services.state.get("execution", run_id, Execution)) 

750 

751 # ----- the verification ladder (#55) ----------------------------------------------------- 

752 def verification(self, path: Path, execution_id: str) -> dict[str, Any]: 

753 """The verification plan, preflight, certification, deferred items and checklist of a 

754 run.""" 

755 with self._services(path) as services: 

756 return verification_state(services, self._run_id(services, execution_id)) 

757 

758 def decide_verification( 

759 self, 

760 path: Path, 

761 *, 

762 execution_id: str, 

763 rationale: str, 

764 actor_id: str | None = None, 

765 continue_after: bool = True, 

766 ) -> dict[str, Any]: 

767 """A person decides to continue a run whose preflight is UNAVAILABLE, uncertified for 

768 what cannot be verified here.""" 

769 with self._run_services(path, execution_id) as (services, execution_id): 

770 decider, display_name = self._decider(services, actor_id) 

771 require_human_actor(decider, "continue a run uncertified") 

772 actor = Actor(actor_type=ActorType.HUMAN, actor_id=decider, display_name=display_name) 

773 with self._leased(services, "verification decide") as lease: 

774 if lease is not None: 774 ↛ 776line 774 didn't jump to line 776 because the condition on line 774 was always true

775 lease.bind(execution_id) 

776 decision = decide_preflight( 

777 services, execution_id, actor=actor, rationale=rationale 

778 ) 

779 result: dict[str, Any] = {"decision": decision} 

780 if continue_after: 780 ↛ 785line 780 didn't jump to line 785 because the condition on line 780 was always true

781 execution = self._after( 

782 services, RunEngine(services).continue_execution(execution_id) 

783 ) 

784 result["execution"] = execution.model_dump(mode="json", by_alias=True) 

785 return result 

786 

787 def confirm_contract( 

788 self, 

789 path: Path, 

790 *, 

791 task_id: str, 

792 digest: str, 

793 actor_id: str | None = None, 

794 pre_approve: bool = False, 

795 hours: int | None = None, 

796 rationale: str = "", 

797 ) -> dict[str, Any]: 

798 """A person confirms the operational contract of a task's revision (#55) and, with 

799 ``pre_approve`` (``friction.preAuthorization``, #58), approves the run in advance under 

800 the condition gate passed, no risk factor, size S, until ``hours`` from now.""" 

801 with self._services(path) as services: 

802 decider, display_name = self._decider(services, actor_id) 

803 require_human_actor(decider, "confirm the operational contract") 

804 actor = Actor(actor_type=ActorType.HUMAN, actor_id=decider, display_name=display_name) 

805 if not pre_approve: 

806 return confirm_contract(services, task_id=task_id, digest=digest, actor=actor) 

807 execution = latest_intent_run(services, task_id) 

808 engine = RunEngine(services) 

809 current = engine.friction.contract_digest(execution, engine.run_task(execution)) 

810 if current != digest: 

811 raise PolicyViolationError( 

812 f"the digest does not match the current contract ({current})" 

813 ) 

814 with self._leased(services, "task confirm") as lease: 

815 if lease is not None: 815 ↛ 817line 815 didn't jump to line 817 because the condition on line 815 was always true

816 lease.bind(execution.execution_id) 

817 record = preauthorize_run( 

818 services, 

819 execution, 

820 actor, 

821 hours=hours, 

822 rationale=rationale, 

823 identity_source=self._identity_source(services), 

824 with_contract=True, 

825 ) 

826 return { 

827 "executionId": execution.execution_id, 

828 "digest": digest, 

829 "actorId": decider, 

830 "preAuthorization": record, 

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

832 } 

833 

834 def _identity_source(self, services: EngineServices) -> str | None: 

835 settings = services.resolved.project.governance_settings 

836 return self.last_identity_source if settings.git_decider else None 

837 

838 def attach_evidence( 

839 self, 

840 path: Path, 

841 *, 

842 file: Path, 

843 execution_id: str | None = None, 

844 task_id: str | None = None, 

845 item: str | None = None, 

846 manual: bool = False, 

847 evidence_format: str = "auto", 

848 case: str | None = None, 

849 commit: str | None = None, 

850 note: str | None = None, 

851 actor_id: str | None = None, 

852 ) -> dict[str, Any]: 

853 """Close a deferred verification with external evidence, or attach a person's evidence 

854 to a run (checklist) or a task (intake context) (#55).""" 

855 with self._services(path) as services: 

856 decider, display_name = self._decider(services, actor_id) 

857 require_human_actor(decider, "attach evidence") 

858 actor = Actor(actor_type=ActorType.HUMAN, actor_id=decider, display_name=display_name) 

859 run_id = self._run_id(services, execution_id) if execution_id else None 

860 return attach_evidence( 

861 services, 

862 file=file, 

863 actor=actor, 

864 execution_id=run_id, 

865 task_id=task_id, 

866 item=item, 

867 manual=manual, 

868 evidence_format=evidence_format, 

869 case=case, 

870 commit=commit, 

871 note=note, 

872 ) 

873 

874 def config_lint(self, path: Path) -> dict[str, Any]: 

875 """Contradictions between the configuration and the agent instruction files (#55).""" 

876 return config_lint(ConfigurationResolver().resolve(path)) 

877 

878 def registry(self) -> dict[str, Any]: 

879 """The projects whose run registry lives in the state directory (``runtime.stateDir: 

880 auto``), with their latest runs: one dashboard for several repositories (#55).""" 

881 from governed_harness.runtime.state_location import default_state_root, registered_projects 

882 from governed_harness.storage import SQLiteStateStore 

883 

884 projects = [] 

885 for entry in registered_projects(): 

886 database = Path(entry["database"]) 

887 runs: list[dict[str, Any]] = [] 

888 if database.is_file(): 888 ↛ 901line 888 didn't jump to line 901 because the condition on line 888 was always true

889 with SQLiteStateStore(database) as store: 

890 executions = store.list("execution", Execution, newest_first=True) 

891 runs = [ 

892 { 

893 "executionId": item.execution_id, 

894 "taskId": item.task_id, 

895 "status": item.status.value, 

896 "currentPhase": item.current_phase.value, 

897 "updatedAt": item.updated_at.isoformat(), 

898 } 

899 for item in executions[:20] 

900 ] 

901 projects.append({**entry, "runs": runs}) 

902 return {"stateRoot": str(default_state_root()), "projects": projects} 

903 

904 def routing_calibration(self, path: Path) -> dict[str, Any]: 

905 """Cost per approved task of the routing decisions recorded in the project (#44).""" 

906 with self._services(path) as services: 

907 return routing_calibration(services) 

908 

909 def agent_calls( 

910 self, path: Path, execution_id: str, kind: str | None = None, iteration: int | None = None 

911 ) -> dict[str, Any]: 

912 """The agent calls of a run, the iterations each agent used and, for one call, exactly 

913 what was sent and what the parent received (#97).""" 

914 with self._services(path) as services: 

915 return agent_calls(services, self._run_id(services, execution_id), kind, iteration) 

916 

917 def budget(self, path: Path, execution_id: str) -> dict[str, Any]: 

918 """Usage of a run and its task against the budget limits (#42).""" 

919 with self._services(path) as services: 

920 return budget_state(services, self._run_id(services, execution_id)) 

921 

922 def raise_budget( 

923 self, 

924 path: Path, 

925 *, 

926 execution_id: str, 

927 scope: str, 

928 metric: str, 

929 limit: float, 

930 rationale: str, 

931 actor_id: str | None = None, 

932 ) -> dict[str, Any]: 

933 """Raise a budget limit of a run (a person, recorded); ``run continue`` resumes it.""" 

934 with self._services(path) as services, self._leased(services, "budget raise"): 

935 execution_id = self._run_id(services, execution_id) 

936 decider = self._decider(services, actor_id)[0] 

937 return raise_budget( 

938 services, 

939 execution_id, 

940 scope=scope, 

941 metric=metric, 

942 limit=limit, 

943 actor_id=decider, 

944 rationale=rationale, 

945 ) 

946 

947 def acceptance(self, path: Path, execution_id: str) -> dict[str, Any]: 

948 """The acceptance tests proposed or frozen for a run (#52).""" 

949 with self._services(path) as services: 

950 return acceptance_state(services, self._run_id(services, execution_id)) 

951 

952 def decide_acceptance( 

953 self, 

954 path: Path, 

955 *, 

956 execution_id: str, 

957 decision: DecisionKind, 

958 digest: str, 

959 rationale: str, 

960 actor_id: str | None = None, 

961 continue_after: bool = True, 

962 ) -> dict[str, Any]: 

963 """Approve or reject the proposed acceptance tests (digest-bound, a person).""" 

964 with self._services(path) as services, self._leased(services, "acceptance decide") as lease: 

965 execution_id = self._run_id(services, execution_id) 

966 if lease is not None: 966 ↛ 968line 966 didn't jump to line 968 because the condition on line 966 was always true

967 lease.bind(execution_id) 

968 decider = self._decider(services, actor_id)[0] 

969 return decide_acceptance( 

970 services, 

971 execution_id, 

972 decision=decision, 

973 digest=digest, 

974 actor_id=decider, 

975 rationale=rationale, 

976 continue_after=continue_after, 

977 ) 

978 

979 def decide_acceptance_dispute( 

980 self, 

981 path: Path, 

982 *, 

983 execution_id: str, 

984 decision: DisputeDecision, 

985 digest: str, 

986 rationale: str, 

987 actor_id: str | None = None, 

988 continue_after: bool = True, 

989 ) -> dict[str, Any]: 

990 """Uphold or revise the frozen acceptance tests an agent disputes (digest-bound, a 

991 person; #94).""" 

992 with ( 

993 self._services(path) as services, 

994 self._leased(services, "acceptance dispute") as lease, 

995 ): 

996 execution_id = self._run_id(services, execution_id) 

997 if lease is not None: 997 ↛ 999line 997 didn't jump to line 999 because the condition on line 997 was always true

998 lease.bind(execution_id) 

999 decider = self._decider(services, actor_id)[0] 

1000 return decide_acceptance_dispute( 

1001 services, 

1002 execution_id, 

1003 decision=decision, 

1004 digest=digest, 

1005 actor_id=decider, 

1006 rationale=rationale, 

1007 continue_after=continue_after, 

1008 ) 

1009 

1010 def plan(self, path: Path, execution_id: str) -> dict[str, Any]: 

1011 """The decomposition of a run and the progress of its sub-tasks (#39).""" 

1012 with self._services(path) as services: 

1013 run_id = self._run_id(services, execution_id) 

1014 checkpoint = checkpoint_state(services, run_id) 

1015 try: 

1016 decomposition = plan_state(services, run_id) 

1017 except NotFoundError: 

1018 if checkpoint is None: 1018 ↛ 1019line 1018 didn't jump to line 1019 because the condition on line 1018 was never true

1019 raise 

1020 decomposition = {"executionId": run_id} 

1021 if checkpoint is None: 

1022 return decomposition 

1023 # The plan-approval checkpoint of #8 (friction.planApproval, #58). 

1024 return {**decomposition, "approval": checkpoint} 

1025 

1026 def decide_plan( 

1027 self, 

1028 path: Path, 

1029 *, 

1030 execution_id: str, 

1031 decision: DecisionKind, 

1032 digest: str, 

1033 rationale: str, 

1034 actor_id: str | None = None, 

1035 continue_after: bool = True, 

1036 ) -> dict[str, Any]: 

1037 """Approve or reject the decomposition PLANNING proposed (digest-bound, a person).""" 

1038 with self._services(path) as services, self._leased(services, "plan decide") as lease: 

1039 execution_id = self._run_id(services, execution_id) 

1040 if lease is not None: 1040 ↛ 1042line 1040 didn't jump to line 1042 because the condition on line 1040 was always true

1041 lease.bind(execution_id) 

1042 decider = self._decider(services, actor_id)[0] 

1043 checkpoint = checkpoint_state(services, execution_id) 

1044 if checkpoint is not None and checkpoint.get("status") == "PENDING": 

1045 # The plan-approval checkpoint (friction.planApproval, #8 through #58). 

1046 return decide_plan_checkpoint( 

1047 services, 

1048 execution_id, 

1049 decision=decision, 

1050 digest=digest, 

1051 actor=Actor(actor_type=ActorType.HUMAN, actor_id=decider), 

1052 rationale=rationale, 

1053 continue_after=continue_after, 

1054 ) 

1055 return decide_plan( 

1056 services, 

1057 execution_id, 

1058 decision=decision, 

1059 digest=digest, 

1060 actor_id=decider, 

1061 rationale=rationale, 

1062 continue_after=continue_after, 

1063 ) 

1064 

1065 def check(self, path: Path, execution_id: str | None = None) -> dict[str, Any]: 

1066 """``harness check``: the gate's validators and diff checks on the workspace, with 

1067 nothing recorded (it reads the configuration and the run's check state only).""" 

1068 return run_check(path, execution_id) 

1069 

1070 def quarantine_run( 

1071 self, path: Path, execution_id: str, actor_id: str | None = None 

1072 ) -> dict[str, Any]: 

1073 """Quarantine the changes of a stopped run and restore the baseline 

1074 (``governance.stopTheLine``); a person only.""" 

1075 with self._services(path) as services, self._leased(services, "run quarantine"): 

1076 execution_id = self._run_id(services, execution_id) 

1077 decider = self._decider(services, actor_id)[0] 

1078 return quarantine_run(services, execution_id, decider) 

1079 

1080 @classmethod 

1081 def _after(cls, services: EngineServices, execution: Execution) -> Execution: 

1082 """Side effects of reaching a state a person cares about: the webhooks of 

1083 ``notifications`` (a delivery failure is recorded, not raised) and, under 

1084 ``retrospective.causal``, the retrospective of a rejected or cancelled run. They never 

1085 change the run.""" 

1086 if services.resolved.project.causal_retrospective: 

1087 trigger: RetrospectiveTrigger | None = None 

1088 if execution.status is ResultStatus.CANCELLED: 

1089 trigger = "CANCELLED" 

1090 elif execution.status is ResultStatus.FAILED and execution.human_decision_id: 

1091 decision = services.state.get( 

1092 "decision", execution.human_decision_id, HumanDecision 

1093 ) 

1094 trigger = "REJECTED" if decision.decision is DecisionKind.REJECT else None 

1095 existing = services.state.list( 

1096 "retrospective", Retrospective, execution_id=execution.execution_id 

1097 ) 

1098 if trigger and not existing: 

1099 cls._generate_retrospective(services, execution.execution_id, trigger) 

1100 notify_transition(services, execution) 

1101 return execution 

1102 

1103 def rule_health(self, path: Path, *, since_days: int | None = None) -> dict[str, Any]: 

1104 """How each rule and validator behaved across the runs of the project.""" 

1105 with self._services(path) as services: 

1106 return rule_health(services, since_days) 

1107 

1108 def record_outcome( 

1109 self, 

1110 path: Path, 

1111 *, 

1112 execution_id: str, 

1113 kind: str, 

1114 summary: str, 

1115 actor_id: str | None = None, 

1116 reference: str | None = None, 

1117 observed_at: str | None = None, 

1118 ) -> OutcomeRecord: 

1119 """Link an incident, revert, hotfix or regression to a run (a person only).""" 

1120 with self._services(path) as services: 

1121 actor_id = self._decider(services, actor_id)[0] 

1122 return record_outcome( 

1123 services, 

1124 execution_id=self._run_id(services, execution_id), 

1125 kind=kind, 

1126 summary=summary, 

1127 reference=reference, 

1128 observed_at=observed_at, 

1129 actor_id=actor_id, 

1130 ) 

1131 

1132 def list_outcomes(self, path: Path, execution_id: str | None = None) -> list[OutcomeRecord]: 

1133 with self._services(path) as services: 

1134 run_id = self._run_id(services, execution_id) if execution_id else None 

1135 return list_outcomes(services, run_id) 

1136 

1137 # ----- low friction (#58) ---------------------------------------------------------------- 

1138 def do( 

1139 self, 

1140 path: Path, 

1141 text: str, 

1142 *, 

1143 criteria: tuple[str, ...] = (), 

1144 owned_paths: tuple[str, ...] = (), 

1145 title: str | None = None, 

1146 provider: str | None = None, 

1147 pre_approve: bool = False, 

1148 hours: int | None = None, 

1149 actor_id: str | None = None, 

1150 ) -> dict[str, Any]: 

1151 """``harness do``: create a task from text, run it and, with ``pre_approve``, approve it 

1152 in advance under the condition gate passed, no risk factor, size S. Returns the task, 

1153 the run, the lane and what waits for the person (questions or the decision).""" 

1154 with self._services(path) as services: 

1155 project = services.resolved.project 

1156 task = task_from_text( 

1157 text, 

1158 project_id=project.project_id, 

1159 criteria=criteria, 

1160 owned_paths=owned_paths, 

1161 title=title, 

1162 ) 

1163 services.state.put("task", task.task_id, task, project_id=task.project_id) 

1164 preauthorization: dict[str, Any] | None = None 

1165 with self._leased(services, "do") as lease: 

1166 engine = RunEngine(services) 

1167 execution = engine.create_execution(task, provider=provider) 

1168 if lease is not None: 1168 ↛ 1170line 1168 didn't jump to line 1170 because the condition on line 1168 was always true

1169 lease.bind(execution.execution_id) 

1170 if pre_approve: 1170 ↛ 1186line 1170 didn't jump to line 1186 because the condition on line 1170 was always true

1171 decider, display_name = self._decider(services, actor_id) 

1172 require_human_actor(decider, "pre-authorise an approval") 

1173 preauthorization = preauthorize_run( 

1174 services, 

1175 execution, 

1176 Actor( 

1177 actor_type=ActorType.HUMAN, 

1178 actor_id=decider, 

1179 display_name=display_name, 

1180 ), 

1181 hours=hours, 

1182 rationale="", 

1183 identity_source=self._identity_source(services), 

1184 with_contract=True, 

1185 ) 

1186 execution = self._after(services, engine.continue_execution(execution.execution_id)) 

1187 return { 

1188 "task": task.model_dump(mode="json", by_alias=True), 

1189 "execution": execution.model_dump(mode="json", by_alias=True), 

1190 "run": run_summary(execution), 

1191 "lane": RunEngine(services).friction.lane(execution), 

1192 "preAuthorization": preauthorization, 

1193 "questions": open_questions(services, execution) 

1194 if execution.current_phase is PhaseId.INTENT 

1195 else [], 

1196 } 

1197 

1198 def answer_questions( 

1199 self, 

1200 path: Path, 

1201 *, 

1202 task_id: str, 

1203 answers: dict[str, str], 

1204 actor_id: str | None = None, 

1205 ) -> dict[str, Any]: 

1206 """Answers typed on the terminal by ``harness do`` (as ``task clarify`` with a file).""" 

1207 from governed_harness.intake.clarification import ClarificationInput 

1208 

1209 with self._services(path) as services: 

1210 decider, display_name = self._decider(services, actor_id) 

1211 with self._leased(services, "task clarify"): 

1212 record, _task = RunEngine(services).clarify( 

1213 task_id=task_id, 

1214 clarification=ClarificationInput(answers=answers), 

1215 actor=Actor( 

1216 actor_type=ActorType.HUMAN, actor_id=decider, display_name=display_name 

1217 ), 

1218 ) 

1219 return {"executionId": record.execution_id, "clarificationId": record.clarification_id} 

1220 

1221 def decide_batch( 

1222 self, 

1223 path: Path, 

1224 items: list[BatchItem], 

1225 *, 

1226 rationale: str, 

1227 actor_id: str | None = None, 

1228 continue_after: bool = True, 

1229 ) -> dict[str, Any]: 

1230 """Decisions on several runs of the inbox, each bound to its own ChangeSet digest: a 

1231 stale digest or a refused decision is reported for that run and the others are still 

1232 recorded.""" 

1233 results: list[dict[str, Any]] = [] 

1234 for item in items: 

1235 reason = (item.rationale or rationale).strip() 

1236 try: 

1237 record, execution = self.decide_gate( 

1238 path, 

1239 execution_id=item.run, 

1240 decision=item.decision, 

1241 change_set_digest=item.digest, 

1242 actor_id=actor_id, 

1243 rationale=reason, 

1244 continue_after=continue_after, 

1245 acknowledged_risks=item.acknowledged_risks, 

1246 ) 

1247 except HarnessError as error: 

1248 results.append( 

1249 { 

1250 "run": item.run, 

1251 "decision": item.decision.value, 

1252 "changeSetDigest": item.digest, 

1253 "recorded": False, 

1254 "error": str(error), 

1255 "exitCode": error.exit_code, 

1256 } 

1257 ) 

1258 continue 

1259 results.append( 

1260 { 

1261 "run": execution.execution_id, 

1262 "decision": record.decision.value, 

1263 "changeSetDigest": record.change_set_digest, 

1264 "recorded": True, 

1265 "decisionId": record.decision_id, 

1266 "execution": run_summary(execution), 

1267 } 

1268 ) 

1269 return { 

1270 "recorded": sum(1 for item in results if item["recorded"]), 

1271 "refused": sum(1 for item in results if not item["recorded"]), 

1272 "results": results, 

1273 } 

1274 

1275 def metrics( 

1276 self, 

1277 path: Path, 

1278 *, 

1279 filters: Any, 

1280 prices_file: Path | None = None, 

1281 narrative: bool = False, 

1282 ) -> tuple[dict[str, Any], dict[str, Any]]: 

1283 """``harness metrics``: the report (zero model calls) and its settings; with 

1284 ``narrative`` one call to ``metrics.narrative.command``, on demand.""" 

1285 from .metrics import metrics_report, narrative_settings, run_narrative 

1286 

1287 report, settings = metrics_report(path, filters=filters, prices_file=prices_file) 

1288 if narrative: 

1289 command = narrative_settings(settings) 

1290 report["narrative"] = run_narrative( 

1291 report, command, Path(report["projects"][0]["workspace"]) 

1292 ) 

1293 return report, settings 

1294 

1295 def inbox(self, path: Path) -> list[dict[str, Any]]: 

1296 """Runs of the project waiting for a person (decision or clarification answers) and, 

1297 since #55, deferred verifications waiting for evidence and preflights waiting for a 

1298 decision; since #73 every other wait before DECISION (plan approval, decomposition, 

1299 acceptance tests, architecture, operational contract).""" 

1300 with self._services(path) as services: 

1301 entries = inbox(services) + inbox_entries(services) + waiting_entries(services) 

1302 return sorted(entries, key=lambda item: item["waitingSince"]) 

1303 

1304 def decide_gate( 

1305 self, 

1306 path: Path, 

1307 *, 

1308 execution_id: str, 

1309 decision: DecisionKind, 

1310 change_set_digest: str, 

1311 actor_id: str | None = None, 

1312 rationale: str, 

1313 continue_after: bool = True, 

1314 default_actor: str = DEFAULT_CLI_ACTOR, 

1315 exception: ExceptionOptions | None = None, 

1316 acknowledged_risks: tuple[str, ...] = (), 

1317 change_requests: tuple[str, ...] = (), 

1318 checked_items: tuple[str, ...] = (), 

1319 ) -> tuple[HumanDecision, Execution]: 

1320 """Record a human decision. Under ``review.exceptions`` an ``APPROVE_EXCEPTION`` also 

1321 records an exception with an expiry (``expires_in``/``expires_at``, else 

1322 ``review.exceptionDays``), a scope (``rule[:path]`` entries, else the blocking findings 

1323 of the gate), alternative evidence and a follow-up (``exception``). 

1324 

1325 Without ``actor_id`` the decider is the Git user under ``governance.deciderIdentity: 

1326 git`` (``default_actor`` with a notice when Git has no identity) and ``default_actor`` 

1327 otherwise; an actor id of an agent, a validator or the harness is refused (exit 5).""" 

1328 options = exception or ExceptionOptions() 

1329 with ( 

1330 self._run_services(path, execution_id) as (services, execution_id), 

1331 self._leased(services, "gate decide") as lease, 

1332 ): 

1333 if lease is not None: 

1334 lease.bind(execution_id) 

1335 engine = RunEngine(services) 

1336 decider, display_name = self._decider(services, actor_id, default_actor) 

1337 project = services.resolved.project 

1338 records_exception = ( 

1339 decision is DecisionKind.APPROVE_EXCEPTION and project.exceptions_enabled 

1340 ) 

1341 if options.given and not records_exception: 

1342 raise ConfigurationError( 

1343 "exception options (--expires-in, --expires-at, --scope, " 

1344 "--alternative-evidence, --follow-up) need APPROVE_EXCEPTION and " 

1345 "review.exceptions: true in project.yaml" 

1346 ) 

1347 expiry = ( 

1348 parse_expiry( 

1349 expires_in=options.expires_in, 

1350 expires_at=options.expires_at, 

1351 default_days=project.exception_days, 

1352 now=utc_now(), 

1353 ) 

1354 if records_exception 

1355 else None 

1356 ) 

1357 scopes = parse_scope(options.scope) 

1358 record = engine.decide( 

1359 execution_id=execution_id, 

1360 decision=decision, 

1361 change_set_digest=change_set_digest, 

1362 actor_id=decider, 

1363 rationale=rationale, 

1364 actor_display_name=display_name, 

1365 identity_source=self.last_identity_source 

1366 if services.resolved.project.governance_settings.git_decider 

1367 else None, 

1368 expires_at=expiry, 

1369 acknowledged_risks=acknowledged_risks, 

1370 change_requests=parse_change_requests(change_requests), 

1371 checked_items=checked_items, 

1372 ) 

1373 if records_exception: 

1374 granted = record_exception( 

1375 services, 

1376 decision=record, 

1377 scope=scopes, 

1378 alternative_evidence=options.alternative_evidence, 

1379 follow_up=options.follow_up, 

1380 ) 

1381 notify( 

1382 services, 

1383 engine.get_execution(execution_id), 

1384 "exception.granted", 

1385 exceptionId=granted.exception_id, 

1386 expiresAt=granted.expires_at.isoformat(), 

1387 ) 

1388 execution = ( 

1389 engine.continue_execution(execution_id) 

1390 if continue_after 

1391 and decision in {DecisionKind.APPROVE, DecisionKind.APPROVE_EXCEPTION} 

1392 else engine.get_execution(execution_id) 

1393 ) 

1394 return record, self._after(services, execution) 

1395 

1396 def decision_summary(self, path: Path, execution_id: str) -> dict[str, Any]: 

1397 """What a person is about to decide on: the phase, the gate result and the ChangeSet the 

1398 decision would be bound to (read-only; used by the interactive confirmation).""" 

1399 with self._services(path) as services: 

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

1401 gate = ( 

1402 services.state.get("gate", execution.gate_evaluation_id, GateEvaluation) 

1403 if execution.gate_evaluation_id 

1404 else None 

1405 ) 

1406 files: list[dict[str, Any]] = [] 

1407 if execution.change_set_digest: 1407 ↛ 1415line 1407 didn't jump to line 1415 because the condition on line 1407 was always true

1408 try: 

1409 change_set = RunEngine(services).current_change_set(execution_id) 

1410 files = [ 

1411 item.model_dump(mode="json", by_alias=True) for item in change_set.files 

1412 ] 

1413 except NotFoundError: 

1414 files = [] 

1415 return { 

1416 "executionId": execution_id, 

1417 "taskId": execution.task_id, 

1418 "currentPhase": execution.current_phase.value, 

1419 "changeSetDigest": execution.change_set_digest, 

1420 "gateStatus": gate.status.value if gate else None, 

1421 "gateReasonCodes": list(gate.reason_codes) if gate else [], 

1422 "files": files, 

1423 "confirmDigest": bool( 

1424 services.resolved.project.governance_settings.confirm_decision_digest 

1425 ), 

1426 } 

1427 

1428 def status(self, path: Path, execution_id: str) -> dict[str, Any]: 

1429 with self._services(path) as services: 

1430 execution_id = self._run_id(services, execution_id) 

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

1432 phases = services.state.list("phase", PhaseExecution, execution_id=execution_id) 

1433 validations = services.state.list( 

1434 "validation", ValidationResult, execution_id=execution_id 

1435 ) 

1436 findings = services.state.list("finding", Finding, execution_id=execution_id) 

1437 gate = ( 

1438 services.state.get("gate", execution.gate_evaluation_id, GateEvaluation) 

1439 if execution.gate_evaluation_id 

1440 else None 

1441 ) 

1442 decision = ( 

1443 services.state.get("decision", execution.human_decision_id, HumanDecision) 

1444 if execution.human_decision_id 

1445 else None 

1446 ) 

1447 events = services.events.list(execution_id) 

1448 metrics = MetricsProjector(services.state).project(execution_id, events) 

1449 # A broken chain is reported, not raised: status is how a person finds out. 

1450 chain = services.events.check_chain(execution_id) 

1451 integrity: dict[str, Any] = {} 

1452 if not chain.valid: 

1453 integrity["eventChainError"] = chain.error 

1454 if services.resolved.project.governance_settings.verify_records: 

1455 verification = RunVerifier(services).verify(execution_id) 

1456 integrity["recordsValid"] = verification.valid 

1457 if not verification.valid: 

1458 integrity["verificationSummary"] = verification.summary() 

1459 return { 

1460 "execution": execution.model_dump(mode="json", by_alias=True), 

1461 "phases": [item.model_dump(mode="json", by_alias=True) for item in phases], 

1462 "validationSummary": { 

1463 "total": len(validations), 

1464 "byStatus": self._count_by(validations, "status"), 

1465 }, 

1466 "findings": { 

1467 "total": len(findings), 

1468 "bySeverity": self._count_by(findings, "severity"), 

1469 }, 

1470 "gate": gate.model_dump(mode="json", by_alias=True) if gate else None, 

1471 "humanDecision": decision.model_dump(mode="json", by_alias=True) 

1472 if decision 

1473 else None, 

1474 "eventCount": len(events), 

1475 "eventChainValid": chain.valid, 

1476 **integrity, 

1477 "metrics": {key: value.as_dict() for key, value in metrics.items()}, 

1478 } 

1479 

1480 def verify(self, path: Path, execution_id: str | None = None) -> dict[str, Any]: 

1481 """Verify one run, or every run of the workspace when ``execution_id`` is ``None``: 

1482 the event chain, the anchor of its head, the records against the events and the 

1483 artifacts against their digests. Never raises on a failed check; ``valid`` is false.""" 

1484 with self._services(path) as services: 

1485 verifier = RunVerifier(services) 

1486 ids = [execution_id] if execution_id else verifier.execution_ids() 

1487 runs = [verifier.verify(item).as_dict() for item in ids] 

1488 report: dict[str, Any] = { 

1489 "valid": all(item["valid"] for item in runs), 

1490 "runCount": len(runs), 

1491 "runs": runs, 

1492 } 

1493 invalid = [item["executionId"] for item in runs if not item["valid"]] 

1494 if invalid: 

1495 report["hint"] = _verify_hint(services, invalid) 

1496 return report 

1497 

1498 def export_bundle(self, path: Path, execution_id: str, output: Path) -> dict[str, Any]: 

1499 """Write the portable evidence bundle of a run (``delivery.bundle``). Under 

1500 ``governance.verifyRecords`` the run is verified first, as for ``trace``.""" 

1501 with self._services(path) as services: 

1502 execution_id = self._run_id(services, execution_id) 

1503 if services.resolved.project.governance_settings.verify_records: 1503 ↛ 1510line 1503 didn't jump to line 1510 because the condition on line 1503 was always true

1504 verification = RunVerifier(services).verify(execution_id) 

1505 if not verification.valid: 1505 ↛ 1506line 1505 didn't jump to line 1506 because the condition on line 1505 was never true

1506 raise IntegrityError( 

1507 f"run {execution_id} does not verify ({verification.summary()}); " 

1508 "inspect it with harness verify --run" 

1509 ) 

1510 return export_bundle(services, execution_id, output) 

1511 

1512 @staticmethod 

1513 def verify_bundle(bundle: Path) -> dict[str, Any]: 

1514 """Verify a bundle without a workspace or a project configuration.""" 

1515 if not bundle.is_file(): 

1516 raise NotFoundError(f"bundle not found: {bundle}") 

1517 return verify_bundle(bundle) 

1518 

1519 @staticmethod 

1520 def verify_approval( 

1521 path: Path, 

1522 *, 

1523 base: str, 

1524 head: str = "HEAD", 

1525 bundles: tuple[Path, ...] = (), 

1526 use_workspace: bool = True, 

1527 ) -> dict[str, Any]: 

1528 """Whether the range ``base..head`` is a ChangeSet a person approved 

1529 (``delivery.approval``); needs a Git repository, not a project configuration.""" 

1530 for bundle in bundles: 

1531 if not bundle.is_file(): 1531 ↛ 1532line 1531 didn't jump to line 1532 because the condition on line 1531 was never true

1532 raise NotFoundError(f"bundle not found: {bundle}") 

1533 root = path.resolve() 

1534 if not Git(root).is_repository(): 1534 ↛ 1535line 1534 didn't jump to line 1535 because the condition on line 1534 was never true

1535 raise ConfigurationError(f"not a Git repository: {root}") 

1536 top = Path(Git(root).text("rev-parse", "--show-toplevel")) 

1537 return verify_approval(top, base, head, bundles=bundles, use_workspace=use_workspace) 

1538 

1539 def publish_pull_request( 

1540 self, 

1541 path: Path, 

1542 execution_id: str, 

1543 *, 

1544 pull_request: int, 

1545 repository: str | None = None, 

1546 transport: str | None = None, 

1547 sarif: bool | None = None, 

1548 commit_sha: str | None = None, 

1549 transport_override: Transport | None = None, 

1550 forge: str | None = None, 

1551 ) -> dict[str, Any]: 

1552 """Post the decision brief of a run on a pull request and upload its SARIF report. 

1553 

1554 Since #56 any forge: with ``forge`` (or ``delivery.forge``), or when ``origin`` is not 

1555 a GitHub remote, the forge layer posts the comment and the forge's quality report.""" 

1556 with self._services(path) as services: 

1557 run_id = self._run_id(services, execution_id) 

1558 use_forge = forge is not None or ( 

1559 services.resolved.project.delivery_settings.forge is not None 

1560 ) 

1561 if not use_forge and repository is None: 

1562 detected = forge_report(services) 

1563 use_forge = detected.get("status") == "DETECTED" and detected["kind"] != "github" 

1564 if use_forge: 

1565 return publish_on_forge( 

1566 services, 

1567 run_id, 

1568 pull_request=pull_request, 

1569 kind=forge, 

1570 repository=repository, 

1571 transport={"gh": "cli", "glab": "cli"}.get(transport or "", transport), 

1572 reports=sarif, 

1573 commit_sha=commit_sha, 

1574 transport_override=transport_override, 

1575 ) 

1576 settings = services.resolved.project.delivery_settings.publisher or PublisherConfig() 

1577 updates: dict[str, Any] = {} 

1578 if repository is not None: 

1579 updates["repository"] = repository 

1580 if transport is not None: 1580 ↛ 1581line 1580 didn't jump to line 1581 because the condition on line 1580 was never true

1581 updates["transport"] = transport 

1582 if sarif is not None: 

1583 updates["sarif"] = sarif 

1584 settings = PublisherConfig.model_validate( 

1585 settings.model_dump(by_alias=True) 

1586 | { 

1587 PublisherConfig.model_fields[key].alias or key: value 

1588 for key, value in updates.items() 

1589 } 

1590 ) 

1591 name = settings.repository or repository_from_remote(services.paths.workspace) 

1592 if name is None: 

1593 raise ConfigurationError( 

1594 "no repository: pass --repository owner/name or set " 

1595 "delivery.publisher.repository (no GitHub remote named origin was found)" 

1596 ) 

1597 execution = services.state.get("execution", run_id, Execution) 

1598 brief = build_brief(services, run_id, exceptions=brief_exceptions(services, execution)) 

1599 report = None 

1600 if settings.sarif: 

1601 findings = services.state.list("finding", Finding, execution_id=run_id) 

1602 report = TraceReporter().render_sarif(findings) 

1603 publisher = GitHubPublisher(transport_override or transport_for(settings), name) 

1604 return publisher.publish( 

1605 pull_request=pull_request, 

1606 run_id=run_id, 

1607 brief_markdown=render_brief_markdown(brief), 

1608 sarif=report, 

1609 commit_sha=commit_sha, 

1610 ) 

1611 

1612 def create_pull_request( 

1613 self, 

1614 path: Path, 

1615 execution_id: str, 

1616 *, 

1617 head: str | None = None, 

1618 base: str | None = None, 

1619 title: str | None = None, 

1620 labels: tuple[str, ...] = (), 

1621 draft: bool | None = None, 

1622 forge: str | None = None, 

1623 repository: str | None = None, 

1624 transport: str | None = None, 

1625 transport_override: Transport | None = None, 

1626 ) -> dict[str, Any]: 

1627 """Open a pull or merge request from the run's closure branch on its forge (#56).""" 

1628 with self._services(path) as services: 

1629 return create_on_forge( 

1630 services, 

1631 self._run_id(services, execution_id), 

1632 head=head, 

1633 base=base, 

1634 title=title, 

1635 labels=labels, 

1636 draft=draft, 

1637 kind=forge, 

1638 repository=repository, 

1639 transport=transport, 

1640 transport_override=transport_override, 

1641 ) 

1642 

1643 def pull_request_status( 

1644 self, 

1645 path: Path, 

1646 execution_id: str, 

1647 *, 

1648 commit_sha: str, 

1649 target_url: str | None = None, 

1650 forge: str | None = None, 

1651 repository: str | None = None, 

1652 transport: str | None = None, 

1653 transport_override: Transport | None = None, 

1654 ) -> dict[str, Any]: 

1655 """Set the commit status of the run on its forge (#56).""" 

1656 with self._services(path) as services: 

1657 return status_on_forge( 

1658 services, 

1659 self._run_id(services, execution_id), 

1660 commit_sha=commit_sha, 

1661 target_url=target_url, 

1662 kind=forge, 

1663 repository=repository, 

1664 transport=transport, 

1665 transport_override=transport_override, 

1666 ) 

1667 

1668 def standards( 

1669 self, path: Path, *, pack: str | None = None, files: tuple[str, ...] = () 

1670 ) -> dict[str, Any]: 

1671 """The language standards packs of the project (#56): detected and effective packs, 

1672 their cards, the tools the repository configures and, for ``files``, the cards an 

1673 implement call and the review checklist would get. Works without a project too.""" 

1674 try: 

1675 resolved = ConfigurationResolver().resolve(path) 

1676 except ConfigurationError: 

1677 return standards_report(path.resolve(), None, (), [], pack=pack, files=files) 

1678 return standards_report( 

1679 resolved.workspace_root, 

1680 resolved.project.standards, 

1681 tuple(item.technology for item in resolved.profiles), 

1682 [item.validator_id for item in resolved.effective_validators], 

1683 pack=pack, 

1684 files=files, 

1685 ) 

1686 

1687 def architecture(self, path: Path) -> dict[str, Any]: 

1688 """The architecture of the project: configuration, survey or ADR, rules in force.""" 

1689 with self._services(path) as services: 

1690 return architecture_report(services) 

1691 

1692 def decide_architecture( 

1693 self, 

1694 path: Path, 

1695 *, 

1696 execution_id: str, 

1697 digest: str, 

1698 rationale: str, 

1699 decision: DecisionKind | None = None, 

1700 option: str | None = None, 

1701 actor_id: str | None = None, 

1702 continue_after: bool = True, 

1703 style: str | None = None, 

1704 ) -> dict[str, Any]: 

1705 """Approve or reject inferred layer rules, or choose an architecture option (#56) or, 

1706 under ``architecture.catalogue: experts``, a style of the catalogue (#97).""" 

1707 with ( 

1708 self._services(path) as services, 

1709 self._leased(services, "architecture decide") as lease, 

1710 ): 

1711 execution_id = self._run_id(services, execution_id) 

1712 if lease is not None: 1712 ↛ 1714line 1712 didn't jump to line 1714 because the condition on line 1712 was always true

1713 lease.bind(execution_id) 

1714 decider = self._decider(services, actor_id)[0] 

1715 return decide_architecture( 

1716 services, 

1717 execution_id, 

1718 digest=digest, 

1719 actor_id=decider, 

1720 rationale=rationale, 

1721 decision=decision, 

1722 option=option, 

1723 continue_after=continue_after, 

1724 style=style, 

1725 ) 

1726 

1727 def refresh_architecture(self, path: Path) -> dict[str, Any]: 

1728 with self._services(path) as services: 

1729 return refresh_architecture(services) 

1730 

1731 def project(self, path: Path) -> dict[str, Any]: 

1732 """New or existing, packs, testing strategy, architecture and forge, without a call.""" 

1733 with self._services(path) as services: 

1734 return project_report(services) 

1735 

1736 def forge(self, path: Path) -> dict[str, Any]: 

1737 """The forge the workspace resolves to, without calling it.""" 

1738 with self._services(path) as services: 

1739 return forge_report(services) 

1740 

1741 def list_runs(self, path: Path) -> list[Execution]: 

1742 with self._services(path) as services: 

1743 return services.state.list( 

1744 "execution", 

1745 Execution, 

1746 project_id=services.resolved.project.project_id, 

1747 newest_first=True, 

1748 ) 

1749 

1750 def trace(self, path: Path, execution_id: str, format: str = "markdown") -> bytes: 

1751 """Export the trace of a run. Under ``governance.verifyRecords`` the run is verified 

1752 first and a run that does not verify is not exported (exit code 6).""" 

1753 with self._services(path) as services: 

1754 execution_id = self._run_id(services, execution_id) 

1755 if services.resolved.project.governance_settings.verify_records: 

1756 verification = RunVerifier(services).verify(execution_id) 

1757 if not verification.valid: 

1758 raise IntegrityError( 

1759 f"run {execution_id} does not verify ({verification.summary()}); " 

1760 "inspect it with harness verify --run" 

1761 ) 

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

1763 task = services.state.get("task", execution.task_id, Task) 

1764 phases = services.state.list("phase", PhaseExecution, execution_id=execution_id) 

1765 validations = services.state.list( 

1766 "validation", ValidationResult, execution_id=execution_id 

1767 ) 

1768 findings = services.state.list("finding", Finding, execution_id=execution_id) 

1769 gate = ( 

1770 services.state.get("gate", execution.gate_evaluation_id, GateEvaluation) 

1771 if execution.gate_evaluation_id 

1772 else None 

1773 ) 

1774 decision = ( 

1775 services.state.get("decision", execution.human_decision_id, HumanDecision) 

1776 if execution.human_decision_id 

1777 else None 

1778 ) 

1779 retrospectives = services.state.list( 

1780 "retrospective", Retrospective, execution_id=execution_id 

1781 ) 

1782 events = services.events.list(execution_id) 

1783 metrics = MetricsProjector(services.state).project(execution_id, events) 

1784 reporter = TraceReporter() 

1785 kwargs = { 

1786 "execution": execution, 

1787 "task": task, 

1788 "phases": phases, 

1789 "validations": validations, 

1790 "findings": findings, 

1791 "gate": gate, 

1792 "decision": decision, 

1793 "events": events, 

1794 "metrics": metrics, 

1795 "retrospective": retrospectives[-1] if retrospectives else None, 

1796 } 

1797 if format == "json": 

1798 return reporter.render_json(**kwargs) 

1799 if format == "sarif": 

1800 return reporter.render_sarif(findings) 

1801 if format == "codequality": 

1802 return render_code_quality(findings) 

1803 if format == "jsonl": 

1804 return services.events.export_jsonl(execution_id) 

1805 if format != "markdown": 1805 ↛ 1806line 1805 didn't jump to line 1806 because the condition on line 1805 was never true

1806 raise ConfigurationError(f"unsupported trace format: {format}") 

1807 return reporter.render_markdown(**kwargs) 

1808 

1809 def gc(self, path: Path, *, apply: bool = False) -> dict[str, Any]: 

1810 """Apply ``retention.artifactDays`` and ``retention.eventDays`` to the runs that 

1811 ended; without ``apply`` only report what would be removed.""" 

1812 with self._services(path) as services, self._leased(services, "gc"): 

1813 collector = RetentionCollector(services) 

1814 plan = collector.plan() 

1815 if apply: 1815 ↛ 1816line 1815 didn't jump to line 1816 because the condition on line 1815 was never true

1816 collector.apply(plan) 

1817 return plan.as_dict(applied=apply) 

1818 

1819 def list_evidence(self, path: Path, execution_id: str) -> list[dict[str, Any]]: 

1820 with self._services(path) as services: 

1821 execution_id = self._run_id(services, execution_id) 

1822 evidence = services.state.list_dicts("evidence", execution_id=execution_id) 

1823 artifacts = services.state.list_dicts("artifact", execution_id=execution_id) 

1824 return [{"evidence": evidence, "artifacts": artifacts}] 

1825 

1826 def list_findings(self, path: Path, execution_id: str) -> list[Finding]: 

1827 with self._services(path) as services: 

1828 execution_id = self._run_id(services, execution_id) 

1829 return services.state.list("finding", Finding, execution_id=execution_id) 

1830 

1831 def retrospect(self, path: Path, execution_id: str) -> Retrospective: 

1832 with self._services(path) as services: 

1833 execution_id = self._run_id(services, execution_id) 

1834 records = services.state.list("retrospective", Retrospective, execution_id=execution_id) 

1835 if records: 1835 ↛ 1837line 1835 didn't jump to line 1837 because the condition on line 1835 was always true

1836 return records[-1] 

1837 return self._generate_retrospective(services, execution_id, "ON_DEMAND") 

1838 

1839 @staticmethod 

1840 def _generate_retrospective( 

1841 services: EngineServices, execution_id: str, trigger: RetrospectiveTrigger 

1842 ) -> Retrospective: 

1843 """A retrospective outside CLOSURE: on demand, or (``retrospective.causal``) when a run 

1844 is rejected or cancelled. Stored as a record; the run's event chain is not extended.""" 

1845 engine = RunEngine(services) 

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

1847 events = services.events.list(execution_id) 

1848 metrics = MetricsProjector(services.state).project(execution_id, events) 

1849 trace_ref = services.artifacts.put( 

1850 services.events.export_jsonl(execution_id), 

1851 media_type="application/x-ndjson", 

1852 metadata={"kind": "retrospective-input"}, 

1853 ) 

1854 analysis = engine.cause_analysis(execution) 

1855 retro = engine.retrospective_engine.generate( 

1856 execution_id=execution_id, 

1857 metrics=metrics, 

1858 evidence_refs=(trace_ref.uri,), 

1859 provenance=engine._provenance(execution), 

1860 analysis=analysis, 

1861 trigger=trigger if analysis is not None else None, 

1862 ) 

1863 services.state.put( 

1864 "retrospective", 

1865 retro.retrospective_id, 

1866 retro, 

1867 execution_id=execution_id, 

1868 project_id=execution.project_id, 

1869 ) 

1870 return retro 

1871 

1872 def add_memory( 

1873 self, 

1874 path: Path, 

1875 *, 

1876 level: MemoryLevel, 

1877 key: str, 

1878 value: dict[str, Any], 

1879 actor_id: str | None = None, 

1880 task_id: str | None = None, 

1881 execution_id: str | None = None, 

1882 valid_until: datetime | None = None, 

1883 supersedes: str | None = None, 

1884 sensitive: bool = False, 

1885 approved: bool = False, 

1886 ) -> MemoryRecord: 

1887 """Record a memory entry. Normative, project and retrospective entries only enter a 

1888 context once approved; the approval is an explicit act of the recorded actor.""" 

1889 with self._services(path) as services: 

1890 actor_id, display_name = self._decider(services, actor_id) 

1891 if approved: 

1892 require_human_actor(actor_id, "approve a memory record") 

1893 store = MemoryStore(services.state) 

1894 project_id = services.resolved.project.project_id 

1895 if not key.strip(): 1895 ↛ 1896line 1895 didn't jump to line 1896 because the condition on line 1895 was never true

1896 raise ConfigurationError("a memory record requires a non-empty key") 

1897 if level is MemoryLevel.TASK and not task_id: 

1898 raise ConfigurationError("task memory requires the task it belongs to") 

1899 if level is MemoryLevel.EPHEMERAL and not execution_id: 1899 ↛ 1900line 1899 didn't jump to line 1900 because the condition on line 1899 was never true

1900 raise ConfigurationError("ephemeral memory requires the run it belongs to") 

1901 if task_id: 1901 ↛ 1902line 1901 didn't jump to line 1902 because the condition on line 1901 was never true

1902 services.state.get("task", task_id, Task) 

1903 if execution_id: 1903 ↛ 1904line 1903 didn't jump to line 1904 because the condition on line 1903 was never true

1904 services.state.get("execution", execution_id, Execution) 

1905 if supersedes: 1905 ↛ 1906line 1905 didn't jump to line 1906 because the condition on line 1905 was never true

1906 self._project_memory(store, supersedes, project_id) 

1907 record = MemoryRecord( 

1908 memory_id=new_id("mem"), 

1909 project_id=project_id, 

1910 task_id=task_id, 

1911 execution_id=execution_id, 

1912 level=level, 

1913 key=key.strip(), 

1914 value=value, 

1915 provenance=self._human_provenance( 

1916 actor_id, 

1917 source_refs=(supersedes,) if supersedes else (), 

1918 display_name=display_name, 

1919 ), 

1920 valid_until=valid_until, 

1921 supersedes=supersedes, 

1922 sensitive=sensitive, 

1923 approved=approved, 

1924 ) 

1925 store.put(record) 

1926 return record 

1927 

1928 def list_memory( 

1929 self, path: Path, *, task_id: str | None = None, execution_id: str | None = None 

1930 ) -> list[dict[str, Any]]: 

1931 """List every memory record of the project with its status for the given task and run: 

1932 active, superseded, expired, unapproved, limit or out_of_scope.""" 

1933 with self._services(path) as services: 

1934 store = MemoryStore(services.state) 

1935 project_id = services.resolved.project.project_id 

1936 selection = store.select( 

1937 project_id=project_id, task_id=task_id, execution_id=execution_id 

1938 ) 

1939 active = {item.memory_id for item in selection.records} 

1940 excluded = {item.memory_id: item for item in selection.exclusions} 

1941 listing: list[dict[str, Any]] = [] 

1942 for record in sorted( 

1943 store.list_project(project_id), key=lambda item: (item.created_at, item.memory_id) 

1944 ): 

1945 entry: dict[str, Any] = {"record": record.model_dump(mode="json", by_alias=True)} 

1946 if record.memory_id in active: 

1947 entry["status"] = "active" 

1948 elif record.memory_id in excluded: 1948 ↛ 1954line 1948 didn't jump to line 1954 because the condition on line 1948 was always true

1949 exclusion = excluded[record.memory_id] 

1950 entry["status"] = exclusion.reason 

1951 if exclusion.superseded_by: 

1952 entry["supersededBy"] = exclusion.superseded_by 

1953 else: 

1954 entry["status"] = "out_of_scope" 

1955 listing.append(entry) 

1956 return listing 

1957 

1958 def memory_manifest(self, path: Path, execution_id: str) -> dict[str, Any]: 

1959 """Return the context manifest recorded for a run: the memory it applied and the 

1960 candidates it left out, as they were when the run was planned.""" 

1961 with self._services(path) as services: 

1962 execution_id = self._run_id(services, execution_id) 

1963 services.state.get("execution", execution_id, Execution) 

1964 reference = services.state.get_flag(f"context:{execution_id}") 

1965 if not reference: 1965 ↛ 1966line 1965 didn't jump to line 1966 because the condition on line 1965 was never true

1966 raise NotFoundError(f"run has no context manifest: {execution_id}") 

1967 manifest: dict[str, Any] = json.loads(services.artifacts.get(reference)) 

1968 return {"executionId": execution_id, "manifestRef": reference, **manifest} 

1969 

1970 def approve_memory( 

1971 self, path: Path, *, memory_id: str, actor_id: str | None = None 

1972 ) -> MemoryRecord: 

1973 """Approve a normative, project or retrospective record. The approval is a new record 

1974 that supersedes the proposal, so the proposal and its approver both stay on record.""" 

1975 with self._services(path) as services: 

1976 actor_id, display_name = self._decider(services, actor_id) 

1977 require_human_actor(actor_id, "approve a memory record") 

1978 store = MemoryStore(services.state) 

1979 target = self._project_memory(store, memory_id, services.resolved.project.project_id) 

1980 if target.level not in APPROVAL_REQUIRED: 1980 ↛ 1981line 1980 didn't jump to line 1981 because the condition on line 1980 was never true

1981 raise PolicyViolationError( 

1982 f"{target.level.value} memory does not require approval: {memory_id}" 

1983 ) 

1984 if target.approved: 

1985 raise PolicyViolationError(f"memory record is already approved: {memory_id}") 

1986 record = target.model_copy( 

1987 update={ 

1988 "memory_id": new_id("mem"), 

1989 "created_at": datetime.now(UTC), 

1990 "supersedes": target.memory_id, 

1991 "approved": True, 

1992 "provenance": self._human_provenance( 

1993 actor_id, source_refs=(target.memory_id,), display_name=display_name 

1994 ), 

1995 } 

1996 ) 

1997 store.put(record) 

1998 return record 

1999 

2000 def invalidate_memory( 

2001 self, path: Path, *, memory_id: str, actor_id: str | None = None, reason: str 

2002 ) -> MemoryRecord: 

2003 """Invalidate a record without deleting it: an approved, already expired record 

2004 supersedes it and keeps who invalidated it and why.""" 

2005 with self._services(path) as services: 

2006 actor_id, display_name = self._decider(services, actor_id) 

2007 require_human_actor(actor_id, "invalidate a memory record") 

2008 store = MemoryStore(services.state) 

2009 target = self._project_memory(store, memory_id, services.resolved.project.project_id) 

2010 if not reason.strip(): 

2011 raise ConfigurationError("invalidating a memory record requires a reason") 

2012 now = datetime.now(UTC) 

2013 record = MemoryRecord( 

2014 memory_id=new_id("mem"), 

2015 project_id=target.project_id, 

2016 task_id=target.task_id, 

2017 execution_id=target.execution_id, 

2018 level=target.level, 

2019 key=target.key, 

2020 value={"invalidated": True, "reason": reason.strip()}, 

2021 provenance=self._human_provenance( 

2022 actor_id, source_refs=(target.memory_id,), display_name=display_name 

2023 ), 

2024 created_at=now, 

2025 valid_until=now, 

2026 supersedes=target.memory_id, 

2027 approved=True, 

2028 ) 

2029 store.put(record) 

2030 return record 

2031 

2032 def list_recommendations(self, path: Path, execution_id: str) -> list[dict[str, Any]]: 

2033 """List the recommendations of a run with the decision recorded for each, if any.""" 

2034 with self._services(path) as services: 

2035 execution_id = self._run_id(services, execution_id) 

2036 retrospective = self._retrospective(services, execution_id) 

2037 decided = { 

2038 item.key: item 

2039 for item in MemoryStore(services.state).list_project( 

2040 services.resolved.project.project_id 

2041 ) 

2042 if item.level is MemoryLevel.RETROSPECTIVE 

2043 } 

2044 listing: list[dict[str, Any]] = [] 

2045 for recommendation in retrospective.recommendations: 

2046 record = decided.get(self._recommendation_key(recommendation.recommendation_id)) 

2047 listing.append( 

2048 { 

2049 "recommendation": recommendation.model_dump(mode="json", by_alias=True), 

2050 "decision": record.value.get("decision") if record else None, 

2051 "memoryId": record.memory_id if record else None, 

2052 } 

2053 ) 

2054 return listing 

2055 

2056 def decide_recommendation( 

2057 self, 

2058 path: Path, 

2059 *, 

2060 execution_id: str, 

2061 recommendation_id: str, 

2062 decision: RecommendationDecision, 

2063 actor_id: str | None = None, 

2064 rationale: str, 

2065 statement: str | None = None, 

2066 ) -> MemoryRecord: 

2067 """Record the decision of a person on a retrospective recommendation. 

2068 

2069 The decision is kept as retrospective memory. An accepted or edited recommendation is 

2070 approved and enters the context of later runs; a rejected one is kept as history and 

2071 never enters a context. Nothing else changes: rules, gates and configuration are only 

2072 modified by a person through a versioned change.""" 

2073 with self._services(path) as services: 

2074 execution_id = self._run_id(services, execution_id) 

2075 actor_id, display_name = self._decider(services, actor_id) 

2076 require_human_actor(actor_id, "decide on a recommendation") 

2077 retrospective = self._retrospective(services, execution_id) 

2078 recommendation = next( 

2079 ( 

2080 item 

2081 for item in retrospective.recommendations 

2082 if item.recommendation_id == recommendation_id 

2083 ), 

2084 None, 

2085 ) 

2086 if recommendation is None: 

2087 raise NotFoundError(f"recommendation not found in run: {recommendation_id}") 

2088 if not rationale.strip(): 2088 ↛ 2089line 2088 didn't jump to line 2089 because the condition on line 2088 was never true

2089 raise ConfigurationError("a decision on a recommendation requires a rationale") 

2090 edited = statement.strip() if statement else "" 

2091 if decision is RecommendationDecision.EDIT and not edited: 

2092 raise ConfigurationError("EDIT requires the edited statement") 

2093 if decision is not RecommendationDecision.EDIT and edited: 

2094 raise ConfigurationError("only EDIT takes an edited statement") 

2095 store = MemoryStore(services.state) 

2096 project_id = services.resolved.project.project_id 

2097 key = self._recommendation_key(recommendation_id) 

2098 if any(item.key == key for item in store.list_project(project_id)): 

2099 raise PolicyViolationError( 

2100 f"recommendation already has a decision: {recommendation_id}" 

2101 ) 

2102 now = datetime.now(UTC) 

2103 value: dict[str, Any] = { 

2104 "recommendationId": recommendation.recommendation_id, 

2105 "executionId": execution_id, 

2106 "category": recommendation.category, 

2107 "statement": edited or recommendation.statement, 

2108 "rationale": recommendation.rationale, 

2109 "decision": decision.value, 

2110 "decisionRationale": rationale.strip(), 

2111 } 

2112 if edited: 

2113 value["originalStatement"] = recommendation.statement 

2114 rejected = decision is RecommendationDecision.REJECT 

2115 record = MemoryRecord( 

2116 memory_id=new_id("mem"), 

2117 project_id=project_id, 

2118 level=MemoryLevel.RETROSPECTIVE, 

2119 key=key, 

2120 value=value, 

2121 provenance=self._human_provenance( 

2122 actor_id, 

2123 source_refs=(retrospective.retrospective_id,), 

2124 display_name=display_name, 

2125 ), 

2126 created_at=now, 

2127 valid_until=now if rejected else None, 

2128 approved=not rejected, 

2129 ) 

2130 store.put(record) 

2131 return record 

2132 

2133 def doctor(self, path: Path | None = None, *, install_hooks: bool = False) -> dict[str, Any]: 

2134 checks: dict[str, Any] = { 

2135 "python": {"status": "PASSED", "version": sys.version.split()[0]}, 

2136 "git": {"status": "PASSED" if shutil.which("git") else "FAILED"}, 

2137 "node": {"status": "PASSED" if shutil.which("node") else "NOT_APPLICABLE"}, 

2138 "npm": {"status": "PASSED" if shutil.which("npm") else "NOT_APPLICABLE"}, 

2139 } 

2140 if checks["git"]["status"] == "FAILED": 2140 ↛ 2141line 2140 didn't jump to line 2141 because the condition on line 2140 was never true

2141 checks["git"]["hint"] = "Install Git: the harness records baselines from Git." 

2142 checks["gitIdentity"] = git_identity(path if path and path.is_dir() else None) 

2143 if path is not None: 2143 ↛ 2170line 2143 didn't jump to line 2170 because the condition on line 2143 was always true

2144 try: 

2145 resolved = ConfigurationResolver().resolve(path) 

2146 checks["configuration"] = { 

2147 "status": "PASSED", 

2148 "projectId": resolved.project.project_id, 

2149 "profiles": [item.profile_id for item in resolved.profiles], 

2150 } 

2151 harness_dir = resolved.workspace_root / ".harness" 

2152 checks["filesystem"] = { 

2153 "status": "PASSED" if os.access(harness_dir, os.W_OK) else "FAILED", 

2154 "path": str(harness_dir), 

2155 } 

2156 if checks["filesystem"]["status"] == "FAILED": 2156 ↛ 2157line 2156 didn't jump to line 2157 because the condition on line 2156 was never true

2157 checks["filesystem"]["hint"] = f"Make {harness_dir} writable by this user." 

2158 checks.update(repository_checks(resolved.workspace_root)) 

2159 checks.update(provider_checks(resolved)) 

2160 checks["agentSandbox"] = sandbox_check(resolved) 

2161 checks["validators"] = validator_checks(resolved) 

2162 checks.update(self._ladder_checks(resolved, install_hooks=install_hooks)) 

2163 except Exception as error: 

2164 checks["configuration"] = { 

2165 "status": "FAILED", 

2166 "message": str(error), 

2167 "hint": default_hint(error) 

2168 or "Fix .harness/project.yaml; `harness config validate` shows the error.", 

2169 } 

2170 status = ( 

2171 "PASSED" 

2172 if all(item["status"] not in {"FAILED", "ERROR"} for item in checks.values()) 

2173 else "FAILED" 

2174 ) 

2175 return {"status": status, "version": __version__, "checks": checks} 

2176 

2177 @staticmethod 

2178 def _ladder_checks(resolved: Any, *, install_hooks: bool) -> dict[str, Any]: 

2179 """The run registry, the environment preflight and the instruction files (#55).""" 

2180 checks: dict[str, Any] = {} 

2181 project = resolved.project 

2182 workspace = resolved.workspace_root 

2183 if project.runtime.state_dir is not None: 2183 ↛ 2184line 2183 didn't jump to line 2184 because the condition on line 2183 was never true

2184 checks["stateDir"] = _state_dir_check(project, workspace) 

2185 if sys.platform == "win32": 2185 ↛ 2186line 2185 didn't jump to line 2186 because the condition on line 2185 was never true

2186 checks["pathLength"] = _path_length_check(project, workspace) 

2187 environment = project.environment 

2188 if environment is not None: 

2189 hooks = environment.git_hooks 

2190 if install_hooks and hooks and hooks.install: 2190 ↛ 2191line 2190 didn't jump to line 2191 because the condition on line 2190 was never true

2191 checks["hooksInstall"] = _hooks_install_check(tuple(hooks.install), workspace) 

2192 checks["environment"] = _environment_check(environment, workspace) 

2193 if project.instructions is not None: 2193 ↛ 2194line 2193 didn't jump to line 2194 because the condition on line 2193 was never true

2194 checks["instructions"] = _instructions_check(resolved) 

2195 return checks 

2196 

2197 @staticmethod 

2198 @contextmanager 

2199 def _leased(services: EngineServices, command: str) -> Iterator[WorkspaceLease | None]: 

2200 """Hold the workspace lease while a command executes phases or records a decision 

2201 (``governance.workspaceLease``); a second process gets exit code 5. ``SIGTERM`` then 

2202 stops the command like Ctrl-C, so the runner terminates the agent's process group and 

2203 the phase is recorded as interrupted.""" 

2204 if not services.resolved.project.governance_settings.workspace_lease: 

2205 yield None 

2206 return 

2207 lease = WorkspaceLease(services.paths.harness_dir, command).acquire() 

2208 try: 

2209 with interruptible(): 

2210 yield lease 

2211 finally: 

2212 lease.release() 

2213 

2214 def resolve_run(self, path: Path, reference: str) -> str: 

2215 """The run id a reference names: an exact id, ``latest`` or a unique prefix.""" 

2216 with self._services(path) as services: 

2217 return self._run_id(services, reference) 

2218 

2219 def review( 

2220 self, path: Path, execution_id: str, *, include_diff: bool = False 

2221 ) -> dict[str, Any]: 

2222 """The decision brief of a run (see ``application.review``).""" 

2223 with self._run_services(path, execution_id) as (services, run_id): 

2224 execution = services.state.get("execution", run_id, Execution) 

2225 brief = build_brief( 

2226 services, 

2227 run_id, 

2228 include_diff=include_diff, 

2229 exceptions=brief_exceptions(services, execution), 

2230 ) 

2231 friction = RunEngine(services).friction.brief(execution) 

2232 if friction is not None: 

2233 # The lane, the change type and the pre-authorisation (#58). 

2234 brief["friction"] = friction 

2235 return brief 

2236 

2237 def list_exceptions( 

2238 self, path: Path, *, status: str = "all", expiring_within: int | None = None 

2239 ) -> list[dict[str, Any]]: 

2240 """The exceptions of the project with their status (ACTIVE or EXPIRED), days left and 

2241 the runs whose gate relied on them.""" 

2242 if status.lower() not in {"all", "active", "expired"}: 2242 ↛ 2243line 2242 didn't jump to line 2243 because the condition on line 2242 was never true

2243 raise ConfigurationError(f"unknown exception status: {status}") 

2244 with self._services(path) as services: 

2245 return list_exceptions(services, status=status.lower(), expiring_within=expiring_within) 

2246 

2247 def show_artifact(self, path: Path, reference: str) -> tuple[dict[str, Any], bytes]: 

2248 """An artifact's descriptor and its content, read with digest verification. The 

2249 reference is ``artifact://sha256/<hex>``, ``sha256:<hex>`` or a unique hex prefix of at 

2250 least 6 characters.""" 

2251 with self._services(path) as services: 

2252 uri = self._artifact_uri(services, reference.strip()) 

2253 descriptor = services.artifacts.describe(uri) 

2254 data = services.artifacts.get(uri) 

2255 return { 

2256 "uri": descriptor.uri, 

2257 "digest": descriptor.digest, 

2258 "sizeBytes": descriptor.size_bytes, 

2259 "mediaType": descriptor.media_type, 

2260 "redacted": descriptor.redacted, 

2261 "verified": True, 

2262 "metadata": descriptor.metadata or {}, 

2263 }, data 

2264 

2265 @staticmethod 

2266 def _artifact_uri(services: EngineServices, reference: str) -> str: 

2267 hex_part = reference 

2268 for prefix in ("artifact://sha256/", "sha256:"): 

2269 if reference.startswith(prefix): 

2270 hex_part = reference[len(prefix) :] 

2271 hex_part = hex_part.lower() 

2272 if len(hex_part) < 6 or any(char not in "0123456789abcdef" for char in hex_part): 

2273 raise ConfigurationError( 

2274 f"not an artifact reference or digest prefix (6+ hex characters): {reference}" 

2275 ) 

2276 meta_root = services.artifacts.meta_root 

2277 if len(hex_part) == 64: 

2278 matches = [hex_part] if (meta_root / f"{hex_part}.json").exists() else [] 

2279 else: 

2280 matches = sorted(item.stem for item in meta_root.glob(f"{hex_part}*.json")) 

2281 if not matches: 

2282 raise NotFoundError(f"artifact not found: {reference}") 

2283 if len(matches) > 1: 2283 ↛ 2284line 2283 didn't jump to line 2284 because the condition on line 2283 was never true

2284 raise ConfigurationError( 

2285 f"artifact prefix {reference} matches {len(matches)} artifacts; use more characters" 

2286 ) 

2287 return f"artifact://sha256/{matches[0]}" 

2288 

2289 @staticmethod 

2290 def _run_id(services: EngineServices, reference: str) -> str: 

2291 reference = reference.strip() 

2292 try: 

2293 services.state.get("execution", reference, Execution) 

2294 return reference 

2295 except NotFoundError: 

2296 pass 

2297 runs = services.state.list( 

2298 "execution", Execution, project_id=services.resolved.project.project_id 

2299 ) 

2300 if reference == "latest": 

2301 if not runs: 

2302 raise NotFoundError("execution not found: latest (the project has no runs)") 

2303 return max(runs, key=lambda item: item.created_at).execution_id 

2304 prefixes = (reference, f"run_{reference}") 

2305 matches = sorted( 

2306 item.execution_id for item in runs if item.execution_id.startswith(prefixes) 

2307 ) 

2308 if len(matches) == 1: 

2309 return matches[0] 

2310 if len(matches) > 1: 

2311 raise ConfigurationError( 

2312 f"run prefix {reference} matches {len(matches)} runs: {', '.join(matches[:5])}" 

2313 ) 

2314 raise NotFoundError(f"execution not found: {reference}") 

2315 

2316 @contextmanager 

2317 def _services(self, path: Path) -> Iterator[EngineServices]: 

2318 resolved = ConfigurationResolver().resolve(path) 

2319 services = EngineServices.open(resolved) 

2320 try: 

2321 yield services 

2322 finally: 

2323 services.close() 

2324 

2325 @staticmethod 

2326 def _open_services(path: Path) -> EngineServices: 

2327 return EngineServices.open(ConfigurationResolver().resolve(path)) 

2328 

2329 @contextmanager 

2330 def _run_services(self, path: Path, reference: str) -> Iterator[tuple[EngineServices, str]]: 

2331 """The services of a run's own workspace: the worktree of an isolated run (#55), else 

2332 the workspace of ``path``.""" 

2333 with self._services(path) as services: 

2334 run_id = self._run_id(services, reference) 

2335 record = isolation_record(services, run_id) 

2336 target = Path(services.state.get("execution", run_id, Execution).workspace) 

2337 if ( 

2338 record is not None 

2339 and record.get("status") == "CREATED" 

2340 and target.is_dir() 

2341 and target.resolve() != services.paths.workspace 

2342 ): 

2343 isolated = self._open_services(target) 

2344 try: 

2345 yield isolated, run_id 

2346 finally: 

2347 isolated.close() 

2348 return 

2349 yield services, run_id 

2350 

2351 @staticmethod 

2352 def _retrospective(services: EngineServices, execution_id: str) -> Retrospective: 

2353 services.state.get("execution", execution_id, Execution) 

2354 records = services.state.list("retrospective", Retrospective, execution_id=execution_id) 

2355 if not records: 

2356 raise NotFoundError(f"run has no retrospective yet: {execution_id}") 

2357 return records[-1] 

2358 

2359 @staticmethod 

2360 def _recommendation_key(recommendation_id: str) -> str: 

2361 return f"recommendation/{recommendation_id}" 

2362 

2363 def _decider( 

2364 self, services: EngineServices, actor_id: str | None, default: str = DEFAULT_CLI_ACTOR 

2365 ) -> tuple[str, str | None]: 

2366 """The actor id (and display name) of the person acting: the explicit ``--actor``, else 

2367 the Git user under ``governance.deciderIdentity: git``, else ``default``. 

2368 

2369 Where it came from is kept in ``last_identity_source``: ``explicit``, ``git``, 

2370 ``fallback`` (the Git user was asked for but Git has no usable ``user.email`` or 

2371 ``user.name``: the 1.0.0 default is used and a notice says so) or ``default``.""" 

2372 if actor_id: 

2373 self.last_identity_source = "explicit" 

2374 return actor_id, None 

2375 if services.resolved.project.governance_settings.git_decider: 

2376 name, email = GitAdapter(services.paths.workspace).user_identity() 

2377 try: 

2378 decider = actor_id_from_identity(name, email) 

2379 except ConfigurationError: 

2380 self.last_identity_source = "fallback" 

2381 self.notices.append( 

2382 f"governance.deciderIdentity is git but Git has no usable user.email or " 

2383 f"user.name; recorded the actor as {default}. Set them with git config " 

2384 f"user.email / user.name, or pass --actor" 

2385 ) 

2386 return default, None 

2387 self.last_identity_source = "git" 

2388 return decider, identity_display_name(name, email) 

2389 self.last_identity_source = "default" 

2390 return default, None 

2391 

2392 @staticmethod 

2393 def _human_provenance( 

2394 actor_id: str, *, source_refs: tuple[str, ...] = (), display_name: str | None = None 

2395 ) -> Provenance: 

2396 return Provenance( 

2397 actor=Actor(actor_type=ActorType.HUMAN, actor_id=actor_id, display_name=display_name), 

2398 core_version=__version__, 

2399 source_refs=source_refs, 

2400 ) 

2401 

2402 @staticmethod 

2403 def _project_memory(store: MemoryStore, memory_id: str, project_id: str) -> MemoryRecord: 

2404 record = store.get(memory_id) 

2405 if record.project_id != project_id: 2405 ↛ 2406line 2405 didn't jump to line 2406 because the condition on line 2405 was never true

2406 raise NotFoundError(f"memory not found: {memory_id}") 

2407 return record 

2408 

2409 @staticmethod 

2410 def _count_by(items: list[Any], field: str) -> dict[str, int]: 

2411 counts: dict[str, int] = {} 

2412 for item in items: 

2413 value = getattr(item, field) 

2414 key = value.value if hasattr(value, "value") else str(value) 

2415 counts[key] = counts.get(key, 0) + 1 

2416 return counts 

2417 

2418 @staticmethod 

2419 def render_json(value: Any) -> str: 

2420 if hasattr(value, "model_dump"): 

2421 value = value.model_dump(mode="json", by_alias=True) 

2422 elif isinstance(value, list): 

2423 value = [ 

2424 item.model_dump(mode="json", by_alias=True) if hasattr(item, "model_dump") else item 

2425 for item in value 

2426 ] 

2427 return json.dumps(value, indent=2, ensure_ascii=False, default=str) 

2428 

2429 

2430def _verify_hint(services: EngineServices, invalid: list[str]) -> str: 

2431 """The next step after a run that does not verify (#157): nothing repairs the record, so 

2432 the run is inspected and its task is done again in a new run.""" 

2433 steps: list[str] = [] 

2434 for execution_id in invalid: 

2435 try: 

2436 task_id = services.state.get("execution", execution_id, Execution).task_id 

2437 except NotFoundError: 

2438 task_id = "<taskId>" 

2439 steps.append( 

2440 f"`harness status --run {execution_id}` shows the run; nothing repairs its record " 

2441 f"(an export refuses it): `harness run cancel --run {execution_id}` ends it " 

2442 f"and `harness run start --task {task_id}` does the task again" 

2443 ) 

2444 return "; ".join(steps) + "."