"""Python quality and test gates with strict three-valued outcomes. Every gate returns GateResult(CONFIRMED | REJECTED | ABSTAIN). A missing toolchain never produces CONFIRMED or REJECTED; it returns ABSTAIN with a clear diagnostic note so the codex decision rule can block honestly. """ from __future__ import annotations import ast import importlib.util import re import shutil import sys from pathlib import Path from typing import TYPE_CHECKING, List, Sequence, Tuple from lingologos_python._codex_bridge import ensure_codex_on_path ensure_codex_on_path() from lingologos_codex.types import ABSTAIN, CONFIRMED, REJECTED, GateResult # noqa: E402 if TYPE_CHECKING: from lingologos_codex.adapter_contract import BaseLanguageAdapter FAILED_TARGET_PATTERNS: Tuple[str, ...] = ( r"FAILED (?P[\w./\\-]+(?:::\S+)?)", r"^(?P[\w./\\-]+\.py):\d+:", r'E\s+File "(?P[^"]+)"', r'File "(?P[^"]+\.py)", line \d+', r"ERROR: .* \((?P[\w./\\-]+\.py)\)", ) SIGNATURE_RULES: Tuple[Tuple[str, str], ...] = ( (r"in [\d.]+s", "in "), (r"Ran \d+ tests? in [\d.]+s", "Ran tests in "), (r"rootdir: \S+", "rootdir: "), (r"plugins?: \S.*", "plugins: "), (r"Found \d+ errors? in \d+ files?", "Found errors in files"), ) def _read_text_safe(cwd: Path, rel: str) -> str | None: target = cwd / Path(*rel.replace("\\", "/").split("/")) if not target.is_file() or target.is_symlink(): return None try: return target.read_text(encoding="utf-8", errors="replace") except OSError: return None def has_python_module(module_name: str) -> bool: """Return True when module_name is importable in the active Python interpreter.""" return importlib.util.find_spec(module_name) is not None def resolve_tool_argv(tool: str) -> List[str] | None: """Resolve a CLI tool binary on PATH or via python -m .""" binary = shutil.which(tool) if binary: return [binary] if has_python_module(tool): return [sys.executable, "-m", tool] return None def run_syntax_gate(cwd: Path, target_files: Sequence[str]) -> GateResult: """Validate Python syntax and code-object compilation in memory without writing .pyc.""" files = [f.replace("\\", "/") for f in target_files if f] if not files: return GateResult(CONFIRMED, "ast.parse + compile (no target files)") broken: List[str] = [] failed: List[str] = [] for rel in files: source = _read_text_safe(cwd, rel) if source is None: broken.append(f"{rel}: unreadable or missing") failed.append(rel) continue try: tree = ast.parse(source, filename=rel) compile(tree, filename=rel, mode="exec", dont_inherit=True) except SyntaxError as exc: broken.append(f"{rel}: line {exc.lineno}: {exc.msg}") failed.append(rel) except ValueError as exc: broken.append(f"{rel}: {exc}") failed.append(rel) command = "ast.parse " + " ".join(files) if broken: return GateResult( REJECTED, command, output="\n".join(broken), failed_targets=tuple(failed), note=f"{len(broken)} file(s) failed syntax verification", ) return GateResult(CONFIRMED, command) def run_tool_gate( adapter: BaseLanguageAdapter, cwd: Path, tool: str, args: Sequence[str], target_files: Sequence[str], ) -> GateResult: """Run an external Python static checker or return ABSTAIN when unavailable.""" argv_prefix = resolve_tool_gate_prefix(tool) if argv_prefix is None: return GateResult( ABSTAIN, f"{tool} {' '.join(args)}".strip(), note=f"{tool} is not installed on this host, the gate has no judgement", ) if not target_files: return GateResult(CONFIRMED, f"{tool} (no target files)") return adapter.run_command( cwd.as_posix(), [*argv_prefix, *args, *[f.replace("\\", "/") for f in target_files]], gate_name=tool, ) def resolve_tool_gate_prefix(tool: str) -> List[str] | None: """Resolve supported Python static analysis tools.""" return resolve_tool_argv(tool) def run_python_tests( adapter: BaseLanguageAdapter, cwd: Path, targets: Sequence[str], full_suite: bool = False, ) -> GateResult: """Run pytest (no cacheprovider) or fall back to unittest discovery.""" pytest_binary = shutil.which("pytest") if has_python_module("pytest"): # The active interpreter runs its own pytest, so the gate judges the same # environment the adapter and the kernel are running in. argv = [sys.executable, "-m", "pytest", "-q", "-p", "no:cacheprovider"] elif pytest_binary: argv = [pytest_binary, "-q", "-p", "no:cacheprovider"] else: argv = None if argv is not None: if full_suite or not targets: return adapter.run_command(cwd.as_posix(), argv, gate_name="full_regression") return adapter.run_command( cwd.as_posix(), argv + [t.replace("\\", "/") for t in targets], gate_name="selected_tests", ) if has_python_module("unittest"): if full_suite or not targets: argv = [sys.executable, "-m", "unittest", "discover", "-q"] return adapter.run_command(cwd.as_posix(), argv, gate_name="full_regression") argv = [sys.executable, "-m", "unittest", "-q", *[t.replace("\\", "/") for t in targets]] return adapter.run_command(cwd.as_posix(), argv, gate_name="selected_tests") return GateResult( ABSTAIN, "python -m pytest", note="neither pytest nor unittest is available in this interpreter", ) def parse_failed_targets(output: str) -> Tuple[str, ...]: """Extract normalized failed target paths or node ids from Python tool output.""" found: List[str] = [] for pattern in FAILED_TARGET_PATTERNS: for match in re.finditer(pattern, output, re.MULTILINE): value = match.group("target").replace("\\", "/") if value and value not in found: found.append(value) return tuple(found[:50])