"""Measure a phase's closure metric against the real target repository. The metric is the one place in a phased campaign where ground truth, not prose, decides whether a phase is done. Everything here is deterministic and fails closed: a command that errors, times out, or prints anything other than a single integer is a measurement failure, never a pass. """ from __future__ import annotations import os import subprocess from datetime import datetime, timezone from pathlib import Path from afk_developer.campaign_models import ClosureMetric from afk_developer.environment import _normalize_interpreter, _project_venv_python DEFAULT_METRIC_TIMEOUT_SECONDS = 300 PYTHON_PLACEHOLDER = "{python}" class ClosureMetricError(RuntimeError): """Raised when a closure metric cannot be measured trustworthily.""" def resolve_metric_command( metric: ClosureMetric, project_dir: Path, *, target_python: Path | str | None = None ) -> str: """Substitute ``{python}`` with the target interpreter; refuse ambient fallback.""" if PYTHON_PLACEHOLDER not in metric.command: return metric.command # Never resolve(): a venv's bin/python is a symlink to the base interpreter, # and following it runs {python} outside the venv that holds pytest and ruff. interpreter = ( _normalize_interpreter(target_python) if target_python else _project_venv_python(project_dir) ) if interpreter is None or not interpreter.is_file(): raise ClosureMetricError( f"Closure metric '{metric.name}' uses {PYTHON_PLACEHOLDER} but no target interpreter " "is available (set AFK_TARGET_PYTHON or create a project-local .venv)." ) return metric.command.replace(PYTHON_PLACEHOLDER, f'"{interpreter}"') def measure_closure_metric( metric: ClosureMetric, project_dir: Path, *, target_python: Path | str | None = None, timeout: int = DEFAULT_METRIC_TIMEOUT_SECONDS, ) -> int: """Run the metric command in ``project_dir`` and return its integer reading.""" command = resolve_metric_command(metric, project_dir, target_python=target_python) environment = os.environ.copy() environment["PYTHONDONTWRITEBYTECODE"] = "1" try: result = subprocess.run( command, shell=True, cwd=str(project_dir), env=environment, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout, ) except subprocess.TimeoutExpired as exc: raise ClosureMetricError( f"Closure metric '{metric.name}' timed out after {timeout}s: {command}" ) from exc except OSError as exc: raise ClosureMetricError(f"Closure metric '{metric.name}' could not start: {exc}") from exc if result.returncode != 0: detail = (result.stderr or result.stdout or "").strip()[-1_000:] raise ClosureMetricError( f"Closure metric '{metric.name}' exited {result.returncode}: {detail or command}" ) return parse_metric_output(metric, result.stdout or "") def parse_metric_output(metric: ClosureMetric, stdout: str) -> int: lines = [line.strip() for line in stdout.splitlines() if line.strip()] if len(lines) != 1: raise ClosureMetricError( f"Closure metric '{metric.name}' must print exactly one integer line; got " f"{len(lines)} non-empty line(s): {stdout.strip()[-500:]!r}" ) try: return int(lines[0]) except ValueError as exc: raise ClosureMetricError( f"Closure metric '{metric.name}' printed a non-integer: {lines[0]!r}" ) from exc def record_measurement(metric: ClosureMetric, value: int, *, at_start: bool = False) -> None: metric.last_value = value metric.last_measured_at = datetime.now(timezone.utc) if at_start: metric.start_value = value