File size: 5,288 Bytes
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c35ac38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c35ac38
2a9dc4c
c35ac38
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c35ac38
2a9dc4c
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
"""External Python LanguageAdapter conforming to the LingoLOGOS codex contract."""

from __future__ import annotations

import os
from pathlib import Path
from typing import Dict, List, Sequence, Tuple

from lingologos_python._codex_bridge import ensure_codex_on_path

ensure_codex_on_path()

from lingologos_codex.adapter_contract import AdapterMetadata, BaseLanguageAdapter  # noqa: E402
from lingologos_codex.types import GateResult  # noqa: E402

from lingologos_python.ast_graph import extract_python_graph  # noqa: E402
from lingologos_python.gates import (  # noqa: E402
    SIGNATURE_RULES,
    parse_failed_targets,
    resolve_tool_gate_prefix,
    run_python_tests,
    run_syntax_gate,
    run_tool_gate,
)
from lingologos_python.test_selector import select_python_tests  # noqa: E402

ADAPTER_NAME = "lingologos-python"
ADAPTER_VERSION = "0.1.0"

# The wall-clock budget every runner command obeys. The kernel instantiates this
# class from a reference string and cannot pass it a per-session number, so the
# environment is the channel the session uses to hand it down.
GATE_TIMEOUT_ENV = "LINGOLOGOS_PY_GATE_TIMEOUT"
DEFAULT_GATE_TIMEOUT_SEC = 120.0


def _resolve_gate_timeout(timeout_sec: float | None) -> float:
    """An explicit argument wins; otherwise the environment names it; otherwise 120 s."""
    if timeout_sec is not None:
        return float(timeout_sec)
    try:
        value = float(os.environ.get(GATE_TIMEOUT_ENV, ""))
    except ValueError:
        return DEFAULT_GATE_TIMEOUT_SEC
    return value if value > 0 else DEFAULT_GATE_TIMEOUT_SEC

DEFAULT_TOOL_ARGS: Dict[str, Tuple[str, ...]] = {
    "mypy": ("--ignore-missing-imports", "--no-incremental"),
    "pyright": (),
    "ruff": ("check", "--no-cache"),
    "flake8": (),
}


class PythonLanguageAdapter(BaseLanguageAdapter):
    """Full-featured external Python adapter built on lingologos_codex.BaseLanguageAdapter.

    By default it runs the in-process syntax and compile gate plus any static
    checkers explicitly requested or discovered when enabled. Calling with
    ``require_tools=("mypy", "ruff")`` enforces those tools strictly: when a
    required tool is missing on the host, the gate returns ABSTAIN so the
    codex arbiter refuses to guess.
    """

    def __init__(
        self,
        workspace_root: str | Path,
        *,
        require_tools: Sequence[str] = (),
        use_installed_tools: bool = False,
        timeout_sec: float | None = None,
    ) -> None:
        super().__init__(workspace_root, timeout_sec=_resolve_gate_timeout(timeout_sec))
        self.require_tools: Tuple[str, ...] = tuple(require_tools)
        self.use_installed_tools: bool = bool(use_installed_tools)

    def meta(self) -> AdapterMetadata:
        return AdapterMetadata(
            name=ADAPTER_NAME,
            languages=("python",),
            extensions=(".py", ".pyi"),
            version=ADAPTER_VERSION,
        )

    def command_env(self) -> Dict[str, str]:
        root_str = str(self.workspace_root)
        existing = os.environ.get("PYTHONPATH", "")
        pythonpath = f"{root_str}{os.pathsep}{existing}" if existing else root_str
        return {"PYTHONDONTWRITEBYTECODE": "1", "PYTHONPATH": pythonpath}

    def extract_symbols_and_edges(
        self, workspace: str, files: Sequence[str]
    ) -> Tuple[List[str], List[Tuple[str, str]]]:
        cwd = self._checked_cwd(workspace)
        return extract_python_graph(cwd, files)

    def select_tests(self, workspace: str, changed_files: Sequence[str]) -> List[str]:
        cwd = self._checked_cwd(workspace)
        return select_python_tests(cwd, changed_files)

    def run_typecheck_and_lint(
        self, workspace: str, target_files: Sequence[str]
    ) -> List[GateResult]:
        cwd = self._checked_cwd(workspace)
        gates: List[GateResult] = [run_syntax_gate(cwd, target_files)]
        if not target_files:
            return gates

        tools_to_run: List[str] = list(self.require_tools)
        if self.use_installed_tools:
            for candidate in ("mypy", "ruff"):
                if candidate not in tools_to_run and resolve_tool_gate_prefix(candidate) is not None:
                    tools_to_run.append(candidate)

        for tool in tools_to_run:
            args = DEFAULT_TOOL_ARGS.get(tool, ())
            gates.append(run_tool_gate(self, cwd, tool, args, target_files))
        return gates

    def run_tests(
        self, workspace: str, targets: Sequence[str], full_suite: bool = False
    ) -> GateResult:
        cwd = self._checked_cwd(workspace)
        return run_python_tests(self, cwd, targets, full_suite=full_suite)

    def failed_targets_from_output(self, output: str) -> Tuple[str, ...]:
        return parse_failed_targets(output)

    def signature_rules(self) -> Tuple[Tuple[str, str], ...]:
        return SIGNATURE_RULES


class StrictPythonLanguageAdapter(PythonLanguageAdapter):
    """Variant that always demands mypy and ruff, abstaining when either is absent."""

    def __init__(self, workspace_root: str | Path, timeout_sec: float | None = None) -> None:
        super().__init__(
            workspace_root,
            require_tools=("mypy", "ruff"),
            use_installed_tools=False,
            timeout_sec=timeout_sec,
        )