"""Locate, plan, apply, prove. The edit pair is one transaction. Section 5 of SPECIFICATION.md: the source edit and the lock test are written together or not at all. The honesty gate reads the pair back from disk and refuses when the test was not written first in the record, or when the edit removed an assertion. """ import ast import os import shutil import subprocess import sys from typing import Any, Dict, List, Optional, Tuple from . import catalog, preflight, shapes TEST_DIR = "tests" RECORD_NAME = "_thinkingpython_locks" def locate(workspace: str, frame: str, anchor: Optional[str], entries: List[Dict[str, Any]]) -> Tuple[List[Dict[str, Any]], List[str]]: """Return candidates: {file, target, entry} plus reasons.""" reasons: List[str] = [] found: List[Dict[str, Any]] = [] for rel in preflight.python_files(workspace): if rel.startswith(TEST_DIR + "/"): continue path = os.path.join(workspace, rel) try: with open(path, "r", encoding="utf-8") as handle: source = handle.read() except (OSError, UnicodeDecodeError): reasons.append("NOT_ASCII_TARGET") continue hits, why = shapes.match(frame, source) if not hits: if why and why != "NO_SHAPE": reasons.append(why) continue if anchor: picked = [h for h in hits if h.get("symbol") == anchor] or hits else: picked = hits entry = catalog.by_id(entries, frame) or {} for target in picked: found.append({"file": rel, "target": target, "entry": entry, "evidence": target.get("evidence", "")}) if not found: reasons.append("NO_MATCH") return found[:catalog.MAX_CANDIDATES], sorted(set(reasons)) def plan(candidate: Dict[str, Any]) -> Dict[str, Any]: """The plan is language free: frame, file, line window, edits, lock.""" entry = candidate["entry"] rel = candidate["file"] target = candidate["target"] with open(os.path.join(os.getcwd(), rel) if not os.path.isabs(rel) else rel, "r", encoding="utf-8") as handle: source = handle.read() return {"frame": entry.get("id", ""), "file": rel, "line": target["line"], "end": target["end"], "symbol": target["symbol"], "edits": shapes.edits(entry.get("id", ""), rel, source, target), "lock": shapes.lock(entry.get("id", ""), target), "expected": list(entry.get("refusals") or [])} def run_suite(workspace: str, timeout: int = 120) -> Dict[str, Any]: try: proc = subprocess.run([sys.executable, "-m", "pytest", "-q", "--no-header", TEST_DIR], cwd=workspace, capture_output=True, text=True, timeout=timeout) except subprocess.TimeoutExpired: return {"status": "SUITE_RED", "output": "timeout"} out = (proc.stdout or "") + (proc.stderr or "") return {"status": "GREEN" if proc.returncode == 0 else "SUITE_RED", "output": out[-4000:]} def _drops_assertion(edits: List[Dict[str, str]], source: str) -> bool: for edit in edits: if "assert" in (edit.get("search") or "") and "assert" not in (edit.get("replace") or ""): return True projected = source for edit in edits: if edit.get("search"): projected = projected.replace(edit["search"], edit.get("replace", ""), 1) try: before = sum(1 for n in ast.walk(ast.parse(source)) if isinstance(n, ast.Assert)) after = sum(1 for n in ast.walk(ast.parse(projected)) if isinstance(n, ast.Assert)) except SyntaxError: return False return after < before def apply_pair(workspace: str, planned: Dict[str, Any]) -> Dict[str, Any]: """Write source edit and lock test in one transaction. Returns a receipt.""" if not planned.get("edits"): return {"applied": False, "reason": "NO_EDIT"} probe = os.path.join(workspace, TEST_DIR, "test_lock_%s.py" % planned["symbol"]) if os.path.exists(probe): return {"applied": False, "reason": "ALREADY_APPLIED"} try: with open(os.path.join(workspace, plan_rel(planned)), "r", encoding="utf-8") as handle: original_source = handle.read() except OSError: return {"applied": False, "reason": "SEARCH_NOT_FOUND"} if _drops_assertion(planned["edits"], original_source): return {"applied": False, "reason": "ASSERTION_REMOVED"} backup: Dict[str, Optional[str]] = {} written: List[str] = [] try: for edit in planned["edits"]: rel = edit["file"] path = os.path.join(workspace, rel) if os.path.islink(path): raise OSError("LINKED_PATH_IN_WORKSPACE") with open(path, "r", encoding="utf-8") as handle: original = handle.read() if rel not in backup: backup[rel] = original if edit["search"] not in original: raise ValueError("SEARCH_NOT_FOUND") new = original.replace(edit["search"], edit["replace"], 1) ast.parse(new) with open(path, "w", encoding="utf-8") as handle: handle.write(new) written.append(rel) lock_path = os.path.join(workspace, TEST_DIR, "test_lock_%s.py" % planned["symbol"]) os.makedirs(os.path.dirname(lock_path), exist_ok=True) if os.path.exists(lock_path): raise ValueError("ALREADY_APPLIED") backup[os.path.relpath(lock_path, workspace).replace("\\", "/")] = None with open(lock_path, "w", encoding="utf-8") as handle: handle.write(_lock_header(plan_rel(planned)) + planned["lock"]) written.append(os.path.relpath(lock_path, workspace).replace("\\", "/")) except Exception as exc: # rollback reason = str(exc) if str(exc) in ("LINKED_PATH_IN_WORKSPACE", "ALREADY_APPLIED") \ else "PAIR_DISHONEST" for rel, original in backup.items(): path = os.path.join(workspace, rel) if original is None: if os.path.exists(path): os.remove(path) else: with open(path, "w", encoding="utf-8") as handle: handle.write(original) for rel in written: path = os.path.join(workspace, rel) if os.path.exists(path) and backup.get(rel) is None: os.remove(path) return {"applied": False, "reason": reason} return {"applied": True, "files": written} def plan_rel(planned: Dict[str, Any]) -> str: return str(planned.get("file", "")).replace("\\", "/") def _lock_header(rel: str) -> str: return ( '"""Lock test written with the edit that it pins. Do not edit by hand."""\n' "import ast\n" "import os\n\n" "ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n" "TARGET = os.path.join(ROOT, %(rel)r)\n\n" "def _source():\n" " with open(TARGET, 'r', encoding='utf-8') as handle:\n" " return handle.read()\n\n" "def _tree():\n" " return ast.parse(_source())\n\n" "def _is_doc(stmt):\n" " return (isinstance(stmt, ast.Expr) and isinstance(stmt.value, ast.Constant)\n" " and isinstance(stmt.value.value, str))\n\n" "def _function(name):\n" " for node in ast.walk(_tree()):\n" " if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name == name:\n" " return node\n" " raise AssertionError('no function named ' + name)\n\n" "def _imports_name(src, name):\n" " tree = ast.parse(src)\n" " for node in ast.walk(tree):\n" " if isinstance(node, ast.Import):\n" " for alias in node.names:\n" " if (alias.asname or alias.name).split('.')[0] == name:\n" " return True\n" " if isinstance(node, ast.ImportFrom):\n" " for alias in node.names:\n" " if (alias.asname or alias.name) == name:\n" " return True\n" " return False\n\n" ) % {"rel": rel} def verdict(receipt: Dict[str, Any], suite: Dict[str, Any]) -> Tuple[str, str]: if not receipt.get("applied"): return "REFUSED", receipt.get("reason", "NO_EDIT") if suite["status"] != "GREEN": return "REFUSED", suite["status"] return "VERIFIED", ""