Download lingologos_python/session.py from tailot/codex-python: direct link, hf CLI and curl.
- Browser
- Download file 70.5 kB
-
https://huggingface.co/datasets/tailot/codex-python/resolve/main/lingologos_python/session.py
- Command line
-
hf download hf://datasets/tailot/codex-python/lingologos_python/session.py
-
curl -L -o session.py https://huggingface.co/datasets/tailot/codex-python/resolve/main/lingologos_python/session.py
70.5 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 ctypes
import hashlib
import inspect
import json
import os
import shutil
import signal
import subprocess
import sys
import tempfile
import threading
import time
import uuid
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.adapter import GATE_TIMEOUT_ENV # noqa: E402
from lingologos_python.ast_graph import ( # noqa: E402
IGNORED_DIRS,
build_reverse_index,
discover_python_files,
hardlinked_file,
importers_from_index,
is_linked_path,
)
from lingologos_python.patterns import PatternPlan, plan_pattern # noqa: E402
from lingologos_python.reasons import ( # noqa: E402
HARDLINKED_PATH_IN_WORKSPACE,
LINKED_PATH_IN_WORKSPACE,
NODE_TIMEOUT,
PATCH_NOT_APPLIED,
PATH_POLICY,
SESSION_LOCKED,
)
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")
# The clock the budgets read. A module attribute so a test can name a deadline
# without touching the clock of every other process on the machine.
_MONOTONIC = time.monotonic
class NodeTimeoutError(RuntimeError):
"""A node subprocess exhausted its time budget instead of answering."""
class WorkspaceLinkError(ValueError):
"""The workspace holds a link, or a name counted twice, whose copy cannot match the disk."""
def __init__(self, message: str, reason: str = LINKED_PATH_IN_WORKSPACE) -> None:
super().__init__(message)
self.reason = reason
class SessionLockError(RuntimeError):
"""Another run holds the workspace lock, or its owner cannot be verified."""
# Two sessions committing to one workspace corrupt each other: each staged its
# own copy from a disk the other has already rewritten. The lock is taken with
# an exclusive create, so claiming it is never a polite ask, and released in a
# finally even when the run was refused. The lock file names the holder's pid,
# the creation time of that pid, and a token unique to the acquisition: the pid
# separates live from dead, the birth time separates the holder that was
# written down from a recycled pid wearing the same number, and the token keeps
# a run from unlinking a lock another run retook after it stalled.
SESSION_LOCK_NAME = ".lingologos-session.lock"
SESSION_LOCK_CLAIM_SUFFIX = ".stale"
# The gate budget reaches the kernel through the environment, and a process
# carries one such window at a time: every six-node call, together with the
# environment set and restore around it, is serialized by this lock. Documented
# limit: two CodeLinguistSessions in one process take their six-node turns in
# order rather than interleaving.
_KERNEL_CALL_LOCK = threading.Lock()
def _process_alive(pid: int) -> bool:
"""Best effort: is a process with this pid still running on this machine?"""
if pid <= 0:
return False
if os.name == "nt":
handle = ctypes.windll.kernel32.OpenProcess(0x1000, False, pid) # PROCESS_QUERY_LIMITED_INFORMATION
if not handle:
return False
ctypes.windll.kernel32.CloseHandle(handle)
return True
try:
os.kill(pid, 0)
except ProcessLookupError:
return False
except PermissionError:
return True
return True
def _process_creation_time(pid: int) -> Optional[int]:
"""When the process behind this pid was born, or None when the host will not say.
A pid alone says a number is answered; it does not say the answering
process is the one that was written down. Birth times are the cheapest
witness of a recycled pid.
"""
if pid <= 0:
return None
if os.name == "nt":
kernel32 = ctypes.windll.kernel32
kernel32.OpenProcess.restype = ctypes.c_void_p
kernel32.OpenProcess.argtypes = [ctypes.c_ulong, ctypes.c_bool, ctypes.c_ulong]
handle = kernel32.OpenProcess(0x1000, False, pid) # PROCESS_QUERY_LIMITED_INFORMATION
if not handle:
return None
try:
low = ctypes.c_ulong(0)
high = ctypes.c_ulong(0)
unused = ctypes.c_ulong(0)
kernel32.GetProcessTimes.argtypes = [
ctypes.c_void_p,
ctypes.POINTER(ctypes.c_ulong),
ctypes.POINTER(ctypes.c_ulong),
ctypes.POINTER(ctypes.c_ulong),
ctypes.POINTER(ctypes.c_ulong),
]
if not kernel32.GetProcessTimes(
handle, ctypes.byref(low), ctypes.byref(high), ctypes.byref(unused), ctypes.byref(unused)
):
return None
return (int(high.value) << 32) | int(low.value)
finally:
kernel32.CloseHandle(handle)
try:
# Field 22 of /proc/<pid>/stat is the start time in clock ticks; the
# comm field before it may itself hold spaces, so count from the last.
with open("/proc/%d/stat" % pid, encoding="ascii") as handle:
after_name = handle.read().rsplit(")", 1)[-1].split()
return int(after_name[19])
except (OSError, ValueError, IndexError):
return None
def _read_lock_record(lock: Path) -> Optional[Tuple[int, Optional[int], Optional[str]]]:
"""The (pid, birth, token) a lock file names, or None when it names nothing readable."""
try:
parts = lock.read_text(encoding="ascii").split()
except (OSError, UnicodeDecodeError):
return None
if not parts:
return None
try:
pid = int(parts[0])
except ValueError:
return None
birth: Optional[int] = None
if len(parts) > 1 and parts[1] != "-":
try:
birth = int(parts[1])
except ValueError:
return None
token = parts[2] if len(parts) > 2 else None
return (pid, birth, token)
def _lock_holder_is_alive(record: Tuple[int, Optional[int], Optional[str]]) -> bool:
"""A holder lives when its pid answers and is the same process it was when written.
A pid recycled by a young process looks alive; the recorded birth time says
the process now wearing the number is somebody else.
"""
pid, birth, _token = record
if not _process_alive(pid):
return False
if birth is not None:
now = _process_creation_time(pid)
if now is not None and now != birth:
return False
return True
def workspace_lock_status(workspace_root: str | Path) -> Dict[str, Any]:
"""What a reader may know about the workspace lock, reading and touching nothing.
Three answers, no fourth: no lock at all; a lock whose holder lives; and a
leftover whose holder no longer runs, which the next session takes over
through the rename and which therefore reads as free. A lock file whose
owner cannot even be read counts as held, because no run may grant itself
the workspace without the takeover dance.
"""
root = Path(workspace_root).resolve()
lock = root / SESSION_LOCK_NAME
status: Dict[str, Any] = {
"workspace": str(root),
"lock_file": SESSION_LOCK_NAME,
"present": lock.is_file(),
"held": False,
"stale": False,
"unreadable": False,
"holder_pid": None,
"holder_birth": None,
"holder_alive": None,
}
if not status["present"]:
return status
record = _read_lock_record(lock)
if record is None:
status["held"] = True
status["unreadable"] = True
return status
pid, birth, _token = record
alive = _lock_holder_is_alive(record)
status.update(
holder_pid=pid,
holder_birth=birth,
holder_alive=alive,
held=alive,
stale=not alive,
)
return status
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", [])),
}
@dataclass(frozen=True)
class RetryContext:
"""What the attempts before this one leave to the proposer: results with trace and dossier.
A loop that hands the proposer only the index and the last result teaches it
nothing about why the nodes refused. A proposer that accepts a third
argument receives all of it: every prior result with its verdict, reason,
trace lines and the dossier the kernel returned, plus the patch signatures
the loop detector compares, which read the fate of a patch and not its
words. A two-argument proposer keeps working unchanged.
"""
attempt: int
rel_path: str
attempts: Tuple[SessionResult, ...] = ()
failure_reasons: Tuple[str, ...] = ()
patch_signatures: Tuple[str, ...] = ()
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 _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. A
file standing under two names is refused too: the copy would split one
file into two, and a later commit could not tell the names apart.
"""
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_path(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_path(src_file):
raise WorkspaceLinkError(
"linked file in the workspace: '%s'" % (rel_dir / name).as_posix()
)
if hardlinked_file(src_file):
raise WorkspaceLinkError(
"hardlinked file in the workspace: '%s'" % (rel_dir / name).as_posix(),
HARDLINKED_PATH_IN_WORKSPACE,
)
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 _kill_process_tree(proc: subprocess.Popen) -> None:
"""Kill a node and everything it started: a budget that leaks grandchildren is not a budget.
A node runs its own gates as children (pytest, a static checker), so killing
only the direct child would leave those processes running past the budget.
Windows gets the process tree through taskkill; elsewhere the node leads its
own process group and the whole group is signalled.
"""
if os.name == "nt":
done = subprocess.run(
["taskkill", "/T", "/F", "/PID", str(proc.pid)],
stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
if done.returncode == 0:
return
else:
try:
os.killpg(os.getpgid(proc.pid), signal.SIGKILL)
except OSError:
pass
try:
proc.kill()
except OSError:
pass
def run_topology_subprocesses(
case: Dict[str, Any],
*,
agent_script: Optional[Path] = None,
timeout_sec: float = 120.0,
total_budget_sec: Optional[float] = None,
) -> 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. A budget is honest only if it
reaches the whole tree: an exhausted node is killed together with the gates
it had started. ``total_budget_sec`` caps the sum of the six waits, and each
node then gets the smaller of its own budget and the time the total still allows.
"""
script = Path(agent_script) if agent_script else DEFAULT_AGENT_SCRIPT
if timeout_sec <= 0 or (total_budget_sec is not None and total_budget_sec <= 0):
raise ValueError("budgets must be positive numbers of seconds")
seed = _envelope.make_envelope("arbiter", 0, 0, "task received", dict(case))
trace: List[Dict[str, Any]] = [seed]
current = seed
env = _subprocess_env()
deadline = _MONOTONIC() + total_budget_sec if total_budget_sec else None
for role in ROLES:
node_timeout = timeout_sec
if deadline is not None:
remaining = deadline - _MONOTONIC()
if remaining <= 0:
raise NodeTimeoutError(
"the run exhausted its %s s total budget before node '%s' started"
% (total_budget_sec, role)
)
node_timeout = min(timeout_sec, remaining)
cmd = [sys.executable, "-B", str(script), "--role", role, "--node-id", role]
popen_kwargs: Dict[str, Any] = dict(
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
encoding="utf-8",
errors="replace",
cwd=str(PYTHON_ROOT),
env=env,
)
if os.name == "nt":
popen_kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP
else:
popen_kwargs["start_new_session"] = True
proc = subprocess.Popen(cmd, **popen_kwargs)
try:
stdout, stderr = proc.communicate(input=json.dumps(current), timeout=node_timeout)
except subprocess.TimeoutExpired as exc:
_kill_process_tree(proc)
try:
proc.communicate(timeout=5)
except (subprocess.TimeoutExpired, ValueError, OSError):
pass
raise NodeTimeoutError(
"node '%s' exhausted its %s s budget without answering"
% (role, round(node_timeout, 3))
) from exc
if proc.returncode != 0:
raise RuntimeError(
f"node '{role}' exited with {proc.returncode}: {(stderr or '').strip()}"
)
current = json.loads(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,
total_budget_sec: Optional[float] = None,
gate_timeout_sec: Optional[float] = None,
lock_wait_sec: float = 0.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)
if (
node_timeout_sec <= 0
or (total_budget_sec is not None and total_budget_sec <= 0)
or (gate_timeout_sec is not None and gate_timeout_sec <= 0)
or lock_wait_sec < 0
):
raise ValueError("budgets must be positive numbers of seconds, and the lock wait may not go negative")
self.node_timeout_sec = float(node_timeout_sec)
self.total_budget_sec = float(total_budget_sec) if total_budget_sec else None
self.gate_timeout_sec = float(gate_timeout_sec) if gate_timeout_sec else None
self.lock_wait_sec = float(lock_wait_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 _enter_gate_timeout_env(self) -> Optional[str]:
"""Hand the gate budget down to the adapter, which reads its own environment.
The kernel instantiates the adapter from a reference string, so the
session cannot pass it a constructor argument. The environment is the
channel both the in-process pipeline and the node subprocesses read.
"""
if self.gate_timeout_sec is None:
return None
previous = os.environ.get(GATE_TIMEOUT_ENV)
os.environ[GATE_TIMEOUT_ENV] = repr(self.gate_timeout_sec)
return previous
@staticmethod
def _exit_gate_timeout_env(previous: Optional[str]) -> None:
if previous is None:
os.environ.pop(GATE_TIMEOUT_ENV, None)
else:
os.environ[GATE_TIMEOUT_ENV] = previous
def _run_six_nodes(self, case: Dict[str, Any]) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]:
with _KERNEL_CALL_LOCK:
# The budget travels through the environment, which one process
# shares; holding the module lock across the whole call is what
# keeps one session's window from bleeding into another's.
previous_env = self._enter_gate_timeout_env()
try:
if self.use_subprocesses:
return run_topology_subprocesses(
case,
timeout_sec=self.node_timeout_sec,
total_budget_sec=self.total_budget_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),
}
}
finally:
self._exit_gate_timeout_env(previous_env)
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=getattr(exc, "reason", LINKED_PATH_IN_WORKSPACE),
detail=str(exc),
committed=False,
touched_files=(rel_posix,),
)
def _linked_path_in_workspace(self) -> Optional[Tuple[str, str]]:
"""Return ('directory'|'file'|'hardlink', rel_posix) for the first anomaly under the root.
Verify judges the workspace where it stands, with no staging copy to
refuse for it, so it asks the same question the copy asks: is any part
of this tree somewhere else, or does any single file answer under two
names.
"""
root = Path(self.workspace_root).resolve()
for dirpath, dirnames, filenames in os.walk(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:
if is_linked_path(Path(dirpath) / name):
return ("directory", (rel_dir / name).as_posix())
for name in filenames:
entry = Path(dirpath) / name
if is_linked_path(entry):
return ("file", (rel_dir / name).as_posix())
if hardlinked_file(entry):
return ("hardlink", (rel_dir / name).as_posix())
return None
def _late_link_at_commit(self) -> Optional[Tuple[str, int, str, str]]:
"""The link question, asked again at the moment of writing.
A link can appear after the run judged the tree. The commit already
re-reads the bytes to catch a workspace that moved; it re-asks the same
question those bytes still belong to the tree the six nodes verified.
"""
linked = self._linked_path_in_workspace()
if linked is None:
return None
kind, rel = linked
if kind == "hardlink":
return (
"REFUSED",
0,
HARDLINKED_PATH_IN_WORKSPACE,
"a hardlinked file appeared in the workspace before the commit: '%s'" % rel,
)
return (
"REFUSED",
0,
LINKED_PATH_IN_WORKSPACE,
"a linked %s appeared in the workspace before the commit: '%s'" % (kind, rel),
)
def _lock_lost_at_commit(self) -> Optional[Tuple[str, int, str, str]]:
"""The lock question, asked again at the moment of writing.
The workspace lock is taken at the start of a run, and another run can
take over a leftover claim while this run is busy. A commit whose lock
no longer names this run is a named refusal: the bytes are still the
tree the six nodes verified, but they would be written without a holder.
"""
token = getattr(self, "_lock_token", None)
if token is None:
return None
record = _read_lock_record(self._lock_path())
if record is not None and record[2] == token:
return None
return (
"REFUSED",
0,
SESSION_LOCKED,
"the workspace lock no longer names this run before the commit: '%s'" % self._lock_path(),
)
def _lock_path(self) -> Path:
return Path(self.workspace_root) / SESSION_LOCK_NAME
def _lock_owner(self) -> Optional[Tuple[int, Optional[int], Optional[str]]]:
return _read_lock_record(self._lock_path())
@staticmethod
def _lock_detail(lock: Path, record: Optional[Tuple[int, Optional[int], Optional[str]]]) -> str:
if record is None:
return "a lock file sits at '%s' and its owner cannot be read" % lock
note = "" if record[1] is not None else ", whose birth time this system cannot read"
return "another session run holds the workspace: '%s' names process %d%s" % (lock, record[0], note)
def _acquire_session_lock(self) -> None:
"""Take the workspace lock with an exclusive create, never a polite ask.
The lock names the holder's pid, its birth time, and a token unique to
this acquisition. A lock left behind by a process that no longer runs is
taken over through a rename: two runs that find the same leftover race
for the rename, only one proceeds, and the loser is refused rather than
handed a second silent holder. A lock whose owner is alive, or that has
recycled only its pid number, or whose owner cannot even be read, is a
refusal the caller can read.
"""
lock = self._lock_path()
claim = Path(str(lock) + SESSION_LOCK_CLAIM_SUFFIX)
if claim.exists():
try:
# Bookkeeping of a takeover that finished or died mid-step; the
# exclusive create below is what actually grants the workspace.
claim.unlink()
except OSError:
pass
token = uuid.uuid4().hex
deadline = time.monotonic() + max(0.0, self.lock_wait_sec)
takeovers = 0
while True:
try:
handle = os.open(str(lock), os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
except FileExistsError:
record = self._lock_owner()
if record is not None and not _lock_holder_is_alive(record) and takeovers < 2:
takeovers += 1
try:
os.rename(str(lock), str(claim))
except OSError:
raise SessionLockError(
"the leftover lock at '%s' is being taken over by another run" % lock
)
continue
# A live holder keeps the workspace until it releases or the
# caller's patience runs out; waiting was asked, waiting is what happens.
if time.monotonic() >= deadline:
raise SessionLockError(self._lock_detail(lock, record))
time.sleep(min(0.05, max(0.0, deadline - time.monotonic())))
continue
birth = _process_creation_time(os.getpid())
try:
os.write(
handle,
("%d %s %s" % (os.getpid(), "-" if birth is None else birth, token)).encode("ascii"),
)
finally:
os.close(handle)
self._held_lock = lock
self._lock_token = token
if claim.exists():
try:
claim.unlink()
except OSError:
pass
return
def _release_session_lock(self) -> None:
lock = getattr(self, "_held_lock", None)
if lock is None:
return
self._held_lock = None
token = getattr(self, "_lock_token", None)
self._lock_token = None
record = _read_lock_record(lock)
if token is None or record is None or record[2] != token:
# The lock under this name is no longer ours: a takeover happened
# while this run stalled, and unlinking it would steal that holder.
return
try:
lock.unlink()
except OSError:
pass
def _lock_refusal(
self, case_id: str, rel_posix: Optional[str], exc: SessionLockError
) -> SessionResult:
return SessionResult(
case_id=case_id,
verdict="REFUSED",
assurance=0,
reason=SESSION_LOCKED,
detail=str(exc),
committed=False,
touched_files=() if rel_posix is None else (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:
"""Judge the workspace, holding the session lock for the whole run.
Two sessions committing to one tree each staged its copy from a disk
the other had already rewritten, so the lock is taken before anything
is read and released in a finally even when the run was refused.
"""
try:
self._acquire_session_lock()
except SessionLockError as exc:
return self._lock_refusal(case_id, target_file, exc)
try:
return self._verify_run(target_file, case_id=case_id, note=note)
finally:
self._release_session_lock()
def _verify_run(
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."""
linked = self._linked_path_in_workspace()
if linked is not None:
kind, rel = linked
if kind == "hardlink":
exc = WorkspaceLinkError(
"hardlinked file in the workspace: '%s'" % rel,
HARDLINKED_PATH_IN_WORKSPACE,
)
else:
exc = WorkspaceLinkError("linked %s in the workspace: '%s'" % (kind, rel))
return self._link_refusal(case_id, rel, exc)
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."""
try:
self._acquire_session_lock()
except SessionLockError as exc:
return self._lock_refusal(case_id, rel_path.replace("\\", "/"), exc)
try:
return self._edit_run(
rel_path,
search,
replace,
case_id=case_id,
note=note,
commit=commit,
attempt_signatures=attempt_signatures,
patch_config=patch_config,
)
finally:
self._release_session_lock()
def _edit_run(
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:
late_link = self._late_link_at_commit() or self._lock_lost_at_commit()
if late_link is not None:
verdict, assurance, reason, detail = late_link
elif _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 under the session lock, pair of files and all."""
try:
self._acquire_session_lock()
except SessionLockError as exc:
return self._lock_refusal(
case_id or "python-pattern-%s" % pattern_id, target, exc
)
try:
return self._apply_pattern_run(
pattern_id,
target=target,
case_id=case_id,
note=note,
commit=commit,
patch_config=patch_config,
)
finally:
self._release_session_lock()
def _apply_pattern_run(
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:
late_link = self._late_link_at_commit() or self._lock_lost_at_commit()
drifted = [] if late_link is not None else [
edit.file for edit in plan.edits
if _disk_text(self.workspace_root, edit.file) != originals[edit.file]
]
if late_link is not None:
verdict, assurance, reason, detail = late_link
elif 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."""
try:
self._acquire_session_lock()
except SessionLockError as exc:
return self._lock_refusal(case_id, rel_path.replace("\\", "/"), exc)
try:
return self._create_run(
rel_path, content, case_id=case_id, note=note, commit=commit
)
finally:
self._release_session_lock()
def _create_run(
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_run(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:
late_link = self._late_link_at_commit() or self._lock_lost_at_commit()
if late_link is not None:
verdict, assurance, reason, detail = late_link
elif 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."""
try:
self._acquire_session_lock()
except SessionLockError as exc:
return self._lock_refusal(case_id, rel_path.replace("\\", "/"), exc)
try:
return self._delete_run(rel_path, case_id=case_id, note=note, commit=commit)
finally:
self._release_session_lock()
def _delete_run(
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_run(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_from_index(build_reverse_index(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:
late_link = self._late_link_at_commit() or self._lock_lost_at_commit()
if late_link is not None:
verdict, assurance, reason, detail = late_link
elif _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.
The proposer takes the attempt index and the last result. A proposer that
accepts a third argument also receives a RetryContext with every prior
attempt, its trace and its dossier.
"""
history: List[str] = []
attempts: List[SessionResult] = []
last: Optional[SessionResult] = None
try:
accepts_context = len(inspect.signature(proposer).parameters) >= 3
except (TypeError, ValueError):
accepts_context = False
for idx in range(1, max_attempts + 1):
if accepts_context:
search, replace = proposer(
idx,
last,
RetryContext(
attempt=idx,
rel_path=rel_path,
attempts=tuple(attempts),
failure_reasons=tuple(r.reason for r in attempts),
patch_signatures=tuple(history),
),
)
else:
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. The hash keeps the
# shape of a kernel signature, "sha256:" and sixteen hex digits, so a
# history of attempts never mixes two notations for one fact.
sig = "sha256:" + hashlib.sha256((search + "\x00" + replace).encode("utf-8")).hexdigest()[:16]
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 ctypes
import hashlib
import inspect
import json
import os
import shutil
import signal
import subprocess
import sys
import tempfile
import threading
import time
import uuid
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.adapter import GATE_TIMEOUT_ENV # noqa: E402
from lingologos_python.ast_graph import ( # noqa: E402
IGNORED_DIRS,
build_reverse_index,
discover_python_files,
hardlinked_file,
importers_from_index,
is_linked_path,
)
from lingologos_python.patterns import PatternPlan, plan_pattern # noqa: E402
from lingologos_python.reasons import ( # noqa: E402
HARDLINKED_PATH_IN_WORKSPACE,
LINKED_PATH_IN_WORKSPACE,
NODE_TIMEOUT,
PATCH_NOT_APPLIED,
PATH_POLICY,
SESSION_LOCKED,
)
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")
# The clock the budgets read. A module attribute so a test can name a deadline
# without touching the clock of every other process on the machine.
_MONOTONIC = time.monotonic
class NodeTimeoutError(RuntimeError):
"""A node subprocess exhausted its time budget instead of answering."""
class WorkspaceLinkError(ValueError):
"""The workspace holds a link, or a name counted twice, whose copy cannot match the disk."""
def __init__(self, message: str, reason: str = LINKED_PATH_IN_WORKSPACE) -> None:
super().__init__(message)
self.reason = reason
class SessionLockError(RuntimeError):
"""Another run holds the workspace lock, or its owner cannot be verified."""