codex-python / lgpython /session.py
tailot's picture
Upload folder using huggingface_hub
339ddd8 verified
Raw History Blame
22.2 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 lgcodex.fsadapter only when the arbiter reaches the required
assurance threshold.
"""
from __future__ import annotations
import json
import os
import shutil
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 lgpython._codex_bridge import ensure_codex_on_path
ensure_codex_on_path()
from lgcodex import envelope as _envelope # noqa: E402
from lgcodex.agents import ROLES, run_pipeline # noqa: E402
from lgcodex.failures import detect_stall_from_hashes # noqa: E402
from lgcodex.fsadapter import create_os_filesystem_adapter # noqa: E402
from lgcodex.fspolicy import ( # noqa: E402
EOL_PRESERVE,
FSPolicy,
OP_DELETE,
OP_WRITE,
PathGuard,
PathSecurityError,
PlannedOp,
)
from lgcodex.patcher import ( # noqa: E402
FuzzyPatchConfig,
SearchReplaceBlock,
apply_controlled_fuzzy_patch,
)
from lgpython.ast_graph import IGNORED_DIRS, discover_python_files # 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")
DEFAULT_PROTECTED_PATTERNS: Tuple[str, ...] = (
"*.env",
".env*",
"*.pem",
"*.key",
".git/*",
"__pycache__/*",
)
ADAPTER_REF_DEFAULT = "lgpython.adapter:PythonLanguageAdapter"
ADAPTER_REF_STRICT = "lgpython.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 _copy_workspace_for_staging(src_root: Path, dst_root: Path) -> None:
"""Copy a workspace cleanly without caches or virtual environments."""
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(src_root.resolve())
target_dir = dst_root / rel_dir
target_dir.mkdir(parents=True, exist_ok=True)
for name in filenames:
src_file = Path(dirpath) / name
if src_file.is_symlink():
continue
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: Path = DEFAULT_AGENT_SCRIPT,
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."""
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(agent_script), "--role", role, "--node-id", role]
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,
)
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,
) -> 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)
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]]:
if self.use_subprocesses:
return run_topology_subprocesses(case)
return run_pipeline(case)
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.
lines = text.splitlines(keepends=True)
if lines:
first_line = lines[0]
probe_search = first_line
probe_replace = first_line.rstrip("\r\n") + " # codex-verify-probe\n"
original_for_patch = text
else:
probe_search = "# empty"
probe_replace = "# empty verified"
original_for_patch = "# empty\n"
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="lgpython_stage_") as tmp_dir:
staged_root = Path(tmp_dir).resolve()
_copy_workspace_for_staging(self.workspace_root, staged_root)
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))
committed = False
if commit and patch_res.applied and not plan.rejected and assurance >= self.min_assurance:
real_fs = self._os_fs(self.workspace_root)
tx = real_fs.begin_transaction()
real_fs.stage_write_text(tx, rel_posix, patch_res.updated_text)
real_fs.commit_transaction(tx)
committed = True
return SessionResult(
case_id=case_id,
verdict=verdict,
assurance=assurance,
reason=str(decision.get("reason", "")),
detail=str(decision.get("detail", "")),
committed=committed,
touched_files=(rel_posix,),
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("\\", "/")
target = self.workspace_root / Path(*rel_posix.split("/"))
if target.exists():
raise FileExistsError(f"target already exists: '{rel_posix}'")
guard = PathGuard(self.policy())
try:
plan = guard.plan_transaction([PlannedOp(op=OP_WRITE, rel_posix=rel_posix, content=content)])
except PathSecurityError:
return self.edit_file(rel_posix, "# NEW_FILE", content, case_id=case_id, note=note, commit=False)
marker = "# __LGPYTHON_NEW_FILE__\n"
with tempfile.TemporaryDirectory(prefix="lgpython_create_") as tmp_dir:
staged_root = Path(tmp_dir).resolve()
_copy_workspace_for_staging(self.workspace_root, staged_root)
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))
committed = False
if commit and not plan.rejected and assurance >= self.min_assurance:
real_fs = self._os_fs(self.workspace_root)
tx = real_fs.begin_transaction()
real_fs.stage_write_text(tx, rel_posix, content)
real_fs.commit_transaction(tx)
committed = True
return SessionResult(
case_id=case_id,
verdict=verdict,
assurance=assurance,
reason=str(decision.get("reason", "")),
detail=str(decision.get("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="lgpython_delete_") as tmp_dir:
staged_root = Path(tmp_dir).resolve()
_copy_workspace_for_staging(self.workspace_root, staged_root)
if not plan.rejected:
# Unlink only the target file; lgcodex.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()
# Evaluate syntax over remaining files by targeting a surviving file if available
remaining = [p for p in discover_python_files(staged_root) if p != rel_posix]
gate_target = remaining[0] if remaining else rel_posix
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),
**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))
committed = False
if commit and not plan.rejected and assurance >= self.min_assurance:
guard.resolve_safe(rel_posix, for_write=True)
current = self.workspace_root
for part in Path(*rel_posix.split("/")).parts:
current = current / part
if current.is_symlink():
raise PathSecurityError(f"refusing to delete across symlink: '{rel_posix}'")
if target.is_file():
target.unlink()
committed = True
return SessionResult(
case_id=case_id,
verdict=verdict,
assurance=assurance,
reason=str(decision.get("reason", "")),
detail=str(decision.get("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 sig:
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