"""Deterministic target-environment resolution for governed AFK runs.""" from __future__ import annotations import hashlib import json import os import subprocess import sys from dataclasses import dataclass from pathlib import Path from typing import Callable ENVIRONMENT_SCHEMA_VERSION = 1 _DEPENDENCY_INPUTS = ( "pyproject.toml", "requirements.txt", "requirements-dev.txt", "requirements-frozen.txt", "poetry.lock", "uv.lock", "pdm.lock", "Pipfile.lock", "pnpm-lock.yaml", "package-lock.json", "yarn.lock", ) def changed_dependency_inputs(paths: list[str]) -> list[str]: """Return governed root dependency inputs present in a reviewed change set.""" dependency_inputs = set(_DEPENDENCY_INPUTS) return sorted( normalized for path in paths if (normalized := path.replace("\\", "/").removeprefix("./")) in dependency_inputs ) class EnvironmentResolutionError(ValueError): """Raised when a requested explicit interpreter cannot be inspected.""" @dataclass(frozen=True) class EnvironmentFingerprint: interpreter: str implementation: str version: str prefix: str dependency_inputs: dict[str, str] fingerprint: str def to_record(self) -> dict[str, object]: return { "interpreter": self.interpreter, "implementation": self.implementation, "version": self.version, "prefix": self.prefix, "dependency_inputs": self.dependency_inputs, "fingerprint": self.fingerprint, } @dataclass(frozen=True) class EnvironmentContract: schema_version: int project_root: str runner: EnvironmentFingerprint target: EnvironmentFingerprint def to_record(self) -> dict[str, object]: return { "schema_version": self.schema_version, "project_root": self.project_root, "runner": self.runner.to_record(), "target": self.target.to_record(), } @dataclass(frozen=True) class EnvironmentResolution: contract: EnvironmentContract | None code: str = "" detail: str = "" @property def passed(self) -> bool: return self.contract is not None and not self.code def _normalize_interpreter(path: Path | str) -> Path: """Absolutise an interpreter path WITHOUT following symlinks. A virtualenv's bin/python is normally a symlink to the base interpreter, so Path.resolve() rewrites it to that base binary -- silently discarding the virtualenv whose site-packages hold pytest and ruff. On Linux that turns every project venv into ambient Python, which is precisely what this module promises never to do. (Windows venvs ship a real python.exe, which is why this only bites on POSIX.) """ return Path(os.path.abspath(os.path.expanduser(str(path)))) def resolve_environment_contract( project_dir: Path | str, *, runner_python: Path | str | None = None, target_python: Path | str | None = None, probe: Callable[[Path], tuple[str, str, str]] | None = None, ) -> EnvironmentResolution: """Resolve one target interpreter without ever falling back to ambient Python. A target is explicit through ``target_python`` or conventionally declared by a project-local ``.venv``. A missing target is a blocking result rather than a request to use the AFK runner or the shell's ``python`` command. """ root = Path(project_dir).resolve() if not root.is_dir(): return EnvironmentResolution( None, "project_root_missing", f"Project directory does not exist: {root}" ) target = _normalize_interpreter(target_python) if target_python else _project_venv_python(root) if target is None: return EnvironmentResolution( None, "target_interpreter_missing", "No explicit target interpreter was supplied and no project-local .venv interpreter exists.", ) runner = _normalize_interpreter(runner_python or sys.executable) if not runner.is_file(): return EnvironmentResolution( None, "runner_interpreter_missing", f"Runner interpreter is missing: {runner}" ) if not target.is_file(): return EnvironmentResolution( None, "target_interpreter_missing", f"Target interpreter is missing: {target}" ) inspect = probe or _probe_python try: runner_fingerprint = _fingerprint(runner, root, inspect) target_fingerprint = _fingerprint(target, root, inspect) except EnvironmentResolutionError as exc: return EnvironmentResolution(None, "environment_probe_failed", str(exc)) return EnvironmentResolution( EnvironmentContract( schema_version=ENVIRONMENT_SCHEMA_VERSION, project_root=str(root), runner=runner_fingerprint, target=target_fingerprint, ) ) def _project_venv_python(project_root: Path) -> Path | None: candidates = ( project_root / ".venv" / "Scripts" / "python.exe", project_root / ".venv" / "bin" / "python", ) return next( (_normalize_interpreter(candidate) for candidate in candidates if candidate.is_file()), None, ) def _fingerprint( interpreter: Path, project_root: Path, probe: Callable[[Path], tuple[str, str, str]], ) -> EnvironmentFingerprint: implementation, version, prefix = probe(interpreter) dependencies = _dependency_input_hashes(project_root) material = { "schema_version": ENVIRONMENT_SCHEMA_VERSION, "interpreter": str(interpreter), "implementation": implementation, "version": version, "prefix": prefix, "dependency_inputs": dependencies, } digest = hashlib.sha256( json.dumps(material, ensure_ascii=True, sort_keys=True, separators=(",", ":")).encode( "utf-8" ) ).hexdigest() return EnvironmentFingerprint( interpreter=str(interpreter), implementation=implementation, version=version, prefix=prefix, dependency_inputs=dependencies, fingerprint=digest, ) def _dependency_input_hashes(project_root: Path) -> dict[str, str]: return { path.name: hashlib.sha256(path.read_bytes()).hexdigest() for name in _DEPENDENCY_INPUTS if (path := project_root / name).is_file() } def _probe_python(interpreter: Path) -> tuple[str, str, str]: try: result = subprocess.run( [ str(interpreter), "-c", "import json,platform,sys; print(json.dumps([platform.python_implementation(), sys.version, sys.prefix]))", ], capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=15, check=False, ) except (OSError, subprocess.TimeoutExpired) as exc: raise EnvironmentResolutionError(f"Could not inspect {interpreter}: {exc}") from exc if result.returncode != 0: detail = (result.stderr or result.stdout).strip()[:500] raise EnvironmentResolutionError( f"Could not inspect {interpreter}: {detail or 'non-zero exit'}" ) try: implementation, version, prefix = json.loads(result.stdout) except (json.JSONDecodeError, ValueError) as exc: raise EnvironmentResolutionError( f"Interpreter probe returned invalid data: {interpreter}" ) from exc if not all(isinstance(value, str) and value for value in (implementation, version, prefix)): raise EnvironmentResolutionError( f"Interpreter probe returned incomplete data: {interpreter}" ) return implementation, version, prefix