File size: 9,688 Bytes
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e1de134
 
2a9dc4c
 
e1de134
2a9dc4c
e1de134
 
 
 
 
2a9dc4c
e1de134
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e1de134
2a9dc4c
e1de134
 
 
2a9dc4c
 
e1de134
 
 
 
 
 
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e1de134
 
 
 
 
 
 
2a9dc4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e1de134
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a9dc4c
 
 
 
 
 
 
1ed2d7f
 
 
 
2a9dc4c
1ed2d7f
 
 
 
 
2a9dc4c
e1de134
 
 
 
 
 
 
 
 
2a9dc4c
 
 
 
 
e1de134
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
"""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<target>[\w./\\-]+(?:::\S+)?)",
    r"^(?P<target>[\w./\\-]+\.py):\d+:",
    r'E\s+File "(?P<target>[^"]+)"',
    r'File "(?P<target>[^"]+\.py)", line \d+',
    r"ERROR: .* \((?P<target>[\w./\\-]+\.py)\)",
)

SIGNATURE_RULES: Tuple[Tuple[str, str], ...] = (
    (r"in [\d.]+s", "in <t>"),
    (r"Ran \d+ tests? in [\d.]+s", "Ran <n> tests in <t>"),
    (r"rootdir: \S+", "rootdir: <path>"),
    (r"plugins?: \S.*", "plugins: <set>"),
    (r"Found \d+ errors? in \d+ files?", "Found <n> errors in <m> files"),
)


def _read_text_state(cwd: Path, rel: str) -> Tuple[str | None, str]:
    """Return (source, state) for one workspace file: ok, missing, undecodable or unreadable."""
    target = cwd / Path(*rel.replace("\\", "/").split("/"))
    if not target.is_file() or target.is_symlink():
        return None, "missing"
    try:
        # utf-8-sig: a byte-order mark is not part of the code, and the compiler
        # reading the file would skip it the same way.
        return target.read_text(encoding="utf-8-sig"), "ok"
    except UnicodeDecodeError:
        return None, "undecodable"
    except OSError:
        return None, "unreadable"


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 <tool>."""
    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] = []
    silent: List[str] = []
    for rel in files:
        source, state = _read_text_state(cwd, rel)
        if state == "missing":
            broken.append(f"{rel}: missing")
            failed.append(rel)
            continue
        if source is None:
            # A file that is not UTF-8 text gives the gate nothing to parse. Calling
            # that a syntax error would be a lie about the file, and calling it a
            # pass would be a lie about the gate: it simply has no judgement.
            silent.append(f"{rel}: {state}")
            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",
        )
    if silent:
        return GateResult(
            ABSTAIN,
            command,
            output="\n".join(silent),
            note=f"{len(silent)} file(s) could not be read as UTF-8 text, the gate has no judgement on them",
        )
    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 _ran_no_tests(output: str) -> bool:
    """True when a test runner reported that it ran zero tests."""
    low = (output or "").lower()
    return "no tests ran" in low or "ran 0 tests" in low


def _zero_run_is_an_abstain(gate: GateResult) -> GateResult:
    """A runner that collected nothing cannot confirm or reject anything.

    The unittest fallback imports the target module and asks unittest to collect
    it. Tests written for pytest stay invisible there, so unittest reports an
    empty run and exits. Reporting that as REJECTED would invent a failure, and
    as CONFIRMED would invent a pass, so the gate abstains and says so.
    """
    if _ran_no_tests(gate.output or ""):
        return GateResult(
            ABSTAIN,
            gate.command,
            output=gate.output,
            note="the test runner collected no tests, the gate has no judgement",
        )
    return gate


def _unittest_module_names(targets: Sequence[str]) -> Tuple[List[str], List[str]]:
    """Map relative test paths to importable dotted module names for unittest."""
    names: List[str] = []
    unmapped: List[str] = []
    for target in targets:
        parts = [p for p in target.replace("\\", "/").split("/") if p and p != "."]
        if parts and parts[-1].endswith(".py"):
            parts = [*parts[:-1], parts[-1][:-3]]
        if parts and parts[-1] == "__init__":
            parts = parts[:-1]
        if not parts or ".." in parts or not all(p.isidentifier() for p in parts):
            unmapped.append(target)
            continue
        names.append(".".join(parts))
    return names, unmapped


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 _zero_run_is_an_abstain(
                adapter.run_command(cwd.as_posix(), argv, gate_name="full_regression")
            )
        return _zero_run_is_an_abstain(
            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 _zero_run_is_an_abstain(
                adapter.run_command(cwd.as_posix(), argv, gate_name="full_regression")
            )
        modules, unmapped = _unittest_module_names(targets)
        if unmapped:
            # unittest takes importable names, not file paths. Passing a path
            # through would exit with an import error that says nothing about
            # the code, so the gate refuses to judge rather than misjudge.
            return GateResult(
                ABSTAIN,
                "python -m unittest -q " + " ".join(str(t) for t in unmapped),
                note="these targets are not importable module names for the unittest fallback: "
                + ", ".join(str(t) for t in unmapped),
            )
        argv = [sys.executable, "-m", "unittest", "-q", *modules]
        return _zero_run_is_an_abstain(
            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])