File size: 7,673 Bytes
79a3ba9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a9dc4c
79a3ba9
2a9dc4c
79a3ba9
 
 
 
 
 
 
 
2a9dc4c
79a3ba9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62eac4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79a3ba9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""The command line is a published interface, so it is run as a process here.

Nothing in this file reaches into the CLI module. Each test starts the same process a
reader of the card would start, and asserts on the exit code and on the text that comes
back, because a documented command that crashes is a broken promise even when every
library call beside it is correct.
"""

from __future__ import annotations

import hashlib
import json
import subprocess
import sys
from pathlib import Path
from typing import Any, Dict

from lingologos_python.patterns import PATTERNS

from lingologos_python.rules import RULE_IDS

ROOT = Path(__file__).resolve().parents[1]
LAB = ROOT / "fixtures" / "pattern_lab"
SAMPLE = ROOT / "fixtures" / "sample_pkg"


def run_cli(*args: str) -> subprocess.CompletedProcess:
    return subprocess.run(
        [sys.executable, "-B", "-m", "lingologos_python", *args],
        cwd=str(ROOT),
        capture_output=True,
        text=True,
    )


def _tree_state(root: Path) -> Dict[str, str]:
    state = {}
    for path in sorted(root.rglob("*")):
        if path.is_file():
            digest = hashlib.sha256(path.read_bytes()).hexdigest()
            state[str(path.relative_to(root))] = digest
    return state


def test_patterns_list_prints_every_card_once_in_a_stable_order() -> None:
    proc = run_cli("patterns", "list")
    assert proc.returncode == 0, proc.stdout + proc.stderr
    lines = [line for line in proc.stdout.splitlines() if line.strip()]
    assert len(lines) == len(PATTERNS)
    assert [line.split()[0] for line in lines] == sorted(PATTERNS)
    for line in lines:
        assert line.split()[1] in {"contracts", "mutation", "resources", "shape", "typing"}


def test_patterns_list_json_carries_the_fields_a_reader_needs() -> None:
    proc = run_cli("patterns", "list", "--json")
    assert proc.returncode == 0, proc.stdout + proc.stderr
    rows = json.loads(proc.stdout)["patterns"]
    assert [row["pattern_id"] for row in rows] == sorted(PATTERNS)
    for row in rows:
        assert set(row) == {
            "pattern_id",
            "family",
            "intent_tags",
            "min_assurance",
            "rule",
            "companions",
        }
        assert row["rule"] in RULE_IDS
        assert row["companions"]
        assert row["min_assurance"] >= 2


def test_patterns_show_answers_for_one_card_in_text_and_in_json() -> None:
    proc = run_cli("patterns", "show", "--pattern", "chain-to-registry")
    assert proc.returncode == 0, proc.stdout + proc.stderr
    for part in ("shape", "why", "needs", "lock", "refuses"):
        assert part in proc.stdout
    assert "BRANCH_SHAPE_MISMATCH" in proc.stdout

    proc = run_cli("patterns", "show", "--pattern", "chain-to-registry", "--json")
    assert proc.returncode == 0, proc.stdout + proc.stderr
    payload: Dict[str, Any] = json.loads(proc.stdout)
    assert payload["pattern_id"] == "chain-to-registry"
    assert payload["lock_claims"]


def test_an_unknown_card_and_a_missing_flag_answer_before_any_work_starts() -> None:
    proc = run_cli("patterns", "show", "--pattern", "no-such-card")
    assert proc.returncode == 2
    assert "unknown pattern" in proc.stderr

    proc = run_cli("patterns", "scan", "--workspace", str(LAB))
    assert proc.returncode == 2
    assert "--pattern" in proc.stderr

    proc = run_cli("patterns", "apply", "--pattern", "chain-to-registry")
    assert proc.returncode == 2
    assert "--workspace" in proc.stderr


def test_patterns_scan_names_the_functions_in_the_shape_of_the_card() -> None:
    proc = run_cli("patterns", "scan", "--workspace", str(LAB), "--pattern", "chain-to-registry")
    assert proc.returncode == 0, proc.stdout + proc.stderr
    assert "src/registry.py::render" in proc.stdout
    assert "render_pair" not in proc.stdout


def test_patterns_scan_shows_the_edits_a_hit_would_apply_and_dumps_nothing() -> None:
    proc = run_cli("patterns", "scan", "--workspace", str(LAB), "--pattern", "chain-to-registry")
    assert proc.returncode == 0, proc.stdout + proc.stderr
    lines = [line.strip() for line in proc.stdout.splitlines() if line.strip()]
    assert lines[0] == "chain-to-registry: 1 hit(s) in this workspace"
    assert lines[1] == "src/registry.py::render"
    assert lines[2].startswith("src/registry.py")
    assert lines[3].startswith("tests/test_registry.py")
    assert any(line.startswith("why:") for line in lines)
    for noise in ("RuleHit", "Edit(", "evidence=", "Traceback"):
        assert noise not in proc.stdout


def test_patterns_scan_json_carries_the_edits_a_reader_can_act_on() -> None:
    proc = run_cli(
        "patterns",
        "scan",
        "--workspace",
        str(LAB),
        "--pattern",
        "chain-to-registry",
        "--json",
    )
    assert proc.returncode == 0, proc.stdout + proc.stderr
    payload: Dict[str, Any] = json.loads(proc.stdout)
    assert payload["pattern"] == "chain-to-registry"
    assert len(payload["hits"]) == 1
    hit = payload["hits"][0]
    assert hit["target"] == "src/registry.py::render"
    assert hit["rule"] == "chain-to-registry"
    assert [edit["file"] for edit in hit["edits"]] == ["src/registry.py", "tests/test_registry.py"]
    for edit in hit["edits"]:
        assert edit["search"] and edit["replace"] and edit["label"]
    assert hit["evidence"] and all(hit["evidence"])


def test_patterns_scan_says_so_when_nothing_in_the_workspace_qualifies() -> None:
    proc = run_cli("patterns", "scan", "--workspace", str(SAMPLE), "--pattern", "chain-to-registry")
    assert proc.returncode == 0, proc.stdout + proc.stderr
    assert "no function in this workspace has the shape of this card" in proc.stdout


def test_apply_dry_run_verifies_the_pair_without_writing_it(pattern_lab: Path) -> None:
    before = _tree_state(pattern_lab)
    proc = run_cli(
        "patterns",
        "apply",
        "--workspace",
        str(pattern_lab),
        "--pattern",
        "chain-to-registry",
        "--target",
        "src/registry.py::render",
        "--dry-run",
    )
    assert proc.returncode == 0, proc.stdout + proc.stderr
    assert "VERIFIED" in proc.stdout
    assert "committed=False" in proc.stdout
    assert _tree_state(pattern_lab) == before


def test_a_shape_the_card_does_not_claim_exits_non_zero_and_writes_nothing(pattern_lab: Path) -> None:
    before = _tree_state(pattern_lab)
    proc = run_cli(
        "patterns",
        "apply",
        "--workspace",
        str(pattern_lab),
        "--pattern",
        "chain-to-registry",
        "--target",
        "src/registry.py::render_pair",
        "--dry-run",
    )
    assert proc.returncode == 1
    assert "REFUSED" in proc.stdout
    assert "BRANCH_SHAPE_MISMATCH" in proc.stdout
    assert "nothing was written" in proc.stdout
    assert _tree_state(pattern_lab) == before


def test_symbols_names_the_functions_of_a_workspace_and_ranks_them() -> None:
    proc = run_cli("symbols", "--workspace", str(LAB), "--limit", "200")
    assert proc.returncode == 0, proc.stdout + proc.stderr
    assert "files=" in proc.stdout
    assert "src/registry.py::render" in proc.stdout


def test_select_tests_answers_with_the_tests_that_import_the_changed_file() -> None:
    proc = run_cli("select-tests", "--workspace", str(LAB), "--files", "src/registry.py")
    assert proc.returncode == 0, proc.stdout + proc.stderr
    assert "tests/test_registry.py" in proc.stdout.split()


def test_the_adapter_answers_the_contract_of_the_kernel() -> None:
    proc = run_cli("check-adapter", "--workspace", str(SAMPLE))
    assert proc.returncode == 0, proc.stdout + proc.stderr
    assert "ADAPTER OK" in proc.stdout