"""Tests for PythonWorkspaceSession transactional editing, verification, and rollback.""" from __future__ import annotations import os from pathlib import Path from typing import Any, Dict, Tuple import pytest from lingologos_codex.fsadapter import FileSystemAdapterError import lingologos_python.session as session_module from lingologos_python.session import ( LINKED_PATH_IN_WORKSPACE, NODE_TIMEOUT, NodeTimeoutError, PythonWorkspaceSession, SessionResult, WorkspaceLinkError, _verify_probe, ) def test_verify_clean_workspace_reaches_verified_assurance_3(sample_pkg: Path) -> None: session = PythonWorkspaceSession(sample_pkg) res = session.verify("src/mathops.py") assert res.verdict == "VERIFIED" assert res.assurance == 3 assert res.committed is False def test_edit_file_commits_only_when_verified(sample_pkg: Path) -> None: session = PythonWorkspaceSession(sample_pkg) res = session.edit_file( "src/mathops.py", "return left + right", "return int(left) + int(right)", commit=True, ) assert res.verdict == "VERIFIED" assert res.assurance == 3 assert res.committed is True assert "return int(left) + int(right)" in (sample_pkg / "src" / "mathops.py").read_text( encoding="utf-8" ) def test_edit_file_does_not_touch_disk_when_tests_fail(sample_pkg: Path) -> None: session = PythonWorkspaceSession(sample_pkg) before = (sample_pkg / "src" / "mathops.py").read_text(encoding="utf-8") res = session.edit_file( "src/mathops.py", "return left + right", "return left - right", commit=True, ) after = (sample_pkg / "src" / "mathops.py").read_text(encoding="utf-8") assert res.verdict == "UNKNOWN" assert res.reason == "GATE_REJECTED" assert res.committed is False assert before == after def test_edit_file_refuses_protected_and_traversal_paths(sample_pkg: Path) -> None: (sample_pkg / ".env").write_text("KEY=1\n", encoding="utf-8") session = PythonWorkspaceSession(sample_pkg) env_res = session.edit_file(".env", "KEY=1", "KEY=2", commit=True) assert env_res.verdict == "UNKNOWN" assert env_res.reason == "PROTECTED_PATH" assert env_res.committed is False assert (sample_pkg / ".env").read_text(encoding="utf-8") == "KEY=1\n" esc_res = session.edit_file("../outside.py", "a = 1", "a = 2", commit=True) assert esc_res.verdict == "UNKNOWN" assert esc_res.reason in ("PROTECTED_PATH", "NOT_APPLIED") assert esc_res.committed is False def test_create_and_delete_file_transactions(sample_pkg: Path) -> None: session = PythonWorkspaceSession(sample_pkg) created = session.create_file( "src/helper.py", '"""Extra module."""\n\n\ndef square(x: int) -> int:\n return x * x\n', commit=True, ) assert created.verdict == "VERIFIED" assert created.committed is True assert (sample_pkg / "src" / "helper.py").is_file() deleted = session.delete_file("src/helper.py", commit=True) assert deleted.verdict == "VERIFIED" assert deleted.committed is True assert not (sample_pkg / "src" / "helper.py").exists() def test_retry_loop_stops_on_identical_failure_stall(sample_pkg: Path) -> None: session = PythonWorkspaceSession(sample_pkg) def repeated_bad_edit(attempt: int, last_result: object) -> tuple[str, str]: return ("return left + right", "return left - right") final, attempts = session.run_retry_loop("src/mathops.py", repeated_bad_edit, max_attempts=5) assert final.verdict == "UNKNOWN" assert len(attempts) == 2 assert any(c.get("role") == "adversary_loop" for c in final.dossier.get("checkers", [])) def test_verify_probe_annotates_a_line_that_keeps_the_file_parsable() -> None: text = '"""Module doc.\n\nSpread over several lines.\n"""\n\n\ndef go() -> int:\n return 1\n' search, replace, original = _verify_probe(text) assert search == "def go() -> int:" assert replace == search + " # codex-verify-probe\n" assert original is text compile(original.replace(search, replace, 1), "module.py", "exec") empty_search, _empty_replace, empty_text = _verify_probe("") assert empty_text == "# empty\n" assert empty_search in empty_text def test_edit_file_refuses_when_the_file_moved_during_the_run(sample_pkg: Path, monkeypatch) -> None: session = PythonWorkspaceSession(sample_pkg) real_run = session._run_six_nodes def run_with_a_moving_workspace(case: Dict[str, Any]) -> Tuple[Any, ...]: path = sample_pkg / "src" / "mathops.py" path.write_text( path.read_text(encoding="utf-8", newline="").replace( "return left + right", "return left + right # moved" ), encoding="utf-8", newline="", ) return real_run(case) monkeypatch.setattr(session, "_run_six_nodes", run_with_a_moving_workspace) res = session.edit_file( "src/mathops.py", "return left + right", "return int(left) + int(right)", commit=True, ) assert res.verdict == "REFUSED" assert res.reason == "PATCH_NOT_APPLIED" assert res.committed is False on_disk = (sample_pkg / "src" / "mathops.py").read_text(encoding="utf-8") assert "# moved" in on_disk assert "int(left)" not in on_disk def test_create_file_refuses_when_a_file_landed_at_its_path_during_the_run( sample_pkg: Path, monkeypatch ) -> None: session = PythonWorkspaceSession(sample_pkg) real_run = session._run_six_nodes def run_that_lands_a_file(case: Dict[str, Any]) -> Tuple[Any, ...]: (sample_pkg / "src" / "landed.py").write_text("VALUE = 1\n", encoding="utf-8", newline="\n") return real_run(case) monkeypatch.setattr(session, "_run_six_nodes", run_that_lands_a_file) res = session.create_file("src/landed.py", "VALUE = 2\n", commit=True) assert res.verdict == "REFUSED" assert res.reason == "PATCH_NOT_APPLIED" assert res.committed is False assert (sample_pkg / "src" / "landed.py").read_text(encoding="utf-8") == "VALUE = 1\n" def test_retry_loop_spots_repetition_even_without_a_patch_signature( sample_pkg: Path, monkeypatch ) -> None: session = PythonWorkspaceSession(sample_pkg) def always_unknown(rel_path: str, search: str, replace: str, **kwargs: Any) -> SessionResult: return SessionResult( case_id=str(kwargs.get("case_id", "python-edit")), verdict="UNKNOWN", assurance=0, reason="GATE_REJECTED", detail="", committed=False, ) monkeypatch.setattr(session, "edit_file", always_unknown) def same_proposal(attempt: int, last_result: object) -> tuple: return ("return left + right", "return left - right") final, attempts = session.run_retry_loop("src/mathops.py", same_proposal, max_attempts=5) assert final.verdict == "UNKNOWN" assert len(attempts) == 2 def test_create_file_refuses_an_escaping_path_before_touching_it(tmp_path: Path) -> None: """The path policy answers before the workspace code probes the named path. Joining the workspace root with an absolute path replaces the root on Windows, so an exists probe placed before the guard reaches files outside the workspace and can even name one back in an error. """ ws = tmp_path / "ws" ws.mkdir() (ws / "value.py").write_text("VALUE = 1\n", encoding="utf-8") outside = tmp_path / "outside.py" outside.write_text("VALUE = 1\n", encoding="utf-8", newline="") session = PythonWorkspaceSession(ws) res = session.create_file(str(outside), "VALUE = 2\n", commit=True) assert res.committed is False assert res.verdict in ("UNKNOWN", "REFUSED") assert outside.read_text(encoding="utf-8", newline="") == "VALUE = 1\n" def test_a_commit_refused_by_the_disk_restores_the_file_from_memory( sample_pkg: Path, monkeypatch ) -> None: """A commit that fails mid flight must not leave the run claiming a write it lost.""" session = PythonWorkspaceSession(sample_pkg) real_os_fs = session._os_fs class CommitRefusingFs: def __init__(self, inner: Any) -> None: self._inner = inner def __getattr__(self, name: str) -> Any: return getattr(self._inner, name) def commit_transaction(self, tx: Any) -> None: raise FileSystemAdapterError("the disk refused the replace") def os_fs(root: Path, *, check_allowed: bool = True) -> Any: fs = real_os_fs(root, check_allowed=check_allowed) if Path(root).resolve() == sample_pkg.resolve(): return CommitRefusingFs(fs) return fs monkeypatch.setattr(session, "_os_fs", os_fs) before = (sample_pkg / "src" / "mathops.py").read_text(encoding="utf-8", newline="") res = session.edit_file( "src/mathops.py", "return left + right", "return int(left) + int(right)", commit=True, ) after = (sample_pkg / "src" / "mathops.py").read_text(encoding="utf-8", newline="") assert res.verdict == "REFUSED" assert res.reason == "PATCH_NOT_APPLIED" assert res.committed is False assert "refused the replace" in res.detail assert before == after def test_a_delete_refused_by_the_disk_leaves_the_file_in_place( sample_pkg: Path, monkeypatch ) -> None: """A delete goes through the kernel transaction, and committed only says the file is gone.""" session = PythonWorkspaceSession(sample_pkg) created = session.create_file( "src/helper.py", '"""Extra module."""\n\nVALUE = 1\n', commit=True ) assert created.committed is True real_os_fs = session._os_fs class DeleteRefusingFs: def __init__(self, inner: Any) -> None: self._inner = inner def __getattr__(self, name: str) -> Any: return getattr(self._inner, name) def stage_delete(self, tx: Any, rel_path: str) -> None: raise FileSystemAdapterError("the disk refused the removal") def os_fs(root: Path, *, check_allowed: bool = True) -> Any: fs = real_os_fs(root, check_allowed=check_allowed) if Path(root).resolve() == sample_pkg.resolve(): return DeleteRefusingFs(fs) return fs monkeypatch.setattr(session, "_os_fs", os_fs) res = session.delete_file("src/helper.py", commit=True) assert res.verdict == "REFUSED" assert res.reason == "PATCH_NOT_APPLIED" assert res.committed is False helper = sample_pkg / "src" / "helper.py" assert helper.is_file() assert helper.read_text(encoding="utf-8", newline="") == '"""Extra module."""\n\nVALUE = 1\n' def test_a_linked_directory_in_the_workspace_refuses_any_staged_run( sample_pkg: Path, tmp_path: Path, dir_link ) -> None: """A junction or symlink makes the staging copy lie, so the session refuses by name.""" outside = tmp_path / "outside" outside.mkdir() (outside / "elsewhere.py").write_text("SECRET = 1\n", encoding="ascii", newline="") link = sample_pkg / "vendor" if not dir_link(link, outside): pytest.skip("this host offers no way to create a directory link") session = PythonWorkspaceSession(sample_pkg) res = session.edit_file( "src/mathops.py", "return left + right", "return int(left) + int(right)", commit=False, ) assert res.verdict == "REFUSED" assert res.reason == LINKED_PATH_IN_WORKSPACE assert "vendor" in res.detail assert res.committed is False created = session.create_file("src/newcomer.py", "VALUE = 1\n", commit=True) assert created.verdict == "REFUSED" assert created.reason == LINKED_PATH_IN_WORKSPACE assert created.committed is False assert not (sample_pkg / "src" / "newcomer.py").exists() assert (outside / "elsewhere.py").read_text(encoding="utf-8") == "SECRET = 1\n" def test_the_staging_copy_refuses_a_linked_file_by_name(sample_pkg: Path, tmp_path: Path) -> None: """The refusal is not limited to directories: one linked file is enough.""" target = tmp_path / "outside_helper.py" target.write_text("VALUE = 1\n", encoding="ascii", newline="") link = sample_pkg / "src" / "linked.py" try: os.symlink(str(target), str(link)) except (OSError, NotImplementedError): pytest.skip("this host does not allow creating a file symlink") with pytest.raises(WorkspaceLinkError) as caught: session_module._copy_workspace_for_staging(sample_pkg, tmp_path / "staged") assert "src/linked.py" in str(caught.value) def test_a_node_that_exhausts_its_budget_raises_a_named_error(tmp_path: Path) -> None: """The subprocess runner turns an exhausted per-node budget into NodeTimeoutError.""" stub = tmp_path / "sleeping_agent.py" stub.write_text("import time\n\ntime.sleep(30)\n", encoding="ascii", newline="") with pytest.raises(NodeTimeoutError) as caught: session_module.run_topology_subprocesses( {"case_id": "budget"}, agent_script=stub, timeout_sec=1.0 ) assert "exhausted its" in str(caught.value) def test_a_timed_out_node_answers_unknown_instead_of_a_traceback( sample_pkg: Path, tmp_path: Path, monkeypatch ) -> None: """The session reports the budget refusal with a reason, like any other abstain.""" stub = tmp_path / "sleeping_agent.py" stub.write_text("import time\n\ntime.sleep(30)\n", encoding="ascii", newline="") monkeypatch.setattr(session_module, "DEFAULT_AGENT_SCRIPT", stub) session = PythonWorkspaceSession(sample_pkg, use_subprocesses=True, node_timeout_sec=1.0) res = session.verify("src/mathops.py") assert res.verdict == "UNKNOWN" assert res.reason == NODE_TIMEOUT assert res.assurance == 0 assert res.committed is False def test_a_total_budget_shrinks_the_wait_of_the_first_node(tmp_path: Path) -> None: """A node gets the smaller of its own budget and what the total still allows.""" stub = tmp_path / "sleeping_agent.py" stub.write_text("import time\n\ntime.sleep(30)\n", encoding="ascii", newline="") with pytest.raises(NodeTimeoutError) as caught: session_module.run_topology_subprocesses( {"case_id": "total"}, agent_script=stub, timeout_sec=30.0, total_budget_sec=1.0 ) assert "exhausted its 1.0 s budget" in str(caught.value) def test_a_spent_total_budget_refuses_a_node_before_starting_it(tmp_path: Path, monkeypatch) -> None: """Once the total is gone, the run says so instead of paying for one more node.""" echo = tmp_path / "echo_agent.py" echo.write_text("import sys\n\nsys.stdout.write(sys.stdin.read())\n", encoding="ascii", newline="") clock = iter([1000.0, 1000.5, 2000.0]) monkeypatch.setattr(session_module, "_MONOTONIC", lambda: next(clock)) with pytest.raises(NodeTimeoutError) as caught: session_module.run_topology_subprocesses( {"case_id": "late"}, agent_script=echo, timeout_sec=10.0, total_budget_sec=5.0 ) assert "total budget" in str(caught.value) def test_a_nonpositive_budget_is_refused_before_anything_runs(sample_pkg: Path) -> None: """A budget of zero seconds is a mistake, not a promise to abstain instantly.""" with pytest.raises(ValueError): session_module.run_topology_subprocesses({"case_id": "bad"}, timeout_sec=0.0) with pytest.raises(ValueError): PythonWorkspaceSession(sample_pkg, total_budget_sec=-1.0) def test_verify_refuses_a_workspace_held_together_by_a_link( sample_pkg: Path, tmp_path: Path, dir_link ) -> None: """verify has no staging copy to refuse for it, so it asks the link question itself.""" outside = tmp_path / "outside" outside.mkdir() (outside / "elsewhere.py").write_text("VALUE = 1\n", encoding="ascii", newline="") link = sample_pkg / "vendor" if not dir_link(link, outside): pytest.skip("this host offers no way to create a directory link") session = PythonWorkspaceSession(sample_pkg) res = session.verify("src/mathops.py") assert res.verdict == "REFUSED" assert res.reason == LINKED_PATH_IN_WORKSPACE assert res.assurance == 0 assert "vendor" in res.detail assert res.touched_files == ("vendor",)