import json import sys from pathlib import Path import pytest from git import Repo from afk_developer import cli from afk_developer.config import Config from afk_developer.environment import ( ENVIRONMENT_SCHEMA_VERSION, _normalize_interpreter, changed_dependency_inputs, resolve_environment_contract, ) from afk_developer.event_store import DurableEventStore, EventProjector from afk_developer.execution import ExecutionBoundaryError, prepare_execution_boundary from afk_developer.planner.task_model import TaskNode, TaskPlan, TaskStatus from afk_developer.scheduler.reviewer import ReviewResult def test_missing_project_venv_blocks_instead_of_using_ambient_runner(tmp_path) -> None: resolution = resolve_environment_contract(tmp_path, runner_python=sys.executable) assert not resolution.passed assert resolution.code == "target_interpreter_missing" def test_runner_and_target_are_resolved_as_distinct_environments(tmp_path) -> None: target = tmp_path / "target-python" target.write_text("not executed", encoding="utf-8") runner = _normalize_interpreter(sys.executable) resolution = resolve_environment_contract( tmp_path, runner_python=sys.executable, target_python=target, probe=lambda path: ( "CPython", "3.13.0" if path == runner else "3.12.0", "/runner/venv" if path == runner else "/target/venv", ), ) assert resolution.passed assert resolution.contract is not None # Absolutised, never resolved: following the symlink would rewrite a venv # interpreter to the base binary and discard its site-packages. assert resolution.contract.runner.interpreter == str(runner) assert resolution.contract.target.interpreter == str(target) assert resolution.contract.runner.fingerprint != resolution.contract.target.fingerprint def test_matching_explicit_interpreter_produces_stable_dependency_fingerprint(tmp_path) -> None: (tmp_path / "pyproject.toml").write_text("[project]\nname = 'demo'\n", encoding="utf-8") resolution = resolve_environment_contract( tmp_path, runner_python=sys.executable, target_python=sys.executable, probe=lambda _path: ("CPython", "3.12.0", "/target/venv"), ) assert resolution.passed assert resolution.contract is not None assert resolution.contract.schema_version == ENVIRONMENT_SCHEMA_VERSION assert resolution.contract.runner.fingerprint == resolution.contract.target.fingerprint assert set(resolution.contract.target.dependency_inputs) == {"pyproject.toml"} def test_dependency_input_changes_change_the_contract_fingerprint(tmp_path) -> None: pyproject = tmp_path / "pyproject.toml" pyproject.write_text("[project]\nname = 'first'\n", encoding="utf-8") kwargs = { "runner_python": sys.executable, "target_python": sys.executable, "probe": lambda _path: ("CPython", "3.12.0", "/target/venv"), } before = resolve_environment_contract(tmp_path, **kwargs) pyproject.write_text("[project]\nname = 'second'\n", encoding="utf-8") after = resolve_environment_contract(tmp_path, **kwargs) assert before.contract is not None assert after.contract is not None assert before.contract.target.fingerprint != after.contract.target.fingerprint def test_changed_dependency_inputs_accepts_only_governed_root_paths() -> None: assert changed_dependency_inputs( ["./pyproject.toml", "requirements.txt", "nested/pyproject.toml", "src/module.py"] ) == ["pyproject.toml", "requirements.txt"] def test_project_local_venv_is_the_only_implicit_target(tmp_path, monkeypatch) -> None: venv_python = tmp_path / ".venv" / "bin" / "python" venv_python.parent.mkdir(parents=True) venv_python.write_text("not executed", encoding="utf-8") resolution = resolve_environment_contract( tmp_path, runner_python=sys.executable, probe=lambda _path: ("CPython", "3.12.0", "/target/venv"), ) assert resolution.passed assert resolution.contract is not None assert resolution.contract.target.interpreter == str(venv_python.resolve()) def test_plan_runner_blocks_before_queue_when_the_target_is_ambiguous(tmp_path) -> None: plan = TaskPlan(project_name="environment-check", goal="Do work", intent="implement", tasks=[]) with pytest.raises(cli.click.ClickException, match="target_interpreter_missing"): cli._run_plan(plan, Config(projects_dir=tmp_path / "state"), object(), tmp_path, "", "") event_path = tmp_path / "state" / "environment-check" / "governance-events.jsonl" records = [json.loads(line) for line in event_path.read_text(encoding="utf-8").splitlines()] assert records[-1]["kind"] == "environment_rejected" def test_plan_runner_binds_resolved_target_interpreter_before_queue_execution(tmp_path, monkeypatch) -> None: from afk_developer.scheduler import queue seen: list[object] = [] class Cortex: def replace_permanent(self, *_args) -> None: pass def save_session(self, *_args) -> None: pass monkeypatch.setattr(queue, "execute_plan", lambda _plan, config, *_args, **_kwargs: seen.append(config.target_python)) plan = TaskPlan(project_name="environment-bound", goal="Do work", intent="implement", tasks=[]) config = Config( api_key="test-key", projects_dir=tmp_path / "state", target_python=Path(sys.executable), ) cli._run_plan(plan, config, Cortex(), tmp_path, "", "") assert seen == [_normalize_interpreter(sys.executable)] def test_plan_runner_blocks_environment_drift_before_queue_execution(tmp_path) -> None: plan = TaskPlan(project_name="environment-drift", goal="Do work", intent="implement", tasks=[]) config = Config(projects_dir=tmp_path / "state", target_python=Path(sys.executable)) event_path = tmp_path / "state" / plan.project_name / "governance-events.jsonl" DurableEventStore(event_path).append( "environment_resolved", {"fingerprint": "old-fingerprint", "contract": {"project_root": str(tmp_path)}}, ) with pytest.raises(cli.click.ClickException, match="environment_drift"): cli._run_plan(plan, config, object(), tmp_path, "", "") records = [json.loads(line) for line in event_path.read_text(encoding="utf-8").splitlines()] assert records[-1]["payload"]["code"] == "environment_drift" def test_environment_repair_command_allows_the_approved_drift(tmp_path, monkeypatch) -> None: from click.testing import CliRunner from afk_developer.scheduler import queue config = Config( api_key="test-key", projects_dir=tmp_path / "state", target_python=Path(sys.executable), ) plan = TaskPlan(project_name="environment-repair", goal="Do work", intent="implement", tasks=[]) cli._save_plan(config, plan, project_dir=tmp_path) event_path = tmp_path / "state" / plan.project_name / "governance-events.jsonl" DurableEventStore(event_path).append( "environment_resolved", {"fingerprint": "old-fingerprint", "contract": {"project_root": str(tmp_path)}}, ) monkeypatch.setattr("afk_developer.cli.Config.from_env", lambda: config) result = CliRunner().invoke( cli.main, ["approve-environment-repair", plan.project_name, "--reason", "Updated dependencies."], ) assert result.exit_code == 0, result.output seen: list[object] = [] class Cortex: def replace_permanent(self, *_args) -> None: pass def save_session(self, *_args) -> None: pass monkeypatch.setattr(queue, "execute_plan", lambda _plan, actual, *_args, **_kwargs: seen.append(actual)) cli._run_plan(plan, config, Cortex(), tmp_path, "", "") assert seen == [config] def test_reviewed_manifest_merge_rebases_next_preflight_but_ambient_edit_blocks( tmp_path, monkeypatch ) -> None: from afk_developer.scheduler import queue repo = Repo.init(tmp_path, initial_branch="main") with repo.config_writer() as config_writer: config_writer.set_value("user", "name", "AFK Test") config_writer.set_value("user", "email", "afk-test@example.invalid") repo.index.commit("Initial project") class FakeWorker: def __init__(self, _config, _cortex, project_dir, **_kwargs) -> None: self.project_dir = project_dir def execute_task(self, _task): (self.project_dir / "pyproject.toml").write_text( "[project]\nname = 'demo'\n", encoding="utf-8" ) return TaskStatus.PASSED, "Created manifest", ["pyproject.toml"] class FakeCortex: def write_fading(self, **_kwargs) -> None: pass monkeypatch.setattr(queue, "Worker", FakeWorker) monkeypatch.setattr( queue, "review_task", lambda *_args, **_kwargs: ReviewResult(True, True, True) ) plan = TaskPlan( project_name="reviewed-environment-rebase", goal="Create a package manifest", intent="implement", tasks=[TaskNode(id="bootstrap", title="Bootstrap", description="Create pyproject.toml")], ) config = Config( api_key="test-key", projects_dir=tmp_path.parent / f"{tmp_path.name}-state", target_python=Path(sys.executable), ) prepared = prepare_execution_boundary(plan, config, tmp_path) original_fingerprint = prepared.contract.target.fingerprint assert queue.execute_plan(plan, config, FakeCortex(), tmp_path, "", "") projection = EventProjector().rebuild( prepared.governance_store, prepared.governance_snapshot, ) records = prepared.governance_store.read_events() rebase = next(event for event in records if event.kind == "environment_contract_rebased") assert rebase.payload["task_id"] == "bootstrap" assert rebase.payload["dependency_inputs"] == ["pyproject.toml"] assert rebase.payload["primary_revision"] == repo.head.commit.hexsha assert projection.environment_fingerprint != original_fingerprint next_step = prepare_execution_boundary(plan, config, tmp_path) assert next_step.contract.target.fingerprint == projection.environment_fingerprint (tmp_path / "pyproject.toml").write_text( "[project]\nname = 'ambient-change'\n", encoding="utf-8" ) with pytest.raises(ExecutionBoundaryError, match="environment_drift"): prepare_execution_boundary(plan, config, tmp_path) def test_product_validation_attestation_requires_declared_artifacts(tmp_path, monkeypatch) -> None: from click.testing import CliRunner from afk_developer.planner.task_model import ( ProductValidationCheckpoint, ProductValidationStatus, TaskLifecyclePhase, TaskNode, TaskStatus, ) config = Config(api_key="test-key", projects_dir=tmp_path / "state") task = TaskNode( id="audio-demo", title="Listen", description="Validate the generated audio.", status=TaskStatus.BLOCKED, lifecycle_phase=TaskLifecyclePhase.PRODUCT_VALIDATION, product_validation=ProductValidationCheckpoint( kind="audio listening", instructions="Listen for the expected envelope.", artifact_paths=["output/demo.wav"], status=ProductValidationStatus.AWAITING_HUMAN, ), ) plan = TaskPlan(project_name="product-check", goal="goal", intent="implement", tasks=[task]) artifact = tmp_path / "output" / "demo.wav" artifact.parent.mkdir() artifact.write_bytes(b"audio") cli._save_plan(config, plan, project_dir=tmp_path) monkeypatch.setattr("afk_developer.cli.Config.from_env", lambda: config) result = CliRunner().invoke( cli.main, [ "attest-product-validation", plan.project_name, task.id, "--observation", "Envelope and timbre are acceptable.", ], ) assert result.exit_code == 0, result.output loaded = cli._load_plan(config, plan.project_name)[0] attested = loaded.tasks[0] assert attested.status is TaskStatus.PASSED assert attested.product_validation.status is ProductValidationStatus.ATTESTED assert attested.product_validation.artifact_sha256["output/demo.wav"] def test_symlinked_venv_interpreter_is_never_rewritten_to_its_base_binary(tmp_path) -> None: """A venv's bin/python is a symlink on POSIX; resolving it discards the venv. Observed live: AFK ran `/usr/bin/python3.14 -m ruff` for a project whose .venv interpreter had ruff installed, and every task failed with "No module named ruff". Path.resolve() had rewritten the venv interpreter to the base binary, which is exactly the ambient-Python fallback this module promises never to make. Windows venvs ship a real python.exe, so only POSIX is bitten and the original Windows host never saw it. """ base = tmp_path / "base-python" base.write_text("not executed", encoding="utf-8") venv_bin = tmp_path / "project" / ".venv" / "bin" venv_bin.mkdir(parents=True) venv_python = venv_bin / "python" try: venv_python.symlink_to(base) except (OSError, NotImplementedError): # pragma: no cover - platform dependent pytest.skip("This platform cannot create symlinks without elevation.") project = tmp_path / "project" explicit = resolve_environment_contract( project, runner_python=sys.executable, target_python=venv_python, probe=lambda path: ("CPython", "3.12.0", str(path.parent.parent)), ) discovered = resolve_environment_contract( project, runner_python=sys.executable, probe=lambda path: ("CPython", "3.12.0", str(path.parent.parent)), ) # Both routes into the venv must keep the venv path, not the symlink target. assert explicit.contract.target.interpreter == str(venv_python) assert discovered.contract.target.interpreter == str(venv_python) assert str(base) not in explicit.contract.target.interpreter