import asyncio import sys from pathlib import Path from types import ModuleType, SimpleNamespace import pytest from afk_developer.backends import copilot from afk_developer.backends.copilot import ( CopilotResearcher, CopilotValidator, _parse_evidence_draft_response, _raw_output_research_requirement, ) from afk_developer.backends.fake import FakeResearcherBackend, FakeValidatorBackend from afk_developer.backends.models import ( AcceptanceOutcome, ResearchProposalResult, ) from afk_developer.backends.registry import BackendRegistry from afk_developer.config import Config, EndpointProfile, EndpointType, RoleRoute from afk_developer.evidence import EvidencePacketDraft from afk_developer.planner.task_model import TaskFailureKind, TaskNode, TaskStatus from afk_developer.scheduler.tools.codebase import grep_codebase, list_directory from afk_developer.scheduler.tools.file_ops import ( glob_files, normalize_line_endings, read_file, write_file, ) def _draft(root: Path) -> EvidencePacketDraft: return EvidencePacketDraft.model_validate( { "sources": [ { "root": str(root.resolve()), "relative_path": "contract.txt", "start_marker": "BEGIN", "end_marker": "END", } ], "facts": ["The source preserves the observed wrapper."], "observed_rules": [ { "category": "wrapper", "statement": "The wrapper order is observable in the source.", "source_indices": [0], } ], "support_boundary": {"supported_forms": ["contract"], "exclusions": []}, } ) def test_raw_output_research_requirement_demands_fixture_contract() -> None: requirement = _raw_output_research_requirement() assert "MUST include at least one raw_output_contracts entry" in requirement assert "project-relative fixture artifact" in requirement def test_researcher_json_fallback_rejects_malformed_content() -> None: assert _parse_evidence_draft_response("proposal submitted") is None assert _parse_evidence_draft_response('{"sources": []}') is None def test_fake_researcher_returns_proposal_without_mutating_task(tmp_path: Path) -> None: evidence_root = tmp_path / "evidence" evidence_root.mkdir() proposal = ResearchProposalResult( status=TaskStatus.PASSED, summary="Proposal ready", draft=_draft(evidence_root), ) backend = FakeResearcherBackend(lambda _task: proposal) task = TaskNode(id="research", title="Research", description="Inspect only") actual = backend.propose_evidence( task=task, project_dir=str(tmp_path), context="bounded context", max_turns=2, ) assert actual == proposal assert backend.tasks == [task] assert backend.requests == [ {"project_dir": str(tmp_path), "context": "bounded context", "max_turns": 2} ] def test_registry_resolves_dedicated_read_only_role_routes_without_provider_calls() -> None: copilot_config = Config( endpoints={"copilot": EndpointProfile("copilot", EndpointType.COPILOT)}, researcher=RoleRoute( endpoint="copilot", model="gpt-5.6-terra", reasoning_effort="high", ), ) openai_config = Config( endpoints={"api": EndpointProfile("api", EndpointType.OPENAI_COMPATIBLE)}, researcher=RoleRoute(endpoint="api", model="research-model"), validator=RoleRoute(endpoint="api", model="validator-model"), ) assert type(BackendRegistry(copilot_config).get_researcher()).__name__ == "CopilotResearcher" assert ( type(BackendRegistry(openai_config).get_researcher()).__name__ == "OpenAICompatibleResearcher" ) assert type(BackendRegistry(copilot_config).get_validator()).__name__ == "CopilotValidator" assert ( type(BackendRegistry(openai_config).get_validator()).__name__ == "OpenAICompatibleValidator" ) def test_openai_researcher_fails_explicitly_instead_of_using_a_coder_path(tmp_path: Path) -> None: config = Config( endpoints={"api": EndpointProfile("api", EndpointType.OPENAI_COMPATIBLE)}, researcher=RoleRoute(endpoint="api", model="research-model"), ) researcher = BackendRegistry(config).get_researcher() with pytest.raises(NotImplementedError, match="constrained read-only tool adapter"): researcher.propose_evidence( task=TaskNode(id="research", title="Research", description="Inspect only"), project_dir=str(tmp_path), context="", max_turns=1, ) def test_fake_validator_is_read_only_and_openai_validator_fails_explicitly(tmp_path: Path) -> None: task = TaskNode(id="validate", title="Validate", description="Inspect only") backend = FakeValidatorBackend() result = backend.validate( task=task, project_dir=str(tmp_path), context="trusted context", max_turns=2, ) assert result.outcome is AcceptanceOutcome.PASS assert backend.tasks == [task] assert backend.requests == [ {"project_dir": str(tmp_path), "context": "trusted context", "max_turns": 2} ] config = Config( endpoints={"api": EndpointProfile("api", EndpointType.OPENAI_COMPATIBLE)}, validator=RoleRoute(endpoint="api", model="validator-model"), ) validator = BackendRegistry(config).get_validator() with pytest.raises(NotImplementedError, match="constrained read-only tool adapter"): validator.validate( task=task, project_dir=str(tmp_path), context="", max_turns=1, ) def test_project_read_helpers_cannot_escape_the_target_root(tmp_path: Path) -> None: project = tmp_path / "project" project.mkdir() (project / "inside.txt").write_text("inside", encoding="utf-8") outside = tmp_path / "outside.txt" outside.write_text("outside", encoding="utf-8") assert "1: inside" in read_file("inside.txt", str(project)) assert "Error:" in read_file("../outside.txt", str(project)) assert "Error:" in write_file("../outside.txt", "changed", str(project)) assert outside.read_text(encoding="utf-8") == "outside" assert "Error:" in list_directory("..", str(project)) assert "Error:" in glob_files("../*.txt", str(project)) assert "Error:" in grep_codebase("outside", str(project), "../*.txt") assert write_file("exact.txt", "first\nsecond\n", str(project)).endswith("(13 bytes)") assert (project / "exact.txt").read_bytes() == b"first\nsecond\n" (project / "exact.txt").write_bytes(b"first\r\nsecond\r\n") assert normalize_line_endings("exact.txt", "lf", str(project)).endswith("13 bytes)") assert (project / "exact.txt").read_bytes() == b"first\nsecond\n" assert "Error:" in normalize_line_endings("exact.txt", "invalid", str(project)) def test_copilot_researcher_exposes_only_read_only_proposal_tools( monkeypatch, tmp_path: Path, ) -> None: project = tmp_path / "project" project.mkdir() (project / "target.py").write_text("value = 1\n", encoding="utf-8") evidence_root = tmp_path / "evidence" evidence_root.mkdir() (evidence_root / "contract.txt").write_text("BEGIN contract END\n", encoding="utf-8") session_module = ModuleType("copilot.session") session_module.PermissionHandler = type("PermissionHandler", (), {"approve_all": object()}) tools_module = ModuleType("copilot.tools") class Tool: def __init__(self, **kwargs) -> None: self.name = kwargs["name"] self.handler = kwargs["handler"] self.parameters = kwargs["parameters"] class ToolResult: def __init__(self, **kwargs) -> None: self.text = kwargs["text_result_for_llm"] self.result_type = kwargs["result_type"] tools_module.Tool = Tool tools_module.ToolResult = ToolResult monkeypatch.setitem(sys.modules, "copilot.session", session_module) monkeypatch.setitem(sys.modules, "copilot.tools", tools_module) class ResearchSession: def __init__(self, tools) -> None: self.tools = tools async def send_and_wait(self, _prompt: str, *, timeout: float): del timeout verifier = next(tool for tool in self.tools if tool.name == "run_verification") rejection = verifier.handler( SimpleNamespace(arguments={"kind": "git_log", "extra_safe_args": ["--max-count=1"]}) ) assert rejection.result_type == "rejected" submit = next(tool for tool in self.tools if tool.name == "submit_evidence_proposal") result = submit.handler(SimpleNamespace(arguments=_draft(evidence_root).model_dump())) assert result.result_type == "success" return SimpleNamespace(data=SimpleNamespace(content="proposal submitted")) async def disconnect(self) -> None: pass class Client: session_config = None async def start(self) -> None: pass async def create_session(self, **kwargs): self.__class__.session_config = kwargs return ResearchSession(kwargs["tools"]) async def stop(self) -> None: pass monkeypatch.setattr("afk_developer.backends.copilot._create_client", Client) config = Config( endpoints={"copilot": EndpointProfile("copilot", EndpointType.COPILOT)}, researcher=RoleRoute( endpoint="copilot", model="gpt-5.6-terra", reasoning_effort="high", ), ) task = TaskNode( id="research", title="Research corpus", description="Inspect the corpus before implementation.", evidence_roots=[str(evidence_root)], ) result = asyncio.run( CopilotResearcher(config, "researcher")._propose_evidence_async( task, str(project), "bounded context", 3, ) ) assert result.status is TaskStatus.PASSED assert result.draft is not None assert Client.session_config["model"] == "gpt-5.6-terra" assert Client.session_config["reasoning_effort"] == "high" assert "omit paths and extra_safe_args" in Client.session_config["system_message"]["content"] tool_names = {tool.name for tool in Client.session_config["tools"]} assert { "read_file", "read_evidence_file", "run_verification", "submit_evidence_proposal", } <= tool_names verifier = next( tool for tool in Client.session_config["tools"] if tool.name == "run_verification" ) assert "file_sha256" in verifier.parameters["properties"]["kind"]["enum"] assert "baseline_compare" not in verifier.parameters["properties"]["kind"]["enum"] assert "baseline_compare" not in verifier.parameters["properties"]["kind"]["description"] assert ( not { "write_file", "edit_file", "normalize_line_endings", "run_command", "task_complete", "compare_ruff_baseline", } & tool_names ) def test_copilot_researcher_can_recover_after_rejected_verification_options( monkeypatch, tmp_path: Path ) -> None: project = tmp_path / "project" project.mkdir() evidence_root = tmp_path / "evidence" evidence_root.mkdir() (evidence_root / "contract.txt").write_text("BEGIN contract END\n", encoding="utf-8") session_module = ModuleType("copilot.session") session_module.PermissionHandler = type("PermissionHandler", (), {"approve_all": object()}) tools_module = ModuleType("copilot.tools") class Tool: def __init__(self, **kwargs) -> None: self.name = kwargs["name"] self.handler = kwargs["handler"] class ToolResult: def __init__(self, **kwargs) -> None: self.result_type = kwargs["result_type"] tools_module.Tool = Tool tools_module.ToolResult = ToolResult monkeypatch.setitem(sys.modules, "copilot.session", session_module) monkeypatch.setitem(sys.modules, "copilot.tools", tools_module) class ResearchSession: calls = 0 def __init__(self, tools) -> None: self.tools = tools async def send_and_wait(self, prompt: str, *, timeout: float): del timeout type(self).calls += 1 if type(self).calls == 1: verifier = next(tool for tool in self.tools if tool.name == "run_verification") rejection = verifier.handler( SimpleNamespace( arguments={"kind": "git_show", "extra_safe_args": ["--format=%B"]} ) ) assert rejection.result_type == "rejected" return SimpleNamespace(data=SimpleNamespace(content="")) assert "rejected by policy" in prompt submit = next(tool for tool in self.tools if tool.name == "submit_evidence_proposal") accepted = submit.handler(SimpleNamespace(arguments=_draft(evidence_root).model_dump())) assert accepted.result_type == "success" return SimpleNamespace(data=SimpleNamespace(content="proposal submitted")) async def disconnect(self) -> None: pass class Client: async def start(self) -> None: pass async def create_session(self, **kwargs): return ResearchSession(kwargs["tools"]) async def stop(self) -> None: pass monkeypatch.setattr("afk_developer.backends.copilot._create_client", Client) config = Config( endpoints={"copilot": EndpointProfile("copilot", EndpointType.COPILOT)}, researcher=RoleRoute(endpoint="copilot", model="gpt-5.6-terra"), ) task = TaskNode( id="research", title="Research corpus", description="Inspect evidence.", evidence_roots=[str(evidence_root)], ) result = asyncio.run( CopilotResearcher(config, "researcher")._propose_evidence_async(task, str(project), "", 2) ) assert result.status is TaskStatus.PASSED assert result.draft is not None assert ResearchSession.calls == 2 def test_copilot_researcher_accepts_schema_valid_json_when_provider_skips_tool_call( monkeypatch, tmp_path: Path, ) -> None: project = tmp_path / "project" project.mkdir() evidence_root = tmp_path / "evidence" evidence_root.mkdir() (evidence_root / "contract.txt").write_text("BEGIN contract END\n", encoding="utf-8") session_module = ModuleType("copilot.session") session_module.PermissionHandler = type("PermissionHandler", (), {"approve_all": object()}) tools_module = ModuleType("copilot.tools") class Tool: def __init__(self, **kwargs) -> None: self.name = kwargs["name"] tools_module.Tool = Tool tools_module.ToolResult = object monkeypatch.setitem(sys.modules, "copilot.session", session_module) monkeypatch.setitem(sys.modules, "copilot.tools", tools_module) class ResearchSession: calls = 0 async def send_and_wait(self, _prompt: str, *, timeout: float): del timeout self.__class__.calls += 1 if self.calls == 1: return SimpleNamespace( data=SimpleNamespace( content="The proposal tool is unavailable in this session." ) ) return SimpleNamespace( data=SimpleNamespace(content=_draft(evidence_root).model_dump_json()) ) async def disconnect(self) -> None: pass class Client: async def start(self) -> None: pass async def create_session(self, **_kwargs): return ResearchSession() async def stop(self) -> None: pass monkeypatch.setattr("afk_developer.backends.copilot._create_client", Client) config = Config( endpoints={"copilot": EndpointProfile("copilot", EndpointType.COPILOT)}, researcher=RoleRoute(endpoint="copilot", model="gpt-5.6-terra"), ) task = TaskNode( id="research", title="Research corpus", description="Inspect evidence.", evidence_roots=[str(evidence_root)], ) result = asyncio.run( CopilotResearcher(config, "researcher")._propose_evidence_async( task, str(project), "", 1, ) ) assert result.status is TaskStatus.PASSED assert result.draft == _draft(evidence_root) assert ResearchSession.calls == 2 def test_copilot_researcher_bounds_cleanup_after_provider_timeout( monkeypatch, tmp_path: Path ) -> None: project = tmp_path / "project" project.mkdir() evidence_root = tmp_path / "evidence" evidence_root.mkdir() (evidence_root / "contract.txt").write_text("BEGIN contract END\n", encoding="utf-8") session_module = ModuleType("copilot.session") session_module.PermissionHandler = type("PermissionHandler", (), {"approve_all": object()}) tools_module = ModuleType("copilot.tools") class Tool: def __init__(self, **kwargs) -> None: self.name = kwargs["name"] tools_module.Tool = Tool tools_module.ToolResult = object monkeypatch.setitem(sys.modules, "copilot.session", session_module) monkeypatch.setitem(sys.modules, "copilot.tools", tools_module) class HangingSession: async def send_and_wait(self, _prompt: str, *, timeout: float): del timeout await asyncio.Event().wait() async def disconnect(self) -> None: await asyncio.Event().wait() class HangingClient: async def start(self) -> None: pass async def create_session(self, **_kwargs): return HangingSession() async def stop(self) -> None: await asyncio.Event().wait() monkeypatch.setattr("afk_developer.backends.copilot._create_client", HangingClient) monkeypatch.setattr(copilot, "_CLEANUP_TIMEOUT_SECONDS", 0.01) config = Config( endpoints={"copilot": EndpointProfile("copilot", EndpointType.COPILOT)}, researcher=RoleRoute(endpoint="copilot", model="gpt-5.6-terra", timeout=0.01), ) task = TaskNode( id="research", title="Research corpus", description="Inspect evidence.", evidence_roots=[str(evidence_root)], ) result = asyncio.run( CopilotResearcher(config, "researcher")._propose_evidence_async(task, str(project), "", 1) ) assert result.status is TaskStatus.ESCALATED assert result.failure_kind is TaskFailureKind.PROVIDER_TIMEOUT def test_copilot_validator_exposes_only_read_only_validation_tools( monkeypatch, tmp_path: Path, ) -> None: project = tmp_path / "project" project.mkdir() (project / "output.xml").write_text("", encoding="utf-8") evidence_root = tmp_path / "evidence" evidence_root.mkdir() (evidence_root / "contract.txt").write_text("BEGIN contract END\n", encoding="utf-8") session_module = ModuleType("copilot.session") session_module.PermissionHandler = type("PermissionHandler", (), {"approve_all": object()}) tools_module = ModuleType("copilot.tools") class Tool: def __init__(self, **kwargs) -> None: self.name = kwargs["name"] self.handler = kwargs["handler"] self.parameters = kwargs["parameters"] class ToolResult: def __init__(self, **kwargs) -> None: self.text = kwargs["text_result_for_llm"] self.result_type = kwargs["result_type"] tools_module.Tool = Tool tools_module.ToolResult = ToolResult monkeypatch.setitem(sys.modules, "copilot.session", session_module) monkeypatch.setitem(sys.modules, "copilot.tools", tools_module) class ValidationSession: def __init__(self, tools) -> None: self.tools = tools async def send_and_wait(self, _prompt: str, *, timeout: float): del timeout verifier = next(tool for tool in self.tools if tool.name == "run_verification") rejection = verifier.handler( SimpleNamespace(arguments={"kind": "git_log", "extra_safe_args": ["--max-count=1"]}) ) assert rejection.result_type == "rejected" submit = next(tool for tool in self.tools if tool.name == "submit_acceptance_result") result = submit.handler( SimpleNamespace( arguments={ "outcome": "PASS", "summary": "Checked the contract and generated output.", } ) ) assert result.result_type == "success" return SimpleNamespace(data=SimpleNamespace(content="validation submitted")) async def disconnect(self) -> None: pass class Client: session_config = None async def start(self) -> None: pass async def create_session(self, **kwargs): self.__class__.session_config = kwargs return ValidationSession(kwargs["tools"]) async def stop(self) -> None: pass monkeypatch.setattr("afk_developer.backends.copilot._create_client", Client) config = Config( endpoints={"copilot": EndpointProfile("copilot", EndpointType.COPILOT)}, validator=RoleRoute( endpoint="copilot", model="gpt-5.6-terra", reasoning_effort="high", ), ) task = TaskNode( id="validate", title="Validate corpus", description="Inspect output without modification.", evidence_roots=[str(evidence_root)], ) result = asyncio.run( CopilotValidator(config, "validator")._validate_async( task, str(project), "trusted context", 3, ) ) assert result.outcome is AcceptanceOutcome.PASS assert Client.session_config["model"] == "gpt-5.6-terra" assert Client.session_config["reasoning_effort"] == "high" assert "omit paths and extra_safe_args" in Client.session_config["system_message"]["content"] tool_names = {tool.name for tool in Client.session_config["tools"]} assert { "read_file", "read_evidence_file", "run_verification", "submit_acceptance_result", } <= tool_names verifier = next( tool for tool in Client.session_config["tools"] if tool.name == "run_verification" ) assert "file_sha256" in verifier.parameters["properties"]["kind"]["enum"] assert "baseline_compare" not in verifier.parameters["properties"]["kind"]["enum"] assert "baseline_compare" not in verifier.parameters["properties"]["kind"]["description"] assert ( not { "write_file", "edit_file", "run_command", "task_complete", "submit_evidence_proposal", } & tool_names )