tailot's picture
Upload folder using huggingface_hub
8947d88 verified
Raw History Blame
44.6 kB
"""Transactional Python programming session built on the LingoLOGOS codex kernel. A change is staged in an isolated copy of the workspace, evaluated by the six-node codex pipeline (either in-process or as six isolated subprocesses walking datasets/codex-python/topology.json), and committed atomically to the real workspace via lingologos_codex.fsadapter only when the arbiter reaches the required assurance threshold. """ from __future__ import annotations import ast import hashlib import json import os import shutil import stat import subprocess import sys import tempfile from dataclasses import dataclass, field from pathlib import Path from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple from lingologos_python._codex_bridge import ensure_codex_on_path ensure_codex_on_path() from lingologos_codex import envelope as _envelope # noqa: E402 from lingologos_codex.agents import ROLES, run_pipeline # noqa: E402 from lingologos_codex.failures import detect_stall_from_hashes # noqa: E402 from lingologos_codex.fsadapter import ( # noqa: E402 FileSystemAdapterError, create_os_filesystem_adapter, ) from lingologos_codex.fspolicy import ( # noqa: E402 EOL_PRESERVE, FSPolicy, OP_DELETE, OP_WRITE, PathGuard, PathSecurityError, PlannedOp, ) from lingologos_codex.patcher import ( # noqa: E402 FuzzyPatchConfig, SearchReplaceBlock, apply_controlled_fuzzy_patch, ) from lingologos_python.ast_graph import ( # noqa: E402 IGNORED_DIRS, discover_python_files, importers_of, ) from lingologos_python.patterns import PatternPlan, plan_pattern # noqa: E402 PYTHON_ROOT = Path(__file__).resolve().parent.parent DEFAULT_AGENT_SCRIPT = PYTHON_ROOT / "agents" / "python_agent.py" DEFAULT_TOPOLOGY_PATH = PYTHON_ROOT / "topology.json" DEFAULT_ALLOWED_PATTERNS: Tuple[str, ...] = ("*.py", "*.pyi") # Named session refusals, alongside the reason codes the rule catalog answers with. PATH_POLICY = "PATH_POLICY" PATCH_NOT_APPLIED = "PATCH_NOT_APPLIED" NODE_TIMEOUT = "NODE_TIMEOUT" LINKED_PATH_IN_WORKSPACE = "LINKED_PATH_IN_WORKSPACE" class NodeTimeoutError(RuntimeError): """A node subprocess exhausted its time budget instead of answering.""" class WorkspaceLinkError(ValueError): """The workspace holds a symlink or a junction whose copy cannot match the disk.""" DEFAULT_PROTECTED_PATTERNS: Tuple[str, ...] = ( "*.env", ".env*", "*.pem", "*.key", ".git/*", "__pycache__/*", ) ADAPTER_REF_DEFAULT = "lingologos_python.adapter:PythonLanguageAdapter" ADAPTER_REF_STRICT = "lingologos_python.adapter:StrictPythonLanguageAdapter" DEFAULT_GATES: Tuple[str, ...] = ("typecheck", "tests") @dataclass(frozen=True) class SessionResult: """Outcome of running the six-node codex pipeline over a Python workspace.""" case_id: str verdict: str assurance: int reason: str detail: str committed: bool touched_files: Tuple[str, ...] = () trace: Tuple[Dict[str, Any], ...] = field(default_factory=tuple) dossier: Dict[str, Any] = field(default_factory=dict) @property def accepted(self) -> bool: return self.verdict in ("VERIFIED", "SINGLE_PROVER") def to_dict(self) -> Dict[str, Any]: return { "case_id": self.case_id, "verdict": self.verdict, "assurance": self.assurance, "reason": self.reason, "detail": self.detail, "committed": self.committed, "touched_files": list(self.touched_files), "decision": dict(self.dossier.get("decision", {})), "gates": list(self.dossier.get("gates", [])), "checkers": list(self.dossier.get("checkers", [])), } def _disk_text(root: Path, rel_posix: str) -> str: """The current text of one workspace file, or an empty string when it is not there.""" path = root / Path(*rel_posix.split("/")) return path.read_text(encoding="utf-8", newline="") if path.is_file() else "" def _restore_originals( root: Path, originals: Dict[str, str], recreate: Sequence[str] = (), ) -> List[str]: """Put every named workspace path back to the text held in memory, listing failures.""" problems: List[str] = [] for rel_posix, text in originals.items(): target = root / Path(*rel_posix.split("/")) try: if text == "" and rel_posix not in recreate: # The pre-image of a created file is an absent path, so undoing a # create means removing the file the transaction left behind. if target.is_file(): target.unlink() else: target.parent.mkdir(parents=True, exist_ok=True) target.write_text(text, encoding="utf-8", newline="") except OSError: problems.append(rel_posix) return problems def _commit_or_restore( fs: Any, root: Path, writes: Dict[str, str], originals: Dict[str, str], recreate: Sequence[str] = (), ) -> Tuple[bool, str]: """Commit the verified writes, and restore the in-memory pre-images when the commit fails. The kernel transaction replaces one file at a time and attempts a best-effort rollback of its own when a replace fails part way, swallowing the errors of that rollback. The session does not trust it: it keeps every pre-image in memory, writes them back itself after any failure, and re-reads each written file once the commit reports success, so committed is only ever true when the verified text is the text on disk. """ tx = fs.begin_transaction() try: for rel_posix, text in writes.items(): fs.stage_write_text(tx, rel_posix, text) fs.commit_transaction(tx) except FileSystemAdapterError as exc: problems = _restore_originals(root, originals, recreate) if problems: return False, ( "the commit failed and these paths could not be restored from memory: " + ", ".join(problems) + " (" + str(exc) + ")" ) return False, "the commit failed, the workspace was restored from the in-memory originals: " + str(exc) drifted: List[str] = [] for rel_posix, text in writes.items(): on_disk = _disk_text(root, rel_posix) if on_disk != text and on_disk.replace("\r\n", "\n") != text.replace("\r\n", "\n"): drifted.append(rel_posix) if drifted: problems = _restore_originals(root, originals, recreate) if problems: return False, ( "the commit landed the wrong text and these paths could not be restored: " + ", ".join(problems) + " (drifted: " + ", ".join(drifted) + ")" ) return False, "the text on disk after the commit is not the verified text: " + ", ".join(drifted) return True, "" def _delete_or_restore( fs: Any, root: Path, rel_posix: str, original_text: str, ) -> Tuple[bool, str, str]: """Delete one workspace file through the kernel transaction, honestly reporting the outcome. Returns committed, the refusal reason code when it did not land, and the detail. A path the policy refuses is a named refusal, not a crash, and a transaction the disk refuses puts the file back from the in-memory original. """ tx = fs.begin_transaction() try: fs.stage_delete(tx, rel_posix) fs.commit_transaction(tx) except PathSecurityError as exc: return False, PATH_POLICY, "the path policy refused the delete: " + str(exc) except FileSystemAdapterError as exc: problems = _restore_originals(root, {rel_posix: original_text}, recreate=(rel_posix,)) if problems: return False, PATCH_NOT_APPLIED, ( "the delete failed and the file could not be restored from memory: " + str(exc) ) return False, PATCH_NOT_APPLIED, "the delete failed, the file was restored from the in-memory original: " + str(exc) target = root / Path(*rel_posix.split("/")) if target.exists(): return False, PATCH_NOT_APPLIED, "the file is still on disk after the delete commit: '%s'" % rel_posix return True, "", "" def _verify_probe(text: str) -> Tuple[str, str, str]: """A search, replace, text triple that annotates one line without breaking the file. The anchor is the first top level statement whose own line still parses once a comment is appended to it, so the probe cannot turn a valid workspace file into a syntax error. When nothing safer is found the first line is used as it has always been, and an empty file gets a probe text of its own. """ lines = text.splitlines(keepends=True) if not lines: return "# empty", "# empty verified", "# empty\n" probe_note = " # codex-verify-probe\n" try: tree = ast.parse(text) except SyntaxError: tree = None if tree is not None: for node in tree.body: if isinstance(node, ast.Expr) and isinstance(node.value, ast.Constant) and isinstance(node.value.value, str): continue line = lines[node.lineno - 1].rstrip("\r\n") if not line: continue candidate = line + probe_note try: ast.parse(text.replace(line, candidate, 1)) except SyntaxError: continue return line, candidate, text first = lines[0].rstrip("\r\n") return first, first + probe_note, text def _is_linked(path: Path) -> bool: """True when the path is a symlink or, on Windows, any reparse point such as a junction. Since Python 3.12 a Windows junction is no longer reported as a symlink, yet a directory walk still descends into it. The reparse attribute is the honest test. """ if path.is_symlink(): return True if os.name == "nt": try: attributes = path.lstat().st_file_attributes except OSError: return False return bool(attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT) return False def _copy_workspace_for_staging(src_root: Path, dst_root: Path) -> None: """Copy a workspace cleanly without caches or virtual environments. A symlink or a junction anywhere under the root is refused by name: a copy that quietly omits a link is not the workspace the six nodes were asked to judge, and a copy that follows one reaches files outside the workspace. """ root = src_root.resolve() for dirpath, dirnames, filenames in os.walk(src_root): dirnames[:] = [ d for d in dirnames if d not in IGNORED_DIRS and not d.endswith(".egg-info") ] rel_dir = Path(dirpath).resolve().relative_to(root) for name in dirnames: entry = Path(dirpath) / name if _is_linked(entry): raise WorkspaceLinkError( "linked directory in the workspace: '%s'" % (rel_dir / name).as_posix() ) target_dir = dst_root / rel_dir target_dir.mkdir(parents=True, exist_ok=True) for name in filenames: src_file = Path(dirpath) / name if _is_linked(src_file): raise WorkspaceLinkError( "linked file in the workspace: '%s'" % (rel_dir / name).as_posix() ) shutil.copy2(src_file, target_dir / name) def _subprocess_env() -> Dict[str, str]: env = dict(os.environ) env["PYTHONDONTWRITEBYTECODE"] = "1" python_pkg_root = str(PYTHON_ROOT) codex_root = str(ensure_codex_on_path()) existing = env.get("PYTHONPATH", "") parts = [python_pkg_root, codex_root] if existing: parts.append(existing) env["PYTHONPATH"] = os.pathsep.join(parts) return env def run_topology_subprocesses( case: Dict[str, Any], *, agent_script: Optional[Path] = None, timeout_sec: float = 120.0, ) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]: """Execute the six roles via isolated node subprocesses communicating over JSON stdio. The agent script is read from the module at call time, so a caller that names a different six-node executable gets it, and the per-node budget is the one asked for rather than one frozen at import. """ script = Path(agent_script) if agent_script else DEFAULT_AGENT_SCRIPT seed = _envelope.make_envelope("arbiter", 0, 0, "task received", dict(case)) trace: List[Dict[str, Any]] = [seed] current = seed env = _subprocess_env() for role in ROLES: cmd = [sys.executable, "-B", str(script), "--role", role, "--node-id", role] try: completed = subprocess.run( cmd, input=json.dumps(current), capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout_sec, cwd=str(PYTHON_ROOT), env=env, ) except subprocess.TimeoutExpired as exc: raise NodeTimeoutError( "node '%s' exhausted its %s s budget without answering" % (role, timeout_sec) ) from exc if completed.returncode != 0: raise RuntimeError( f"node '{role}' exited with {completed.returncode}: {completed.stderr.strip()}" ) current = json.loads(completed.stdout) trace.append(current) return trace, _envelope.read_dossier(current) class PythonWorkspaceSession: """High-level interface to inspect, edit, verify, and commit Python code via codex.""" def __init__( self, workspace_root: str | Path, *, allowed_patterns: Sequence[str] = DEFAULT_ALLOWED_PATTERNS, protected_patterns: Sequence[str] = DEFAULT_PROTECTED_PATTERNS, required_gates: Sequence[str] = DEFAULT_GATES, strict_tools: bool = False, spec_path: Optional[str | Path] = None, use_subprocesses: bool = False, min_assurance: int = 3, node_timeout_sec: float = 120.0, ) -> None: self.workspace_root = Path(workspace_root).resolve() if not self.workspace_root.is_dir(): raise FileNotFoundError(f"workspace does not exist: '{self.workspace_root}'") self.allowed_patterns = tuple(allowed_patterns) self.protected_patterns = tuple(protected_patterns) self.required_gates = tuple(required_gates) self.strict_tools = bool(strict_tools) self.spec_path = str(Path(spec_path).resolve()) if spec_path else None self.use_subprocesses = bool(use_subprocesses) self.min_assurance = int(min_assurance) self.node_timeout_sec = float(node_timeout_sec) def policy_dict(self, root: Optional[Path] = None) -> Dict[str, Any]: return { "repo_root": str((root or self.workspace_root).resolve()), "allowed_patterns": list(self.allowed_patterns), "protected_patterns": list(self.protected_patterns), "default_eol": EOL_PRESERVE, } def policy(self, root: Optional[Path] = None) -> FSPolicy: return FSPolicy( repo_root=str((root or self.workspace_root).resolve()), allowed_patterns=self.allowed_patterns, protected_patterns=self.protected_patterns, case_insensitive=(os.name == "nt"), default_eol=EOL_PRESERVE, ) def _os_fs(self, root: Path, *, check_allowed: bool = True): policy = FSPolicy( repo_root=str(root.resolve()), allowed_patterns=self.allowed_patterns if check_allowed else (), protected_patterns=self.protected_patterns, case_insensitive=(os.name == "nt"), default_eol=EOL_PRESERVE, ) fs = create_os_filesystem_adapter( root, protected_patterns=self.protected_patterns, allowed_patterns=self.allowed_patterns if check_allowed else (), ) fs.policy = policy fs.guard = PathGuard(policy) return fs def _adapter_fields(self) -> Dict[str, Any]: if self.spec_path: return {"spec": self.spec_path} return {"adapter": ADAPTER_REF_STRICT if self.strict_tools else ADAPTER_REF_DEFAULT} def _run_six_nodes(self, case: Dict[str, Any]) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]: try: if self.use_subprocesses: return run_topology_subprocesses(case, timeout_sec=self.node_timeout_sec) return run_pipeline(case) except NodeTimeoutError as exc: # A node that exhausts its budget abstains: the session answers # UNKNOWN with the named reason instead of a traceback or a verdict. return [], { "decision": { "verdict": "UNKNOWN", "assurance": 0, "reason": NODE_TIMEOUT, "detail": str(exc), } } def _link_refusal(self, case_id: str, rel_posix: str, exc: WorkspaceLinkError) -> SessionResult: """A workspace held together by links cannot be copied to staging faithfully.""" return SessionResult( case_id=case_id, verdict="REFUSED", assurance=0, reason=LINKED_PATH_IN_WORKSPACE, detail=str(exc), committed=False, touched_files=(rel_posix,), ) def list_files(self) -> List[str]: """Return all Python source files in the workspace.""" return discover_python_files(self.workspace_root) def verify( self, target_file: Optional[str] = None, *, case_id: str = "python-verify", note: str = "verify Python workspace against codex gates", ) -> SessionResult: """Verify an existing file or the whole Python workspace without modifying disk.""" py_files = self.list_files() chosen = (target_file or (py_files[0] if py_files else "src/__init__.py")).replace("\\", "/") target_path = self.workspace_root / Path(*chosen.split("/")) if target_path.is_file(): text = target_path.read_text(encoding="utf-8", newline="") else: text = "" # Verify without changing file content by probing a non-mutating exact check # over a temporary staging copy so real workspace files remain untouched. probe_search, probe_replace, original_for_patch = _verify_probe(text) case: Dict[str, Any] = { "case_id": case_id, "workspace": str(self.workspace_root), "file": chosen, "text": original_for_patch, "search": probe_search, "replace": probe_replace, "note": note, "required_gates": list(self.required_gates), "policy": self.policy_dict(), **self._adapter_fields(), } trace, dossier = self._run_six_nodes(case) decision = dict(dossier.get("decision", {})) return SessionResult( case_id=case_id, verdict=str(decision.get("verdict", "UNKNOWN")), assurance=int(decision.get("assurance", 0)), reason=str(decision.get("reason", "")), detail=str(decision.get("detail", "")), committed=False, touched_files=(chosen,), trace=tuple(trace), dossier=dossier, ) def edit_file( self, rel_path: str, search: str, replace: str, *, case_id: str = "python-edit", note: str = "apply controlled search-and-replace edit", commit: bool = True, attempt_signatures: Sequence[str] = (), patch_config: FuzzyPatchConfig = FuzzyPatchConfig(), ) -> SessionResult: """Stage a search-and-replace edit, verify via codex, and commit atomically on pass.""" rel_posix = rel_path.replace("\\", "/") guard = PathGuard(self.policy()) # Check path policy before touching or staging anything try: plan = guard.plan_transaction([PlannedOp(op=OP_WRITE, rel_posix=rel_posix, content="")]) except PathSecurityError: case = { "case_id": case_id, "workspace": str(self.workspace_root), "file": rel_posix, "text": "", "search": search, "replace": replace, "note": note, "required_gates": list(self.required_gates), "policy": self.policy_dict(), "attemptSignatures": list(attempt_signatures), **self._adapter_fields(), } trace, dossier = self._run_six_nodes(case) decision = dict(dossier.get("decision", {})) return SessionResult( case_id=case_id, verdict=str(decision.get("verdict", "UNKNOWN")), assurance=int(decision.get("assurance", 0)), reason=str(decision.get("reason", "")), detail=str(decision.get("detail", "")), committed=False, touched_files=(rel_posix,), trace=tuple(trace), dossier=dossier, ) target = self.workspace_root / Path(*rel_posix.split("/")) original_text = target.read_text(encoding="utf-8", newline="") if target.is_file() else "" patch_res = apply_controlled_fuzzy_patch( original_text, SearchReplaceBlock(search, replace), patch_config ) with tempfile.TemporaryDirectory(prefix="lingologos_python_stage_") as tmp_dir: staged_root = Path(tmp_dir).resolve() try: _copy_workspace_for_staging(self.workspace_root, staged_root) except WorkspaceLinkError as exc: return self._link_refusal(case_id, rel_posix, exc) if patch_res.applied and not plan.rejected: staged_fs = self._os_fs(staged_root) tx = staged_fs.begin_transaction() staged_fs.stage_write_text(tx, rel_posix, patch_res.updated_text) staged_fs.commit_transaction(tx) case = { "case_id": case_id, "workspace": str(staged_root), "file": rel_posix, "text": original_text, "search": search, "replace": replace, "note": note, "required_gates": list(self.required_gates), "policy": self.policy_dict(staged_root), "options": { "min_similarity": patch_config.min_similarity, "ambiguity_margin": patch_config.ambiguity_margin, }, "attemptSignatures": list(attempt_signatures), **self._adapter_fields(), } trace, dossier = self._run_six_nodes(case) decision = dict(dossier.get("decision", {})) verdict = str(decision.get("verdict", "UNKNOWN")) assurance = int(decision.get("assurance", 0)) reason = str(decision.get("reason", "")) detail = str(decision.get("detail", "")) committed = False if commit and patch_res.applied and not plan.rejected and assurance >= self.min_assurance: if _disk_text(self.workspace_root, rel_posix) != original_text: # The workspace moved while the six nodes were running: the patch that # was verified is no longer the patch for the file on disk, so nothing # is written and the run reports the named refusal instead. verdict = "REFUSED" assurance = 0 reason = PATCH_NOT_APPLIED detail = "the file changed on disk after the run verified the patch: '%s'" % rel_posix else: committed, failure = _commit_or_restore( self._os_fs(self.workspace_root), self.workspace_root, {rel_posix: patch_res.updated_text}, {rel_posix: original_text}, ) if not committed: verdict = "REFUSED" assurance = 0 reason = PATCH_NOT_APPLIED detail = failure return SessionResult( case_id=case_id, verdict=verdict, assurance=assurance, reason=reason, detail=detail, committed=committed, touched_files=(rel_posix,), trace=tuple(trace), dossier=dossier, ) def apply_pattern( self, pattern_id: str, *, target: Optional[str] = None, case_id: Optional[str] = None, note: Optional[str] = None, commit: bool = True, patch_config: FuzzyPatchConfig = FuzzyPatchConfig(), ) -> SessionResult: """Apply one catalog card to one target, primary edit and lock test together. Both files of the pair land in the same staged copy, so the test gate runs against the rewritten source and the lock test that can only pass once the rewrite landed. The kernel claim stays the primary edit, because that is the edit the six nodes are asked to judge, and the companion paths are announced on the same case. The commit is one transaction: the source replaced and the test file replaced, or neither. If the disk refuses that transaction part way, the session restores both files from the in-memory originals and reports the named refusal instead. A card that refuses is not a failed run. It reports the reason code the rule named and never reaches the six nodes, because there is nothing there to verify. A card that applies but whose anchors do not apply writes nothing either: a pattern that would have to edit one file of its pair and skip the other is a pattern this session does not run. """ chosen_case_id = case_id or "pattern-%s" % pattern_id plan = plan_pattern(self.workspace_root, pattern_id, target) if plan.refused: return SessionResult( case_id=chosen_case_id, verdict="REFUSED", assurance=0, reason=plan.reason_code, detail=plan.detail, committed=False, touched_files=(), dossier={ "pattern": pattern_id, "target": plan.target, "refusal": plan.reason_code, "decision": { "verdict": "REFUSED", "assurance": 0, "reason": plan.reason_code, "detail": plan.detail, }, "gates": [], "checkers": [], }, ) primary = plan.primary() guard = PathGuard(self.policy()) try: planned = guard.plan_transaction( [PlannedOp(op=OP_WRITE, rel_posix=edit.file, content="") for edit in plan.edits] ) except PathSecurityError: case = { "case_id": chosen_case_id, "workspace": str(self.workspace_root), "file": primary.file, "text": "", "search": primary.search, "replace": primary.replace, "note": note or plan.summary(), "required_gates": list(self.required_gates), "policy": self.policy_dict(), "pattern": pattern_id, "companionFiles": [edit.file for edit in plan.companions()], **self._adapter_fields(), } trace, dossier = self._run_six_nodes(case) decision = dict(dossier.get("decision", {})) return SessionResult( case_id=chosen_case_id, verdict=str(decision.get("verdict", "UNKNOWN")), assurance=int(decision.get("assurance", 0)), reason=str(decision.get("reason", "")), detail=str(decision.get("detail", "")), committed=False, touched_files=plan.files, trace=tuple(trace), dossier=dossier, ) originals: Dict[str, str] = {} patched: Dict[str, str] = {} unapplied: List[str] = [] for edit in plan.edits: source = self.workspace_root / Path(*edit.file.split("/")) original = source.read_text(encoding="utf-8", newline="") if source.is_file() else "" originals[edit.file] = original outcome = apply_controlled_fuzzy_patch( original, SearchReplaceBlock(edit.search, edit.replace), patch_config ) if not outcome.applied: unapplied.append(edit.file) patched[edit.file] = outcome.updated_text if planned.rejected or unapplied: # Nothing of the pair is written: a half pair is exactly the state the lock # test exists to prevent, and staging it would judge a change nobody proposed. return SessionResult( case_id=chosen_case_id, verdict="REFUSED", assurance=0, reason=PATH_POLICY if planned.rejected else PATCH_NOT_APPLIED, detail=( "the path policy rejected the pair: " + ", ".join(plan.files) if planned.rejected else "the anchor of this card did not apply in: " + ", ".join(unapplied) ), committed=False, touched_files=plan.files, dossier={ "pattern": pattern_id, "target": plan.target, "refusal": PATH_POLICY if planned.rejected else PATCH_NOT_APPLIED, "decision": {"verdict": "REFUSED", "assurance": 0}, "gates": [], "checkers": [], }, ) needed = max(self.min_assurance, plan.min_assurance) with tempfile.TemporaryDirectory(prefix="lingologos_python_pattern_stage_") as tmp_dir: staged_root = Path(tmp_dir).resolve() try: _copy_workspace_for_staging(self.workspace_root, staged_root) except WorkspaceLinkError as exc: return self._link_refusal(chosen_case_id, primary.file, exc) staged_fs = self._os_fs(staged_root) tx = staged_fs.begin_transaction() for edit in plan.edits: staged_fs.stage_write_text(tx, edit.file, patched[edit.file]) staged_fs.commit_transaction(tx) case = { "case_id": chosen_case_id, "workspace": str(staged_root), "file": primary.file, "text": originals[primary.file], "search": primary.search, "replace": primary.replace, "note": note or plan.summary(), "required_gates": list(self.required_gates), "policy": self.policy_dict(staged_root), "options": { "min_similarity": patch_config.min_similarity, "ambiguity_margin": patch_config.ambiguity_margin, }, "attemptSignatures": [], "pattern": pattern_id, "companionFiles": [edit.file for edit in plan.companions()], **self._adapter_fields(), } trace, dossier = self._run_six_nodes(case) decision = dict(dossier.get("decision", {})) verdict = str(decision.get("verdict", "UNKNOWN")) assurance = int(decision.get("assurance", 0)) reason = str(decision.get("reason", "")) detail = str(decision.get("detail", "")) committed = False if commit and assurance >= needed: drifted = [ edit.file for edit in plan.edits if _disk_text(self.workspace_root, edit.file) != originals[edit.file] ] if drifted: # The pair was verified against the workspace as it was at staging time. # If a file of the pair moved since, the anchors proven in staging are # not the anchors of what is on disk, so the pair is not written. verdict = "REFUSED" assurance = 0 reason = PATCH_NOT_APPLIED detail = "these files changed on disk after the pair was verified: " + ", ".join(drifted) else: committed, failure = _commit_or_restore( self._os_fs(self.workspace_root), self.workspace_root, {edit.file: patched[edit.file] for edit in plan.edits}, {edit.file: originals[edit.file] for edit in plan.edits}, ) if not committed: verdict = "REFUSED" assurance = 0 reason = PATCH_NOT_APPLIED detail = failure dossier["pattern"] = pattern_id dossier["target"] = plan.target dossier["companionFiles"] = [edit.file for edit in plan.companions()] dossier["requiredAssurance"] = needed return SessionResult( case_id=chosen_case_id, verdict=verdict, assurance=assurance, reason=reason, detail=detail, committed=committed, touched_files=plan.files, trace=tuple(trace), dossier=dossier, ) def create_file( self, rel_path: str, content: str, *, case_id: str = "python-create", note: str = "create verified Python module", commit: bool = True, ) -> SessionResult: """Create a new Python file, verifying it in isolation before committing.""" rel_posix = rel_path.replace("\\", "/") guard = PathGuard(self.policy()) try: plan = guard.plan_transaction([PlannedOp(op=OP_WRITE, rel_posix=rel_posix, content=content)]) except PathSecurityError: # The policy answers first. Probing the named path before the guard would let # an absolute path replace the workspace root on Windows and touch a file # outside the workspace, naming it back in the error. return self.edit_file(rel_posix, "# NEW_FILE", content, case_id=case_id, note=note, commit=False) # The guard has resolved the path inside the workspace by now; build the target # from the resolved rel path, never from the raw input. safe_rel = plan.touched_files[0] if plan.touched_files else rel_posix target = self.workspace_root / Path(*safe_rel.split("/")) if target.exists(): raise FileExistsError(f"target already exists: '{rel_posix}'") marker = "# __LINGOLOGOS_PYTHON_NEW_FILE__\n" with tempfile.TemporaryDirectory(prefix="lingologos_python_create_") as tmp_dir: staged_root = Path(tmp_dir).resolve() try: _copy_workspace_for_staging(self.workspace_root, staged_root) except WorkspaceLinkError as exc: return self._link_refusal(case_id, rel_posix, exc) if not plan.rejected: staged_fs = self._os_fs(staged_root) tx = staged_fs.begin_transaction() staged_fs.stage_write_text(tx, rel_posix, content) staged_fs.commit_transaction(tx) case = { "case_id": case_id, "workspace": str(staged_root), "file": rel_posix, "text": marker, "search": marker, "replace": content, "note": note, "required_gates": list(self.required_gates), "policy": self.policy_dict(staged_root), **self._adapter_fields(), } trace, dossier = self._run_six_nodes(case) decision = dict(dossier.get("decision", {})) verdict = str(decision.get("verdict", "UNKNOWN")) assurance = int(decision.get("assurance", 0)) reason = str(decision.get("reason", "")) detail = str(decision.get("detail", "")) committed = False if commit and not plan.rejected and assurance >= self.min_assurance: if target.is_file(): # The verified text was staged as a new file. If a file landed at that # path while the run was going, writing would replace something the # six nodes never saw, so the create is not committed. verdict = "REFUSED" assurance = 0 reason = PATCH_NOT_APPLIED detail = "a file appeared at '%s' while the create was being verified" % rel_posix else: committed, failure = _commit_or_restore( self._os_fs(self.workspace_root), self.workspace_root, {rel_posix: content}, {rel_posix: ""}, ) if not committed: verdict = "REFUSED" assurance = 0 reason = PATCH_NOT_APPLIED detail = failure return SessionResult( case_id=case_id, verdict=verdict, assurance=assurance, reason=reason, detail=detail, committed=committed, touched_files=(rel_posix,), trace=tuple(trace), dossier=dossier, ) def delete_file( self, rel_path: str, *, case_id: str = "python-delete", note: str = "delete Python module with full regression check", commit: bool = True, ) -> SessionResult: """Delete a Python file only if the full regression passes after removal.""" rel_posix = rel_path.replace("\\", "/") guard = PathGuard(self.policy()) try: plan = guard.plan_transaction([PlannedOp(op=OP_DELETE, rel_posix=rel_posix)]) except PathSecurityError: return self.edit_file(rel_posix, "# DELETE", "", case_id=case_id, note=note, commit=False) target = self.workspace_root / Path(*rel_posix.split("/")) if not target.is_file(): raise FileNotFoundError(f"target file does not exist: '{rel_posix}'") original_text = target.read_text(encoding="utf-8", newline="") with tempfile.TemporaryDirectory(prefix="lingologos_python_delete_") as tmp_dir: staged_root = Path(tmp_dir).resolve() try: _copy_workspace_for_staging(self.workspace_root, staged_root) except WorkspaceLinkError as exc: return self._link_refusal(case_id, rel_posix, exc) if not plan.rejected: # Unlink only the target file; lingologos_codex.fsadapter.stage_delete walks parent dirs. staged_target = staged_root / Path(*rel_posix.split("/")) if staged_target.is_file() and not staged_target.is_symlink(): staged_target.unlink() # A delete is judged where it can actually hurt: the surviving files that # import the module being removed are the gate target and its companions, # not the alphabetically first file of the copy. remaining = [p for p in discover_python_files(staged_root) if p != rel_posix] importers = importers_of(staged_root, remaining, rel_posix) gate_target = importers[0] if importers else (remaining[0] if remaining else rel_posix) companion_files = [p for p in importers if p != gate_target] case = { "case_id": case_id, "workspace": str(staged_root), "file": gate_target, "text": original_text, "search": original_text if original_text.strip() else "# empty", "replace": "# deleted\n", "note": note, "required_gates": list(self.required_gates), "policy": self.policy_dict(staged_root), "companionFiles": companion_files, **self._adapter_fields(), } trace, dossier = self._run_six_nodes(case) decision = dict(dossier.get("decision", {})) verdict = str(decision.get("verdict", "UNKNOWN")) assurance = int(decision.get("assurance", 0)) reason = str(decision.get("reason", "")) detail = str(decision.get("detail", "")) committed = False if commit and not plan.rejected and assurance >= self.min_assurance: if _disk_text(self.workspace_root, rel_posix) != original_text: # The file moved while the six nodes were running: the removal that was # verified is no longer the removal of what is on disk. verdict = "REFUSED" assurance = 0 reason = PATCH_NOT_APPLIED detail = "the file changed on disk after the run verified the delete: '%s'" % rel_posix else: committed, refusal_reason, failure = _delete_or_restore( # The guard above has already decided the policy for this delete; # the kernel stage_delete re-walks the parent directories against # the allowed set and refuses legitimate paths, so the adapter # only enforces the protected patterns here. self._os_fs(self.workspace_root, check_allowed=False), self.workspace_root, rel_posix, original_text, ) if not committed: verdict = "REFUSED" assurance = 0 reason = refusal_reason detail = failure dossier["companionFiles"] = companion_files return SessionResult( case_id=case_id, verdict=verdict, assurance=assurance, reason=reason, detail=detail, committed=committed, touched_files=(rel_posix,), trace=tuple(trace), dossier=dossier, ) def run_retry_loop( self, rel_path: str, proposer: Callable[[int, Optional[SessionResult]], Tuple[str, str]], *, max_attempts: int = 4, commit: bool = True, ) -> Tuple[SessionResult, List[SessionResult]]: """Run bounded edit attempts using codex stall detection to stop identical or cyclic failures.""" history: List[str] = [] attempts: List[SessionResult] = [] last: Optional[SessionResult] = None for idx in range(1, max_attempts + 1): search, replace = proposer(idx, last) result = self.edit_file( rel_path, search, replace, case_id=f"retry-{idx}", commit=commit, attempt_signatures=history, ) attempts.append(result) last = result sig = str(result.dossier.get("patchSignature", "")) if not sig: # Two attempts that propose the same anchor and the same text have to # share one hash even when the kernel recorded no patch signature, or # the stall detector never sees the repetition. sig = hashlib.sha1((search + "\x00" + replace).encode("utf-8")).hexdigest() history.append(sig) if result.assurance >= self.min_assurance: return result, attempts if detect_stall_from_hashes(history) is not None: return result, attempts assert last is not None return last, attempts
"""Transactional Python programming session built on the LingoLOGOS codex kernel.
A change is staged in an isolated copy of the workspace, evaluated by the
six-node codex pipeline (either in-process or as six isolated subprocesses
walking datasets/codex-python/topology.json), and committed atomically to the real
workspace via lingologos_codex.fsadapter only when the arbiter reaches the required
assurance threshold.
"""
from __future__ import annotations
import ast
import hashlib
import json
import os
import shutil
import stat
import subprocess
import sys
import tempfile
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple
from lingologos_python._codex_bridge import ensure_codex_on_path
ensure_codex_on_path()
from lingologos_codex import envelope as _envelope # noqa: E402
from lingologos_codex.agents import ROLES, run_pipeline # noqa: E402
from lingologos_codex.failures import detect_stall_from_hashes # noqa: E402
from lingologos_codex.fsadapter import ( # noqa: E402
FileSystemAdapterError,
create_os_filesystem_adapter,
)
from lingologos_codex.fspolicy import ( # noqa: E402
EOL_PRESERVE,
FSPolicy,
OP_DELETE,
OP_WRITE,
PathGuard,
PathSecurityError,
PlannedOp,
)
from lingologos_codex.patcher import ( # noqa: E402
FuzzyPatchConfig,
SearchReplaceBlock,
apply_controlled_fuzzy_patch,
)
from lingologos_python.ast_graph import ( # noqa: E402
IGNORED_DIRS,
discover_python_files,
importers_of,
)
from lingologos_python.patterns import PatternPlan, plan_pattern # noqa: E402
PYTHON_ROOT = Path(__file__).resolve().parent.parent
DEFAULT_AGENT_SCRIPT = PYTHON_ROOT / "agents" / "python_agent.py"
DEFAULT_TOPOLOGY_PATH = PYTHON_ROOT / "topology.json"
DEFAULT_ALLOWED_PATTERNS: Tuple[str, ...] = ("*.py", "*.pyi")
# Named session refusals, alongside the reason codes the rule catalog answers with.
PATH_POLICY = "PATH_POLICY"
PATCH_NOT_APPLIED = "PATCH_NOT_APPLIED"
NODE_TIMEOUT = "NODE_TIMEOUT"
LINKED_PATH_IN_WORKSPACE = "LINKED_PATH_IN_WORKSPACE"
class NodeTimeoutError(RuntimeError):
"""A node subprocess exhausted its time budget instead of answering."""
class WorkspaceLinkError(ValueError):
"""The workspace holds a symlink or a junction whose copy cannot match the disk."""
DEFAULT_PROTECTED_PATTERNS: Tuple[str, ...] = (
"*.env",
".env*",
"*.pem",
"*.key",
".git/*",
"__pycache__/*",
)
ADAPTER_REF_DEFAULT = "lingologos_python.adapter:PythonLanguageAdapter"
ADAPTER_REF_STRICT = "lingologos_python.adapter:StrictPythonLanguageAdapter"
DEFAULT_GATES: Tuple[str, ...] = ("typecheck", "tests")
@dataclass(frozen=True)
class SessionResult:
"""Outcome of running the six-node codex pipeline over a Python workspace."""
case_id: str
verdict: str
assurance: int
reason: str
detail: str
committed: bool