import asyncio import sys from pathlib import Path from types import ModuleType, SimpleNamespace import pytest from afk_developer.backends.fake import FakeCoderBackend, FakeReasonerBackend from afk_developer.backends.models import TaskExecutionResult from afk_developer.backends.copilot import ( CopilotCoder, CopilotResearcher, _CopilotUsageCollector, _send_and_wait, ) from afk_developer.backends.openai_compatible import ( OpenAICompatibleResearcher, _normalize_openai_usage, ) from afk_developer.backends.registry import BackendRegistry from afk_developer.config import Config, EndpointProfile, EndpointType, RoleRoute from afk_developer.grillme.spec_model import DetectedContext, TaskIntent, TaskSpec from afk_developer.planner import decomposer from afk_developer.planner.task_model import ( DiscoveryContract, TaskFailureKind, TaskNode, TaskStatus, ) from afk_developer.scheduler.tools.file_ops import ( read_evidence_file, read_evidence_metadata, read_evidence_section, search_evidence_text, ) def test_fake_reasoner_returns_responses_in_order(): backend = FakeReasonerBackend(['{"tasks": []}', "summary"]) first = backend.complete(system_prompt="system", user_prompt="plan") second = backend.complete(system_prompt="system", user_prompt="summarize") assert first.content == '{"tasks": []}' assert second.content == "summary" assert backend.requests == [("system", "plan"), ("system", "summarize")] def test_fake_coder_records_task_and_returns_configured_result(): task = TaskNode(id="add-tests", title="Add tests", description="Create tests") result = TaskExecutionResult( status=TaskStatus.PASSED, summary="done", files_changed=["tests/test_example.py"], ) backend = FakeCoderBackend(lambda _task: result) actual = backend.execute_task( task=task, project_dir="C:/work/example", context="", hitl_mode=False, max_turns=1, ) assert actual == result assert backend.tasks == [task] def test_registry_resolves_copilot_routes_without_starting_a_client(): config = Config( endpoints={"copilot": EndpointProfile("copilot", EndpointType.COPILOT)}, reasoner=RoleRoute(endpoint="copilot", model="gpt-5"), coder=RoleRoute(endpoint="copilot", model="gpt-5"), ) registry = BackendRegistry(config) assert type(registry.get_reasoner()).__name__ == "CopilotReasoner" assert type(registry.get_coder()).__name__ == "CopilotCoder" def test_registry_resolves_foreman_and_coder_light_routes_by_inheritance(): config = Config( endpoints={"copilot": EndpointProfile("copilot", EndpointType.COPILOT)}, reasoner=RoleRoute(endpoint="copilot", model="gpt-5"), coder=RoleRoute(endpoint="copilot", model="gpt-5"), ) registry = BackendRegistry(config) assert type(registry.get_foreman()).__name__ == "CopilotReasoner" assert type(registry.get_coder_light()).__name__ == "CopilotCoder" assert config.route_for("foreman") == config.route_for("reasoner") assert config.route_for("coder_light") == config.route_for("coder") def test_brownfield_audit_task_can_be_read_only(monkeypatch, tmp_path: Path) -> None: class FakeRegistry: def __init__(self, _config: Config) -> None: pass def get_reasoner(self) -> FakeReasonerBackend: return FakeReasonerBackend( [ '{"tasks":[{"id":"audit","title":"Audit baseline",' '"description":"Read source and run tests",' '"dependencies":[],"read_only":true}]}' ] ) monkeypatch.setattr(decomposer, "BackendRegistry", FakeRegistry) spec = TaskSpec( project_name="existing-app", project_dir=tmp_path, goal="Extend the existing application", intent=TaskIntent.IMPLEMENT, auto_detected=DetectedContext(existing_files_count=3), ) plan = decomposer.decompose_task(spec, Config()) assert plan.tasks[0].read_only is True assert plan.tasks[0].status.value == "pending" def test_decomposer_preserves_red_regression_test_files(monkeypatch, tmp_path: Path) -> None: class FakeRegistry: def __init__(self, _config: Config) -> None: pass def get_reasoner(self) -> FakeReasonerBackend: return FakeReasonerBackend( [ '{"tasks":[' '{"id":"red","title":"Add red witness",' '"description":"Create the intentional failing test",' '"dependencies":[],"red_regression_test_files":' '["tests/test_red.py"]},' '{"id":"repair","title":"Repair behavior",' '"description":"Make the witness pass","dependencies":["red"]}' "]}" ] ) monkeypatch.setattr(decomposer, "BackendRegistry", FakeRegistry) spec = TaskSpec( project_name="existing-app", project_dir=tmp_path, goal="Add one red witness and its repair", intent=TaskIntent.IMPLEMENT, auto_detected=DetectedContext(existing_files_count=3), ) plan = decomposer.decompose_task(spec, Config()) assert plan.tasks[0].red_regression_test_files == ["tests/test_red.py"] assert plan.tasks[0].disallow_unscoped_pytest is True def test_decomposer_preserves_executable_task_contract_fields(monkeypatch, tmp_path: Path) -> None: class FakeRegistry: def __init__(self, _config: Config) -> None: pass def get_reasoner(self) -> FakeReasonerBackend: return FakeReasonerBackend( [ ( '{"tasks":[{"id":"scaffold","title":"Create scaffold",' '"description":"Create the package metadata",' '"dependencies":[],"required_artifacts":["pyproject.toml"],' '"acceptance_criteria":["The package metadata parses."],' '"disallow_unscoped_pytest":true}]}' ) ] ) monkeypatch.setattr(decomposer, "BackendRegistry", FakeRegistry) spec = TaskSpec( project_name="new-app", project_dir=tmp_path, goal="Create a bounded project scaffold", intent=TaskIntent.IMPLEMENT, ) plan = decomposer.decompose_task(spec, Config()) assert plan.tasks[0].required_artifacts == ["pyproject.toml"] assert plan.tasks[0].acceptance_criteria == ["The package metadata parses."] assert plan.tasks[0].disallow_unscoped_pytest is True def test_decomposer_preserves_explicit_discovery_contract(monkeypatch, tmp_path: Path) -> None: class FakeRegistry: def __init__(self, _config: Config) -> None: pass def get_reasoner(self) -> FakeReasonerBackend: return FakeReasonerBackend( [ '{"tasks":[{"id":"witness","title":"Write witness",' '"description":"Create the focused witness","dependencies":[],' '"discovery_contract":{"cache_key":"opcode-94-95",' '"questions":["Which templates are canonical?"],' '"input_paths":["src/cpu.py","tests/template.py"],' '"allowed_output_paths":["tests/test_94.py"],' '"exclusions":["Do not inspect opcode 96."]}}]}' ] ) monkeypatch.setattr(decomposer, "BackendRegistry", FakeRegistry) plan = decomposer.decompose_task( TaskSpec( project_name="existing-app", project_dir=tmp_path, goal="Add one focused witness", intent=TaskIntent.IMPLEMENT, auto_detected=DetectedContext(existing_files_count=3), ), Config(), ) contract = plan.tasks[0].discovery_contract assert contract is not None assert contract.cache_key == "opcode-94-95" assert contract.input_paths == ["src/cpu.py", "tests/template.py"] def test_decomposer_adds_evidence_gates_to_dependencies(monkeypatch, tmp_path: Path) -> None: class FakeRegistry: def __init__(self, _config: Config) -> None: pass def get_reasoner(self) -> FakeReasonerBackend: return FakeReasonerBackend( [ '{"tasks":[' '{"id":"discover","title":"Discover source","description":"Read corpus",' '"dependencies":[],"read_only":true},' '{"id":"implement","title":"Implement source","description":"Write code",' '"dependencies":[],"evidence_gated_by":["discover"]}' "]}" ] ) monkeypatch.setattr(decomposer, "BackendRegistry", FakeRegistry) spec = TaskSpec( project_name="existing-app", project_dir=tmp_path, goal="Implement only source-proven output", intent=TaskIntent.IMPLEMENT, auto_detected=DetectedContext(existing_files_count=3), ) plan = decomposer.decompose_task(spec, Config()) assert plan.tasks[1].dependencies == ["discover"] assert plan.tasks[1].evidence_gated_by == [] def test_decomposer_keeps_evidence_gate_when_discovery_has_an_external_root( monkeypatch, tmp_path: Path ) -> None: corpus = tmp_path.parent / "immutable-corpus" corpus.mkdir() class FakeRegistry: def __init__(self, _config: Config) -> None: pass def get_reasoner(self) -> FakeReasonerBackend: return FakeReasonerBackend( [ '{"tasks":[' f'{{"id":"discover","title":"Discover source","description":"Read corpus",' f'"dependencies":[],"read_only":true,"evidence_roots":["{corpus.as_posix()}"]}},' '{"id":"implement","title":"Implement source","description":"Write code",' '"dependencies":[],"evidence_gated_by":["discover"]}' "]}" ] ) monkeypatch.setattr(decomposer, "BackendRegistry", FakeRegistry) spec = TaskSpec( project_name="existing-app", project_dir=tmp_path, goal="Implement only source-proven output", intent=TaskIntent.IMPLEMENT, auto_detected=DetectedContext(existing_files_count=3), ) plan = decomposer.decompose_task(spec, Config()) assert plan.tasks[1].dependencies == ["discover"] assert plan.tasks[1].evidence_gated_by == ["discover"] def test_copilot_wait_enforces_a_hard_async_deadline() -> None: class UnresponsiveSession: async def send_and_wait(self, _prompt: str, *, timeout: float) -> None: del timeout await asyncio.Event().wait() with pytest.raises(TimeoutError): asyncio.run(_send_and_wait(UnresponsiveSession(), "task", 0.01)) def test_copilot_usage_collector_normalizes_sdk_events() -> None: collector = _CopilotUsageCollector("copilot", "gpt-5.6-luna") collector.record_prompt() collector.handle_event( SimpleNamespace( type=SimpleNamespace(value="assistant.usage"), data=SimpleNamespace( model="gpt-5.6-luna", input_tokens=100, output_tokens=25, cache_read_tokens=60, cache_write_tokens=10, reasoning_tokens=15, copilot_usage=SimpleNamespace(total_nano_aiu=2_500_000_000.0), ), ) ) collector.handle_event( SimpleNamespace(type=SimpleNamespace(value="assistant.turn_end"), data=None) ) collector.handle_event( SimpleNamespace( type=SimpleNamespace(value="session.usage_checkpoint"), data=SimpleNamespace(total_nano_aiu=3_000_000_000.0), ) ) usage = collector.to_backend_usage() assert usage.api_calls == 1 assert usage.agent_turns == 1 assert usage.prompt_tokens == 100 assert usage.completion_tokens == 25 assert usage.copilot_prompts_submitted == 1 assert usage.copilot_nano_aiu == 3_000_000_000.0 assert usage.telemetry_available assert usage.model_usages[0].copilot_nano_aiu == 3_000_000_000.0 def test_openai_compatible_usage_preserves_optional_cache_and_reasoning_details() -> None: usage = _normalize_openai_usage( SimpleNamespace( prompt_tokens=1_000, completion_tokens=200, total_tokens=1_200, prompt_tokens_details=SimpleNamespace( cached_tokens=650, cache_creation_tokens=75, ), completion_tokens_details=SimpleNamespace(reasoning_tokens=125), ) ) assert usage.prompt_tokens == 1_000 assert usage.completion_tokens == 200 assert usage.total_tokens == 1_200 assert usage.cache_read_tokens == 650 assert usage.cache_write_tokens == 75 assert usage.reasoning_tokens == 125 assert usage.api_calls == 1 def test_openai_compatible_researcher_submits_structured_local_discovery( monkeypatch, tmp_path: Path ) -> None: import openai proposal = { "source_paths": ["src/example.py"], "canonical_paths": ["src/example.py"], "canonical_symbols": ["Example"], "conclusions": ["Example is the canonical entry point."], "approved_next_action": "Implement only the declared test file.", "summary": "Use the known entry point without broad rediscovery.", } tool_call = SimpleNamespace( id="call-1", function=SimpleNamespace( name="submit_discovery_proposal", arguments=__import__("json").dumps(proposal), ), ) response = SimpleNamespace( usage=SimpleNamespace(prompt_tokens=10, completion_tokens=5, total_tokens=15), choices=[SimpleNamespace(message=SimpleNamespace(content="", tool_calls=[tool_call]))], ) class FakeCompletions: def __init__(self) -> None: self.calls = [] def create(self, **kwargs): self.calls.append(kwargs) return response completions = FakeCompletions() class FakeOpenAI: def __init__(self, **_kwargs) -> None: self.chat = SimpleNamespace(completions=completions) monkeypatch.setattr(openai, "OpenAI", FakeOpenAI) project = tmp_path / "project" (project / "src").mkdir(parents=True) (project / "src" / "example.py").write_text("class Example: pass\n", encoding="utf-8") config = Config( api_key="test-key", endpoints={ "deepseek": EndpointProfile("deepseek", EndpointType.OPENAI_COMPATIBLE), }, reasoner=RoleRoute(endpoint="deepseek", model="test-model"), ) backend = OpenAICompatibleResearcher(config, "researcher") result = backend.propose_discovery( task=TaskNode(id="discover", title="Discover", description="Inspect source."), project_dir=str(project), contract=DiscoveryContract( questions=["What is the entry point?"], input_paths=["src/example.py"], allowed_output_paths=["tests/test_example.py"], ), context="Declared input manifest: src/example.py", max_turns=2, ) assert result.status is TaskStatus.PASSED assert result.draft is not None assert result.draft.canonical_symbols == ["Example"] assert completions.calls[0]["tools"][-2]["function"]["name"] == "submit_discovery_proposal" names = [item["function"]["name"] for item in completions.calls[0]["tools"]] assert not {"write_file", "edit_file", "run_command"}.intersection(names) def test_copilot_researcher_submits_structured_local_discovery(monkeypatch, tmp_path: Path) -> None: 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.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) proposal = { "source_paths": ["src/example.py"], "canonical_paths": ["src/example.py"], "canonical_symbols": ["Example"], "conclusions": ["Example is the canonical entry point."], "approved_next_action": "Implement only the declared test file.", "summary": "Use the known entry point without broad rediscovery.", } class DiscoverySession: def __init__(self, tools) -> None: self.tools = tools async def send_and_wait(self, _prompt: str, *, timeout: float): del timeout submit = next(tool for tool in self.tools if tool.name == "submit_discovery_proposal") submitted = submit.handler(SimpleNamespace(arguments=proposal)) assert submitted.result_type == "success" return SimpleNamespace(data=SimpleNamespace(content="")) 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 DiscoverySession(kwargs["tools"]) async def stop(self) -> None: pass monkeypatch.setattr("afk_developer.backends.copilot._create_client", Client) project = tmp_path / "project" (project / "src").mkdir(parents=True) (project / "src" / "example.py").write_text("class Example: pass\n", encoding="utf-8") config = Config( endpoints={"copilot": EndpointProfile("copilot", EndpointType.COPILOT)}, reasoner=RoleRoute(endpoint="copilot", model="gpt-5"), ) result = asyncio.run( CopilotResearcher(config, "researcher")._propose_discovery_async( TaskNode(id="discover", title="Discover", description="Inspect source."), str(project), DiscoveryContract( questions=["What is the entry point?"], input_paths=["src/example.py"], allowed_output_paths=["tests/test_example.py"], ), "Declared input manifest: src/example.py", 2, ) ) assert result.status is TaskStatus.PASSED assert result.draft is not None assert result.draft.canonical_symbols == ["Example"] names = {tool.name for tool in Client.session_config["tools"]} assert "submit_discovery_proposal" in names assert not {"write_file", "edit_file", "run_command", "task_complete"}.intersection(names) def test_copilot_researcher_forces_terminal_submission_after_empty_response( monkeypatch, tmp_path: Path ) -> None: 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) proposal = { "source_paths": ["src/example.py"], "conclusions": ["Example is the declared local seam."], "approved_next_action": "Write only the declared test file.", "summary": "Use the declared source seam.", } class Session: def __init__(self, tools) -> None: self.tools = tools self.prompts: list[str] = [] async def send_and_wait(self, prompt: str, *, timeout: float): del timeout self.prompts.append(prompt) if len(self.prompts) == 2: submit = next( tool for tool in self.tools if tool.name == "submit_discovery_proposal" ) assert submit.handler(SimpleNamespace(arguments=proposal)).result_type == "success" return SimpleNamespace(data=SimpleNamespace(content="")) async def disconnect(self) -> None: pass class Client: session = None async def start(self) -> None: pass async def create_session(self, **kwargs): self.__class__.session = Session(kwargs["tools"]) return self.session async def stop(self) -> None: pass monkeypatch.setattr("afk_developer.backends.copilot._create_client", Client) project = tmp_path / "project" (project / "src").mkdir(parents=True) (project / "src" / "example.py").write_text("class Example: pass\n", encoding="utf-8") config = Config( endpoints={"copilot": EndpointProfile("copilot", EndpointType.COPILOT)}, reasoner=RoleRoute(endpoint="copilot", model="gpt-5"), ) result = asyncio.run( CopilotResearcher(config, "researcher")._propose_discovery_async( TaskNode(id="discover", title="Discover", description="Inspect source."), str(project), DiscoveryContract( questions=["What is the local seam?"], input_paths=["src/example.py"], allowed_output_paths=["tests/test_example.py"], ), "Declared input manifest: src/example.py", 2, ) ) assert result.status is TaskStatus.PASSED assert len(Client.session.prompts) == 2 assert "MUST be exactly one call to submit_discovery_proposal" in Client.session.prompts[1] def test_copilot_coder_records_sdk_usage_events(monkeypatch, tmp_path: Path) -> None: 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 EventSession: def __init__(self) -> None: self.handlers = [] self.prompts = [] def on(self, handler): self.handlers.append(handler) def unsubscribe() -> None: self.handlers.remove(handler) return unsubscribe async def send_and_wait(self, _prompt: str, *, timeout: float): del timeout self.prompts.append(_prompt) for handler in self.handlers: handler( SimpleNamespace( type=SimpleNamespace(value="assistant.usage"), data=SimpleNamespace( model="gpt-5.6-luna", input_tokens=80, output_tokens=20, cache_read_tokens=0, cache_write_tokens=0, reasoning_tokens=0, copilot_usage=SimpleNamespace(total_nano_aiu=500_000_000.0), ), ) ) handler( SimpleNamespace(type=SimpleNamespace(value="assistant.turn_end"), data=None) ) return SimpleNamespace(data=SimpleNamespace(content="No completion tool call.")) async def disconnect(self) -> None: pass class Client: session = None async def start(self) -> None: pass async def create_session(self, **_kwargs): self.__class__.session = EventSession() return self.session async def stop(self) -> None: pass monkeypatch.setattr("afk_developer.backends.copilot._create_client", Client) config = Config( endpoints={"copilot": EndpointProfile("copilot", EndpointType.COPILOT)}, coder=RoleRoute(endpoint="copilot", model="gpt-5.6-luna"), ) result = asyncio.run( CopilotCoder(config, "coder")._execute_async( TaskNode( id="audit", title="Audit", description="Inspect", read_only=True, evidence_packet_id="project/audit/revision-1", ), str(tmp_path), "", False, 1, ) ) assert result.status is TaskStatus.FAILED assert config.stats.api_calls == 1 assert config.stats.total_turns == 1 assert config.stats.copilot_prompts_submitted == 1 assert config.stats.copilot_ai_credits == 0.5 assert "Evidence gate already passed" in Client.session.prompts[0] @pytest.mark.parametrize("recover", [False, True]) def test_copilot_coder_handles_rejected_task_complete( monkeypatch, tmp_path: Path, recover: bool ) -> None: 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.text_result_for_llm = 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 Session: def __init__(self, tools) -> None: self.tools = {tool.name: tool for tool in tools} async def send_and_wait(self, _prompt: str, *, timeout: float): del timeout outcome = self.tools["task_complete"].handler( SimpleNamespace(arguments={"summary": "No changes needed.", "files_changed": []}) ) assert outcome.result_type == "rejected" if recover: written = self.tools["write_file"].handler( SimpleNamespace( arguments={"path": "result.py", "content": "completed = True\n"} ) ) assert written.result_type == "success" outcome = self.tools["task_complete"].handler( SimpleNamespace( arguments={ "summary": "Task completed after writing.", "files_changed": ["result.py"], } ) ) assert outcome.result_type == "success" return SimpleNamespace(data=SimpleNamespace(content="")) async def disconnect(self) -> None: pass class Client: async def start(self) -> None: pass async def create_session(self, **kwargs): return Session(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)}, coder=RoleRoute(endpoint="copilot", model="gpt-5.6-luna"), ) result = asyncio.run( CopilotCoder(config, "coder")._execute_async( TaskNode(id="repair", title="Repair", description="Make a bounded repair."), str(tmp_path), "", False, 1, ) ) if recover: assert result.status is TaskStatus.PASSED assert result.summary == "Task completed after writing." assert result.tool_name_counts == {"task_complete": 2, "write_file": 1} else: assert result.status is TaskStatus.FAILED assert result.summary == "REJECTED: Create or edit at least one file before task_complete." assert result.tool_name_counts == {"task_complete": 1} def test_copilot_startup_failure_returns_a_task_result(monkeypatch, tmp_path: Path) -> None: 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 FailingClient: stopped = False async def start(self) -> None: raise ConnectionError("failed to fetch authenticated GitHub user") async def stop(self) -> None: self.stopped = True client = FailingClient() monkeypatch.setattr("afk_developer.backends.copilot._create_client", lambda: client) config = Config( endpoints={"copilot": EndpointProfile("copilot", EndpointType.COPILOT)}, coder=RoleRoute(endpoint="copilot", model="gpt-5"), ) result = asyncio.run( CopilotCoder(config, "coder")._execute_async( TaskNode(id="task", title="Task", description="Do work"), str(tmp_path), "", False, 1, ) ) assert result.status is TaskStatus.ESCALATED assert result.summary.startswith("Copilot error:") assert result.failure_kind is TaskFailureKind.PROVIDER_UNAVAILABLE assert client.stopped def test_read_evidence_file_stays_inside_approved_root(tmp_path: Path) -> None: evidence = tmp_path / "evidence" evidence.mkdir() (evidence / "contract.xml").write_text("\n", encoding="utf-8") outside = tmp_path / "outside.xml" outside.write_text("outside\n", encoding="utf-8") assert "1: " in read_evidence_file("contract.xml", [str(evidence)]) assert "Error:" in read_evidence_file("../outside.xml", [str(evidence)]) assert "Error:" in read_evidence_file(str(outside), [str(evidence)]) def test_read_evidence_metadata_reports_bytes_without_exposing_content(tmp_path: Path) -> None: evidence = tmp_path / "evidence" evidence.mkdir() source = evidence / "contract.xml" source.write_bytes(b"verified\r\n") outside = tmp_path / "outside.xml" outside.write_text("outside\n", encoding="utf-8") metadata = read_evidence_metadata("contract.xml", [str(evidence)]) assert "Byte length: 31" in metadata assert "UTF-8 decode: valid; BOM: none" in metadata assert "ASCII-only: yes" in metadata assert "Line endings: LF=0, CRLF=1, CR=0" in metadata assert "Terminal newline: crlf" in metadata assert "verified" not in metadata assert "Error:" in read_evidence_metadata("../outside.xml", [str(evidence)]) assert "Error:" in read_evidence_metadata(str(outside), [str(evidence)]) def test_read_evidence_section_extracts_only_the_requested_instance(tmp_path: Path) -> None: evidence = tmp_path / "evidence" evidence.mkdir() corpus = evidence / "project.xml" corpus.write_text( 'ignore' 'verified' 'ignore', encoding="utf-8", ) section = read_evidence_section( "project.xml", '', [str(evidence)], "", ) assert section == 'verified' assert "Error:" in read_evidence_section( "project.xml", '', [str(evidence)] ) def test_search_evidence_text_reports_per_file_literal_counts(tmp_path: Path) -> None: evidence = tmp_path / "evidence" evidence.mkdir() (evidence / "one.xml").write_text("DSCMA DSCMA", encoding="utf-8") nested = evidence / "nested" nested.mkdir() (nested / "two.XML").write_text("DSCMA", encoding="utf-8") (evidence / "ignore.json").write_text("DSCMA", encoding="utf-8") result = search_evidence_text("DSCMA", [str(evidence)]) assert "one.xml (2 matches" in result assert "nested\\two.XML (1 matches" in result assert "ignore.json" not in result def test_copilot_read_only_task_requires_explicit_completion(monkeypatch, tmp_path: Path) -> None: evidence_root = tmp_path / "evidence" evidence_root.mkdir() 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.parameters = kwargs["parameters"] 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 IncompleteSession: prompt = None async def send_and_wait(self, prompt: str, *, timeout: float): del timeout self.__class__.prompt = prompt return SimpleNamespace(data=SimpleNamespace(content="The corpus is unavailable.")) 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 IncompleteSession() async def stop(self) -> None: pass monkeypatch.setattr("afk_developer.backends.copilot._create_client", Client) config = Config( endpoints={"copilot": EndpointProfile("copilot", EndpointType.COPILOT)}, coder=RoleRoute(endpoint="copilot", model="gpt-5"), ) result = asyncio.run( CopilotCoder(config, "coder")._execute_async( TaskNode( id="audit", title="Audit", description="Inspect corpus", read_only=True, evidence_roots=[str(evidence_root)], ), str(tmp_path), "", False, 1, ) ) assert result.status is TaskStatus.FAILED assert "without calling task_complete" in result.summary tool_names = {tool.name for tool in Client.session_config["tools"]} assert "run_verification" in tool_names assert "compare_ruff_baseline" not in tool_names assert "run_command" not in tool_names assert "read_evidence_section" in tool_names assert "read_evidence_metadata" in tool_names assert ( "For a large or one-line corpus XML" in Client.session_config["system_message"]["content"] ) assert "omit paths and extra_safe_args" in Client.session_config["system_message"]["content"] assert ( "manifest references already supplied in this trusted task contract" in IncompleteSession.prompt ) assert "not as project files" in IncompleteSession.prompt verifier = next( tool for tool in Client.session_config["tools"] if tool.name == "run_verification" ) verification_kinds = verifier.parameters["properties"]["kind"]["enum"] assert "file_sha256" in verification_kinds assert "baseline_compare" not in verification_kinds def test_copilot_coder_rejects_repeated_checkpoint_input_read(monkeypatch, tmp_path: Path) -> None: 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.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) outcomes: list[ToolResult] = [] class Session: def __init__(self, tools) -> None: self.tools = tools async def send_and_wait(self, _prompt: str, *, timeout: float): del timeout reader = next(tool for tool in self.tools if tool.name == "read_file") outcomes.append(reader.handler(SimpleNamespace(arguments={"path": "src/example.py"}))) outcomes.append(reader.handler(SimpleNamespace(arguments={"path": "src/example.py"}))) return SimpleNamespace(data=SimpleNamespace(content="No completion tool call.")) async def disconnect(self) -> None: pass class Client: async def start(self) -> None: pass async def create_session(self, **kwargs): return Session(kwargs["tools"]) async def stop(self) -> None: pass monkeypatch.setattr("afk_developer.backends.copilot._create_client", Client) (tmp_path / "src").mkdir() (tmp_path / "src" / "example.py").write_text("VALUE = 1\n", encoding="utf-8") config = Config( endpoints={"copilot": EndpointProfile("copilot", EndpointType.COPILOT)}, coder=RoleRoute(endpoint="copilot", model="gpt-5"), ) task = TaskNode( id="implement", title="Implement", description="Use checkpoint facts.", discovery_contract=DiscoveryContract( questions=["What is the seam?"], input_paths=["src/example.py"], allowed_output_paths=["tests/test_example.py"], ), discovery_checkpoint_fingerprint="a" * 64, ) result = asyncio.run( CopilotCoder(config, "coder")._execute_async(task, str(tmp_path), "checkpoint", False, 1) ) assert result.status is TaskStatus.FAILED assert outcomes[0].result_type == "success" assert outcomes[1].result_type == "rejected" assert outcomes[1].text.startswith("CHECKPOINT_READ_BUDGET_REJECTED:") def test_copilot_discovery_governor_followup_can_write_and_complete( monkeypatch, tmp_path: Path ) -> None: 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.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 Session: def __init__(self, tools) -> None: self.tools = {tool.name: tool for tool in tools} self.prompts: list[str] = [] self.handlers = [] def on(self, handler): self.handlers.append(handler) def unsubscribe() -> None: self.handlers.remove(handler) return unsubscribe async def send_and_wait(self, prompt: str, *, timeout: float): del timeout self.prompts.append(prompt) if len(self.prompts) == 1: self.tools["read_file"].handler(SimpleNamespace(arguments={"path": "source.py"})) for handler in self.handlers: handler( SimpleNamespace(type=SimpleNamespace(value="assistant.turn_end"), data=None) ) elif len(self.prompts) == 2: rejected = self.tools["grep_codebase"].handler( SimpleNamespace(arguments={"pattern": "more"}) ) assert rejected.text.startswith("DISCOVERY_PROGRESS_REJECTED:") else: written = self.tools["write_file"].handler( SimpleNamespace(arguments={"path": "app.py", "content": "x = 1\n"}) ) assert written.result_type == "success" self.tools["task_complete"].handler( SimpleNamespace(arguments={"summary": "done", "files_changed": ["app.py"]}) ) return SimpleNamespace(data=SimpleNamespace(content="")) async def disconnect(self) -> None: pass class Client: session = None async def start(self) -> None: pass async def create_session(self, **kwargs): self.__class__.session = Session(kwargs["tools"]) return self.session async def stop(self) -> None: pass monkeypatch.setattr("afk_developer.backends.copilot._create_client", Client) (tmp_path / "source.py").write_text("SOURCE = 1\n", encoding="utf-8") config = Config( endpoints={"copilot": EndpointProfile("copilot", EndpointType.COPILOT)}, coder=RoleRoute(endpoint="copilot", model="gpt-5"), discovery_progress_turn_limit=1, discovery_progress_tool_limit=0, ) result = asyncio.run( CopilotCoder(config, "coder")._execute_async( TaskNode(id="governed", title="Governed", description="Create app.py"), str(tmp_path), "", False, 20, ) ) assert result.status is TaskStatus.PASSED assert result.files_changed == ["app.py"] assert result.tool_name_counts == { "read_file": 1, "grep_codebase": 1, "write_file": 1, "task_complete": 1, } assert len(Client.session.prompts) == 3 assert "bounded discovery phase is over" in Client.session.prompts[1].lower() assert "previous pre-write tool call was rejected" in Client.session.prompts[2].lower() def test_copilot_discovery_governor_fails_later_defiance_without_dispatch( monkeypatch, tmp_path: Path ) -> None: 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.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) dispatched: list[str] = [] def fake_dispatch(name, _args, **_kwargs): dispatched.append(name) return "source" monkeypatch.setattr("afk_developer.backends.copilot.dispatch_tool_call", fake_dispatch) class Session: def __init__(self, tools) -> None: self.tools = {tool.name: tool for tool in tools} self.calls = 0 async def send_and_wait(self, _prompt: str, *, timeout: float): del timeout self.calls += 1 if self.calls == 1: self.tools["read_file"].handler(SimpleNamespace(arguments={"path": "source.py"})) self.tools["grep_codebase"].handler( SimpleNamespace(arguments={"pattern": "same-turn"}) ) else: rejected = self.tools["glob_files"].handler( SimpleNamespace(arguments={"pattern": "**/*.py"}) ) assert rejected.text.startswith("DISCOVERY_PROGRESS_REJECTED:") return SimpleNamespace(data=SimpleNamespace(content="")) async def disconnect(self) -> None: pass class Client: session = None async def start(self) -> None: pass async def create_session(self, **kwargs): self.__class__.session = Session(kwargs["tools"]) return self.session async def stop(self) -> None: pass monkeypatch.setattr("afk_developer.backends.copilot._create_client", Client) config = Config( endpoints={"copilot": EndpointProfile("copilot", EndpointType.COPILOT)}, coder=RoleRoute(endpoint="copilot", model="gpt-5"), discovery_progress_turn_limit=0, discovery_progress_tool_limit=1, ) result = asyncio.run( CopilotCoder(config, "coder")._execute_async( TaskNode(id="defiant", title="Defiant", description="Create app.py"), str(tmp_path), "", False, 20, ) ) assert result.status is TaskStatus.FAILED assert result.failure_kind is TaskFailureKind.DISCOVERY_PROGRESS_STALLED assert result.summary.startswith("DISCOVERY_PROGRESS_STALLED:") assert dispatched == ["read_file"] assert Client.session.calls == 2 def test_copilot_typed_verification_policy_failure_escalates_task( monkeypatch, tmp_path: Path ) -> None: 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.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 VerificationSession: 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") outcome = verifier.handler( SimpleNamespace(arguments={"kind": "pytest", "paths": ["../outside.py"]}) ) assert outcome.result_type == "rejected" return SimpleNamespace(data=SimpleNamespace(content="Ignored after rejection.")) async def disconnect(self) -> None: pass class Client: async def start(self) -> None: pass async def create_session(self, **kwargs): return VerificationSession(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)}, coder=RoleRoute(endpoint="copilot", model="gpt-5"), ) result = asyncio.run( CopilotCoder(config, "coder")._execute_async( TaskNode(id="audit", title="Audit", description="Inspect", read_only=True), str(tmp_path), "", False, 1, ) ) assert result.status is TaskStatus.ESCALATED assert result.summary.startswith("VERIFICATION_POLICY_REJECTED:") assert result.failure_kind is TaskFailureKind.VERIFICATION_POLICY_REJECTED assert len(result.verification_events) == 2 for event in result.verification_events: assert event.kind == "pytest" assert event.normalized_path_count == 1 assert event.outcome_code == "verification_policy_rejected" assert event.rejection_reason