import asyncio import hashlib import json import os import shutil import traceback from collections import Counter from pathlib import Path from afk_developer.backends.base import ( CoderBackend, ReasonerBackend, ResearcherBackend, ValidatorBackend, ) from afk_developer.backends.models import ( BackendResponse, BackendUsage, DiscoveryProposalResult, ModelUsage, ResearchProposalResult, TaskExecutionResult, AcceptanceFinding, AcceptanceOutcome, AcceptanceValidationResult, ) from afk_developer.config import Config, LintMode from afk_developer.events import emit from afk_developer.evidence import ( EVIDENCE_PACKET_DRAFT_TOOL_SCHEMA, EvidencePacketDraft, EvidencePacketError, normalize_evidence_roots, ) from afk_developer.planner.task_model import ( DiscoveryContract, TaskFailureKind, TaskNode, TaskStatus, ) from afk_developer.scheduler.discovery_checkpoint import DiscoveryCheckpointDraft from afk_developer.scheduler.tools.codebase import discover_project, grep_codebase, list_directory from afk_developer.scheduler.tools.file_ops import ( glob_files, read_evidence_file, read_evidence_section, read_file, search_evidence_text, ) from afk_developer.scheduler.tools.dispatch import dispatch_tool_call from afk_developer.scheduler.tools.checkpoint_read_budget import CheckpointReadBudget from afk_developer.scheduler.tools.discovery_progress_governor import DiscoveryProgressGovernor from afk_developer.scheduler.tools.schemas import build_tool_schemas, tool_parameters from afk_developer.scheduler.verification import ( VerificationOutcomeCode, run_verification_request, verification_attempt_event, ) async def _send_and_wait(session, prompt: str, timeout: float): """Enforce the configured deadline even if the SDK does not enforce its own timeout.""" return await asyncio.wait_for( session.send_and_wait(prompt, timeout=timeout), timeout=timeout, ) _CLEANUP_TIMEOUT_SECONDS = 15.0 async def _complete_cleanup(awaitable) -> None: """Bound SDK cleanup so a timed-out call cannot leave AFK running forever.""" try: await asyncio.wait_for(awaitable, timeout=_CLEANUP_TIMEOUT_SECONDS) except TimeoutError: pass except Exception: pass async def _disconnect_session(session) -> None: """Best-effort session cleanup with an independent deadline.""" await _complete_cleanup(session.disconnect()) async def _stop_client(client) -> None: """Best-effort client cleanup with an independent deadline.""" await _complete_cleanup(client.stop()) def _response_content(response) -> str: """Return final provider text without depending on SDK response classes.""" return getattr(getattr(response, "data", None), "content", "") or "" def _parse_evidence_draft_response(content: str) -> EvidencePacketDraft | None: """Parse explicit JSON fallback when a provider skips the proposal tool. The parsed proposal remains untrusted: the evidence store still validates roots, source markers, hashes, excerpts, and raw-output contracts before an immutable packet can be attached to a task. """ text = content.strip() if text.startswith("```") and text.endswith("```"): text = text.split("\n", 1)[1] if "\n" in text else "" text = text.rsplit("```", 1)[0].strip() if not text.startswith("{"): return None try: return EvidencePacketDraft.model_validate(json.loads(text)) except (json.JSONDecodeError, ValueError, TypeError): return None _DISCOVERY_DRAFT_TOOL_SCHEMA = { "type": "object", "additionalProperties": False, "properties": { "source_paths": {"type": "array", "items": {"type": "string"}}, "canonical_paths": {"type": "array", "items": {"type": "string"}}, "canonical_symbols": {"type": "array", "items": {"type": "string"}}, "conclusions": {"type": "array", "items": {"type": "string"}}, "approved_next_action": {"type": "string"}, "summary": {"type": "string"}, }, "required": ["source_paths", "conclusions", "approved_next_action", "summary"], } def _parse_discovery_draft_response(content: str) -> DiscoveryCheckpointDraft | None: """Parse the JSON fallback when the provider skips structured submission.""" text = content.strip() if text.startswith("```") and text.endswith("```"): text = text.split("\n", 1)[1] if "\n" in text else "" text = text.rsplit("```", 1)[0].strip() if not text.startswith("{"): return None try: return DiscoveryCheckpointDraft.model_validate(json.loads(text)) except (json.JSONDecodeError, ValueError, TypeError): return None def _create_client(): """Create a Copilot client using an installed CLI when one is available.""" from copilot import CopilotClient, RuntimeConnection cli_path = os.environ.get("AFK_COPILOT_CLI_PATH") or os.environ.get("COPILOT_CLI_PATH") if not cli_path: command = "copilot.cmd" if os.name == "nt" else "copilot" cli_path = shutil.which(command) connection = RuntimeConnection.for_stdio(path=cli_path) if cli_path else None return CopilotClient(connection=connection, use_logged_in_user=True) class _CopilotUsageCollector: """Collect the SDK's per-model-call telemetry for one Copilot session.""" def __init__(self, endpoint: str, configured_model: str): self.endpoint = endpoint self.configured_model = configured_model self.prompts_submitted = 0 self.agent_turns = 0 self._usage_by_model: dict[str, dict] = {} self._checkpoint_nano_aiu: float | None = None self._telemetry_available = False def record_prompt(self) -> None: self.prompts_submitted += 1 def handle_event(self, event) -> None: """Handle current SDK events by shape to tolerate SDK enum/type evolution.""" event_type = getattr(event, "type", "") event_kind = getattr(event_type, "value", event_type) data = getattr(event, "data", None) if event_kind == "assistant.usage" and data is not None: self._record_assistant_usage(data) elif event_kind == "assistant.turn_end": self.agent_turns += 1 elif event_kind == "session.usage_checkpoint" and data is not None: value = getattr(data, "total_nano_aiu", None) if value is not None: self._checkpoint_nano_aiu = float(value) self._telemetry_available = True def _record_assistant_usage(self, data) -> None: model = getattr(data, "model", None) or self.configured_model bucket = self._usage_by_model.setdefault( model, { "prompt_tokens": 0, "completion_tokens": 0, "cache_read_tokens": 0, "cache_write_tokens": 0, "reasoning_tokens": 0, "api_calls": 0, "copilot_nano_aiu": 0.0, }, ) bucket["prompt_tokens"] += getattr(data, "input_tokens", 0) or 0 bucket["completion_tokens"] += getattr(data, "output_tokens", 0) or 0 bucket["cache_read_tokens"] += getattr(data, "cache_read_tokens", 0) or 0 bucket["cache_write_tokens"] += getattr(data, "cache_write_tokens", 0) or 0 bucket["reasoning_tokens"] += getattr(data, "reasoning_tokens", 0) or 0 bucket["api_calls"] += 1 copilot_usage = getattr(data, "copilot_usage", None) bucket["copilot_nano_aiu"] += getattr(copilot_usage, "total_nano_aiu", 0.0) or 0.0 self._telemetry_available = True def to_backend_usage(self) -> BackendUsage: event_nano_aiu = sum(bucket["copilot_nano_aiu"] for bucket in self._usage_by_model.values()) checkpoint_nano_aiu = self._checkpoint_nano_aiu or 0.0 checkpoint_remainder = max(checkpoint_nano_aiu - event_nano_aiu, 0.0) if checkpoint_remainder and not self._usage_by_model: self._usage_by_model[self.configured_model] = { "prompt_tokens": 0, "completion_tokens": 0, "cache_read_tokens": 0, "cache_write_tokens": 0, "reasoning_tokens": 0, "api_calls": 0, "copilot_nano_aiu": checkpoint_remainder, } checkpoint_remainder = 0.0 model_usages = tuple( ModelUsage( model=model, endpoint=self.endpoint, prompt_tokens=bucket["prompt_tokens"], completion_tokens=bucket["completion_tokens"], total_tokens=bucket["prompt_tokens"] + bucket["completion_tokens"], cache_read_tokens=bucket["cache_read_tokens"], cache_write_tokens=bucket["cache_write_tokens"], reasoning_tokens=bucket["reasoning_tokens"], api_calls=bucket["api_calls"], agent_turns=self.agent_turns if model == self.configured_model else 0, copilot_nano_aiu=( bucket["copilot_nano_aiu"] + checkpoint_remainder if model == self.configured_model else bucket["copilot_nano_aiu"] ), telemetry_available=True, ) for model, bucket in self._usage_by_model.items() ) prompt_tokens = sum(item.prompt_tokens for item in model_usages) completion_tokens = sum(item.completion_tokens for item in model_usages) cache_read_tokens = sum(item.cache_read_tokens for item in model_usages) cache_write_tokens = sum(item.cache_write_tokens for item in model_usages) reasoning_tokens = sum(item.reasoning_tokens for item in model_usages) api_calls = sum(item.api_calls for item in model_usages) # A checkpoint is a session total, while assistant.usage is per-call. It # may include a final call whose detailed event was not delivered. copilot_nano_aiu = max(event_nano_aiu, checkpoint_nano_aiu) return BackendUsage( prompt_tokens=prompt_tokens, completion_tokens=completion_tokens, total_tokens=prompt_tokens + completion_tokens, cache_read_tokens=cache_read_tokens, cache_write_tokens=cache_write_tokens, reasoning_tokens=reasoning_tokens, api_calls=api_calls, agent_turns=self.agent_turns, copilot_prompts_submitted=self.prompts_submitted, copilot_nano_aiu=copilot_nano_aiu, telemetry_available=self._telemetry_available, model_usages=model_usages, ) def _subscribe_to_usage(session, collector: _CopilotUsageCollector): """Subscribe when the installed SDK exposes session events; otherwise degrade visibly.""" subscribe = getattr(session, "on", None) return subscribe(collector.handle_event) if callable(subscribe) else None class CopilotReasoner(ReasonerBackend): """GitHub Copilot SDK adapter for non-mutating reasoning calls.""" def __init__(self, config: Config, role: str): self.config = config self.role = role def complete( self, *, system_prompt: str, user_prompt: str, temperature: float = 0.0, ) -> BackendResponse: del temperature # Copilot SDK does not expose a temperature parameter. return asyncio.run(self._complete_async(system_prompt, user_prompt)) async def _complete_async(self, system_prompt: str, user_prompt: str) -> BackendResponse: from copilot.session import PermissionHandler route = self.config.route_for(self.role) endpoint = self.config.endpoint_for(self.role) client = _create_client() await client.start() try: session_config = { "model": route.model, "on_permission_request": PermissionHandler.approve_all, "available_tools": [], "working_directory": str(self.config.projects_dir), "infinite_sessions": {"enabled": False}, "system_message": {"mode": "append", "content": system_prompt}, } if route.reasoning_effort: session_config["reasoning_effort"] = route.reasoning_effort session = await client.create_session(**session_config) collector = _CopilotUsageCollector(endpoint.name, route.model) unsubscribe = _subscribe_to_usage(session, collector) try: collector.record_prompt() response = await _send_and_wait(session, user_prompt, route.timeout) content = getattr(getattr(response, "data", None), "content", "") or "" return BackendResponse( content=content, model=route.model, endpoint=endpoint.name, usage=collector.to_backend_usage(), ) finally: if unsubscribe: unsubscribe() await _disconnect_session(session) finally: await _stop_client(client) class CopilotCoder(CoderBackend): """GitHub Copilot SDK adapter using AFK's existing project tool functions.""" def __init__(self, config: Config, role: str): self.config = config self.role = role def execute_task( self, *, task: TaskNode, project_dir: str, context: str, hitl_mode: bool, max_turns: int, project_name: str = "", ) -> TaskExecutionResult: return asyncio.run( self._execute_async(task, project_dir, context, hitl_mode, max_turns, project_name) ) async def _execute_async( self, task: TaskNode, project_dir: str, context: str, hitl_mode: bool, max_turns: int, project_name: str = "", ) -> TaskExecutionResult: from copilot.session import PermissionHandler from copilot.tools import Tool, ToolResult route = self.config.route_for(self.role) endpoint = self.config.endpoint_for(self.role) collector = _CopilotUsageCollector(endpoint.name, route.model) files_changed: list[str] = [] complete: dict[str, str] = {} blocked: dict[str, str] = {} verification_failure: tuple[str, TaskFailureKind] | None = None command_policy_rejection = "" completion_rejection = "" governor_failure = "" tool_name_counts: Counter = Counter() verification_events = [] verification_artifact_dir = None if project_name and task.attempts: task_key = hashlib.sha256(task.id.encode("utf-8", errors="replace")).hexdigest()[:16] verification_artifact_dir = ( self.config.resolve_project_dir(project_name) / "diagnostics" / task_key / task.attempts[-1].id / "verification" ) discovery_progress_governor = DiscoveryProgressGovernor( turn_limit=self.config.discovery_progress_turn_limit, tool_limit=self.config.discovery_progress_tool_limit, read_only=task.read_only, ) discovery_progress_governor.begin_turn(0) checkpoint_read_budget = CheckpointReadBudget( task.discovery_contract.input_paths if task.discovery_checkpoint_fingerprint else None ) project_root = str(Path(project_dir).resolve()) evidence_roots = [ str(Path(path).resolve()) for path in task.evidence_roots if Path(path).is_dir() ] def result(text: str, result_type: str = "success") -> ToolResult: return ToolResult(text_result_for_llm=text, result_type=result_type) def parse(invocation) -> dict: arguments = invocation.arguments if isinstance(arguments, str): return json.loads(arguments) return arguments or {} def execute(name: str, invocation) -> dict: nonlocal \ command_policy_rejection, \ completion_rejection, \ governor_failure, \ verification_failure try: args = parse(invocation) tool_name_counts[name] += 1 if hitl_mode and name in { "write_file", "edit_file", "normalize_line_endings", "run_command", }: return result( "HITL mode is not yet supported by the Copilot SDK adapter. " "Retry with --hitl disabled or use an OpenAI-compatible endpoint.", "rejected", ) governor_decision = discovery_progress_governor.decision_for(name) if governor_decision.rejection: emit( "warning", " [yellow]Pre-write tool rejected[/yellow] -- write or block is required.", task_id=task.id, code="DISCOVERY_PROGRESS_REJECTED", tool=name, completed_turns=discovery_progress_governor.completed_turns, exploratory_calls=discovery_progress_governor.exploratory_calls, failed_lookups=discovery_progress_governor.failed_lookups, terminal=governor_decision.terminal, ) if governor_decision.terminal: governor_failure = discovery_progress_governor.failure_summary() return result(governor_decision.rejection, "rejected") # run_verification is deliberately NOT delegated to the shared # dispatch_tool_call: this loop needs the structured # VerificationOutcome (outcome.code) to decide whether to record # a verification_failure for the second-chance retry flow below, # not just the rendered text worker.py's simpler contract needs. if name == "run_verification": outcome = run_verification_request( args, project_root, max_timeout_seconds=self.config.max_shell_timeout, projects_dir=self.config.projects_dir, python_executable=self.config.target_python, default_project_name=project_name, ) verification_events.append( verification_attempt_event( args, outcome, artifact_dir=verification_artifact_dir, event_index=len(verification_events) + 1, ) ) output = outcome.to_tool_text() if outcome.code in { VerificationOutcomeCode.POLICY_REJECTED, VerificationOutcomeCode.TOOL_FAILED, }: verification_failure = ( output, ( TaskFailureKind.VERIFICATION_POLICY_REJECTED if outcome.code is VerificationOutcomeCode.POLICY_REJECTED else TaskFailureKind.VERIFICATION_TOOL_FAILED ), ) discovery_progress_governor.record_result(name, output) return result(output, "rejected") discovery_progress_governor.record_result(name, output) return result(output) if name == "task_complete": if not task.read_only and not files_changed: output = "REJECTED: Create or edit at least one file before task_complete." completion_rejection = output discovery_progress_governor.record_result(name, output) return result( output, "rejected", ) completion_rejection = "" complete.update(args) return result("Task marked complete.") if name == "task_blocked": blocked.update(args) return result("Task marked blocked pending the requested evidence.") read_rejection = checkpoint_read_budget.reject_reason(name, args) if read_rejection: discovery_progress_governor.record_result(name, read_rejection) return result(read_rejection, "rejected") output = dispatch_tool_call( name, args, project_dir=project_root, evidence_roots=evidence_roots, config=self.config, disallow_unscoped_pytest=task.disallow_unscoped_pytest, allowed_output_paths=( list(task.discovery_contract.allowed_output_paths) if task.discovery_contract is not None else None ), ) if output.startswith("TASK_COMMAND_POLICY_REJECTED:"): command_policy_rejection = output discovery_progress_governor.record_result(name, output) return result(output, "rejected") discovery_progress_governor.record_result(name, output) if name in { "write_file", "edit_file", "normalize_line_endings", } and discovery_progress_governor.result_succeeded(output): files_changed.append(args["path"]) return result(output) except Exception: return result(f"Tool error: {traceback.format_exc()}", "failure") # Canonical tool schemas now live in scheduler/tools/schemas.py # (shared with scheduler/worker.py's agent loop -- see # docs/refactor-handoffs/02-dedup.md Task 2). build_tool_schemas() # applies the exact same read_only/evidence_roots filter this loop # already had. definitions = build_tool_schemas( read_only=task.read_only, has_evidence_roots=bool(evidence_roots), allow_baseline_compare=self.config.lint_mode is LintMode.BASELINE, ) tools = [ Tool( name=name, description=description, handler=lambda invocation, name=name: execute(name, invocation), parameters=tool_parameters(name, properties, required), ) for name, description, properties, required in definitions ] tool_names = [tool.name for tool in tools] system_prompt = ( "You are an expert software engineer completing one task in a project. " "Explore relevant files before changing them. Work incrementally. Verify changes with tests, " "linting, or a relevant command, then call task_complete. A final text response does not " "complete a task. If required evidence is unavailable, call task_blocked with the precise " "missing evidence rather than making an unsupported assumption. Treat successful tool results as " "authoritative: never report a file, marker, or evidence section absent after its tool returned it. " "For any Git verification kind, omit paths and extra_safe_args; AFK supplies the fixed " "read-only command. " "Never write outside the project root." ) if task.evidence_packet_id: system_prompt += ( " An immutable evidence packet is already attached to this task. Any task wording about " "submitting evidence is a completed prerequisite, not a current instruction: do not re-run " "research, do not call task_blocked because an evidence-proposal tool is unavailable, and " "implement against the attached evidence summary." ) if evidence_roots: system_prompt += ( "\n\n--- Approved Read-Only Evidence Roots ---\n" + "\n".join(f"- {path}" for path in evidence_roots) + "\nUse read_evidence_file, read_evidence_metadata, read_evidence_section, or search_evidence_text; these roots are read-only. " "Evidence paths are relative to an approved root. For a large or one-line corpus XML, use " "read_evidence_section with a literal start marker, literal end marker (often ), " "and zero-based occurrence to read the bounded instance. Do not treat an oversized search " "result as evidence that the named source is unavailable." ) if context: system_prompt = f"{system_prompt}\n\n--- Project Memory ---\n{context}" task_prompt = f"TASK: {task.title}\n{task.description}" if task.evidence_packet_id: task_prompt += ( "\n\nEvidence gate already passed: an immutable, source-validated evidence packet is " "attached to this task and summarized in the provided project memory. Do not re-run evidence " "research or attempt to submit an evidence proposal. Implement or repair only against that " "attached contract; a missing submit_evidence_proposal tool is not a task blocker." ) if task.read_only: task_prompt += ( "\n\nRead-only analysis: inspect the project and approved evidence without modifications. " "Treat policy or manifest references already supplied in this trusted task contract " "as governing context, not as project files; require a target-local copy only when " "the task explicitly identifies that copy as an artifact to verify. " "Use run_verification for typed Git, pytest, Ruff, format-check, or project-file SHA-256 validation. " "baseline_compare is only a saved Ruff lint-baseline comparison in baseline lint mode; " "it never validates Git revisions, environments, or file integrity. " "Call task_complete only after the requested evidence is verified." ) client = None session = None unsubscribe = None try: client = _create_client() await client.start() config = { "model": route.model, "on_permission_request": PermissionHandler.approve_all, "tools": tools, "available_tools": tool_names, "working_directory": project_root, "infinite_sessions": {"enabled": False}, "system_message": {"mode": "append", "content": system_prompt}, } if route.reasoning_effort: config["reasoning_effort"] = route.reasoning_effort session = await client.create_session(**config) subscribe = getattr(session, "on", None) if callable(subscribe): def handle_coder_event(event) -> None: collector.handle_event(event) event_type = getattr(event, "type", "") event_kind = getattr(event_type, "value", event_type) if event_kind == "assistant.turn_end": discovery_progress_governor.begin_turn(collector.agent_turns) unsubscribe = subscribe(handle_coder_event) try: collector.record_prompt() response = await _send_and_wait(session, task_prompt, route.timeout) final_content = getattr(getattr(response, "data", None), "content", "") or "" progress_followups = 0 while ( discovery_progress_governor.active and not discovery_progress_governor.has_written and not complete and not blocked and not governor_failure and progress_followups < 2 ): progress_nudge = discovery_progress_governor.take_nudge() if progress_nudge: emit( "warning", " [yellow]Discovery budget reached[/yellow] -- worker must write or block.", task_id=task.id, code="DISCOVERY_PROGRESS_ACTIVATED", activation_reason=discovery_progress_governor.activation_reason, completed_turns=discovery_progress_governor.completed_turns, exploratory_calls=discovery_progress_governor.exploratory_calls, failed_lookups=discovery_progress_governor.failed_lookups, ) elif discovery_progress_governor.has_rejected: progress_nudge = ( "Your previous pre-write tool call was rejected by AFK's discovery " "progress policy. Do not explore again. Write or edit the bounded " "requested artifact now, or call task_blocked with one precise missing " "fact that prevents writing." ) else: break discovery_progress_governor.begin_turn( discovery_progress_governor.completed_turns + 1 ) collector.record_prompt() completion_response = await _send_and_wait( session, progress_nudge, route.timeout, ) progress_followups += 1 final_content = ( getattr(getattr(completion_response, "data", None), "content", "") or "" ) if ( verification_failure and verification_failure[1] is TaskFailureKind.VERIFICATION_POLICY_REJECTED and not complete ): collector.record_prompt() completion_response = await _send_and_wait( session, "A verification request was rejected by AFK policy and was not executed. Do not retry " "it, run verification, read more sources, or modify files. Based only on facts already " "retrieved, call task_complete if the task is complete; otherwise call task_blocked. " "Do not provide a final-text answer.", route.timeout, ) final_content = ( getattr(getattr(completion_response, "data", None), "content", "") or "" ) finally: if unsubscribe: unsubscribe() unsubscribe = None await _disconnect_session(session) session = None except TimeoutError: return TaskExecutionResult( TaskStatus.ESCALATED, f"Copilot timed out after {route.timeout}s", files_changed, failure_kind=TaskFailureKind.PROVIDER_TIMEOUT, tool_name_counts=dict(tool_name_counts), verification_events=list(verification_events), ) except Exception as exc: return TaskExecutionResult( TaskStatus.ESCALATED, f"Copilot error: {exc}", files_changed, failure_kind=TaskFailureKind.PROVIDER_UNAVAILABLE, tool_name_counts=dict(tool_name_counts), verification_events=list(verification_events), ) finally: if unsubscribe: unsubscribe() if session is not None: await _disconnect_session(session) self.config.record_usage(collector.to_backend_usage(), role=self.role) if client is not None: await _stop_client(client) if governor_failure: return TaskExecutionResult( TaskStatus.FAILED, governor_failure, files_changed, failure_kind=TaskFailureKind.DISCOVERY_PROGRESS_STALLED, tool_name_counts=dict(tool_name_counts), verification_events=list(verification_events), ) if blocked: return TaskExecutionResult( TaskStatus.ESCALATED, "RESEARCH_INSUFFICIENT: " f"{blocked.get('reason', 'Required research evidence is unavailable.')} " f"Missing evidence: {blocked.get('missing_evidence', 'not specified.')}", files_changed, failure_kind=TaskFailureKind.RESEARCH_INSUFFICIENT, tool_name_counts=dict(tool_name_counts), verification_events=list(verification_events), ) if command_policy_rejection: return TaskExecutionResult( TaskStatus.FAILED, command_policy_rejection, files_changed, failure_kind=TaskFailureKind.COMMAND_POLICY_REJECTED, tool_name_counts=dict(tool_name_counts), verification_events=list(verification_events), ) if completion_rejection: return TaskExecutionResult( TaskStatus.FAILED, completion_rejection, files_changed, failure_kind=TaskFailureKind.WORKER_FAILED, tool_name_counts=dict(tool_name_counts), verification_events=list(verification_events), ) if complete: declared = [path for path in complete.get("files_changed", []) if path] return TaskExecutionResult( TaskStatus.PASSED, complete.get("summary", final_content or "Task completed"), list(dict.fromkeys(files_changed + declared)), tool_name_counts=dict(tool_name_counts), verification_events=list(verification_events), ) if verification_failure: return TaskExecutionResult( TaskStatus.ESCALATED, verification_failure[0], files_changed, failure_kind=verification_failure[1], tool_name_counts=dict(tool_name_counts), verification_events=list(verification_events), ) if task.read_only: return TaskExecutionResult( TaskStatus.FAILED, "Read-only task ended without calling task_complete. " "Use task_blocked when required evidence is unavailable.", tool_name_counts=dict(tool_name_counts), verification_events=list(verification_events), ) return TaskExecutionResult( TaskStatus.FAILED, "Copilot ended without calling task_complete." + ( " Final response was non-empty; inspect the recorded provider session when diagnosing." if final_content.strip() else "" ), files_changed, tool_name_counts=dict(tool_name_counts), verification_events=list(verification_events), ) class CopilotResearcher(ResearcherBackend): """Copilot adapter that can only propose evidence through read-only AFK tools.""" def __init__(self, config: Config, role: str): self.config = config self.role = role def propose_evidence( self, *, task: TaskNode, project_dir: str, context: str, max_turns: int, project_name: str = "", ) -> ResearchProposalResult: return asyncio.run( self._propose_evidence_async(task, project_dir, context, max_turns, project_name) ) def propose_discovery( self, *, task: TaskNode, project_dir: str, contract: DiscoveryContract, context: str, max_turns: int, project_name: str = "", ) -> DiscoveryProposalResult: return asyncio.run( self._propose_discovery_async(task, project_dir, contract, context, max_turns) ) async def _propose_discovery_async( self, task: TaskNode, project_dir: str, contract: DiscoveryContract, context: str, max_turns: int, ) -> DiscoveryProposalResult: """Use Copilot's tool loop for one manifest-bounded local discovery pass.""" from copilot.session import PermissionHandler from copilot.tools import Tool, ToolResult route = self.config.route_for(self.role) endpoint = self.config.endpoint_for(self.role) collector = _CopilotUsageCollector(endpoint.name, route.model) project_root = str(Path(project_dir).resolve()) proposal: DiscoveryCheckpointDraft | None = None blocked: dict[str, str] = {} response_content = "" def result(text: str, result_type: str = "success") -> ToolResult: return ToolResult(text_result_for_llm=text, result_type=result_type) def parse(invocation) -> dict: arguments = invocation.arguments return json.loads(arguments) if isinstance(arguments, str) else (arguments or {}) def execute(name: str, invocation) -> ToolResult: nonlocal proposal try: args = parse(invocation) if name == "submit_discovery_proposal": if proposal is not None: return result( "REJECTED: A discovery proposal was already submitted.", "rejected" ) try: proposal = DiscoveryCheckpointDraft.model_validate(args) except ValueError as exc: return result(f"REJECTED: Invalid discovery proposal: {exc}", "rejected") return result( "Discovery proposal received. AFK will independently validate its paths, " "source hashes, and content-addressed fingerprint before persistence." ) if name == "task_blocked": blocked.update(args) return result("Discovery marked blocked pending the requested local evidence.") output = dispatch_tool_call( name, args, project_dir=project_root, evidence_roots=[], config=self.config, ) return result(output, "rejected" if output.startswith("Error:") else "success") except Exception: return result(f"Tool error: {traceback.format_exc()}", "failure") definitions = [ definition for definition in build_tool_schemas( read_only=True, has_evidence_roots=False, allow_baseline_compare=self.config.lint_mode is LintMode.BASELINE, ) if definition[0] not in {"task_complete", "task_blocked"} ] definitions.extend( [ ( "submit_discovery_proposal", "Submit exactly one structured local discovery proposal.", _DISCOVERY_DRAFT_TOOL_SCHEMA["properties"], _DISCOVERY_DRAFT_TOOL_SCHEMA["required"], ), ( "task_blocked", "State the precise missing local evidence instead of inventing a fact.", {"reason": {"type": "string"}, "missing_evidence": {"type": "string"}}, ["reason", "missing_evidence"], ), ] ) tools = [ Tool( name=name, description=description, handler=lambda invocation, name=name: execute(name, invocation), parameters=( _DISCOVERY_DRAFT_TOOL_SCHEMA if name == "submit_discovery_proposal" else tool_parameters(name, properties, required) ), ) for name, description, properties, required in definitions ] system_prompt = ( "You are AFK's read-only local discovery researcher. Inspect only the target project using " "the provided read-only tools. Never modify files, invoke a general shell, format, commit, " "merge, push, use network/database tools, or cite paths outside the declared input manifest. " "Answer only the declared questions. Submit exactly one complete structured proposal with " "submit_discovery_proposal. Every source_paths and canonical_paths value must name a declared " "manifest path: they are existing, hashed evidence only. Never list an allowed future output " "path in either field; refer to it only in approved_next_action or summary. If the provider does " "not invoke that tool, return only one JSON object conforming " "to this schema, without Markdown or commentary:\n" + json.dumps(_DISCOVERY_DRAFT_TOOL_SCHEMA, separators=(",", ":")) + "\nTrusted AFK runner code, not you, validates source hashes and persists the checkpoint." + "\n\n--- Discovery Contract ---\nQuestions:\n" + "\n".join(f"- {item}" for item in contract.questions) + "\nDeclared input manifest:\n" + "\n".join(f"- {item}" for item in contract.input_paths) + "\nAllowed outputs after discovery:\n" + "\n".join(f"- {item}" for item in contract.allowed_output_paths) + "\nExclusions:\n" + ("\n".join(f"- {item}" for item in contract.exclusions) or "- (none)") ) if context: system_prompt = f"{system_prompt}\n\n--- Bounded Task Context ---\n{context}" task_prompt = ( f"TASK: {task.title}\n{task.description}\n\nUse at most {max_turns} tool-guided turns. " "Submit the discovery proposal once the declared questions are answered." ) client = None session = None unsubscribe = None try: client = _create_client() await client.start() session_config = { "model": route.model, "on_permission_request": PermissionHandler.approve_all, "tools": tools, "available_tools": [tool.name for tool in tools], "working_directory": project_root, "infinite_sessions": {"enabled": False}, "system_message": {"mode": "append", "content": system_prompt}, } if route.reasoning_effort: session_config["reasoning_effort"] = route.reasoning_effort session = await client.create_session(**session_config) unsubscribe = _subscribe_to_usage(session, collector) try: collector.record_prompt() response = await _send_and_wait(session, task_prompt, route.timeout) response_content = _response_content(response) if proposal is None and not blocked: collector.record_prompt() repair_response = await _send_and_wait( session, "Discovery cannot complete without a structured terminal result. Your next and " "final action MUST be exactly one call to submit_discovery_proposal using only " "facts already retrieved, or exactly one call to task_blocked if that is impossible. " "Do not read more files. Do not return prose, Markdown, or JSON text; invoke the " "tool now.", route.timeout, ) repair_content = _response_content(repair_response) if repair_content.strip(): response_content = repair_content finally: if unsubscribe: unsubscribe() unsubscribe = None await _disconnect_session(session) session = None except TimeoutError: return DiscoveryProposalResult( status=TaskStatus.ESCALATED, summary=f"Copilot discovery researcher timed out after {route.timeout}s", failure_kind=TaskFailureKind.PROVIDER_TIMEOUT, usage=collector.to_backend_usage(), ) except Exception as exc: return DiscoveryProposalResult( status=TaskStatus.ESCALATED, summary=f"Copilot discovery researcher error: {exc}", failure_kind=TaskFailureKind.PROVIDER_UNAVAILABLE, usage=collector.to_backend_usage(), ) finally: if unsubscribe: unsubscribe() if session is not None: await _disconnect_session(session) usage = collector.to_backend_usage() self.config.record_usage(usage, role=self.role) if client is not None: await _stop_client(client) if blocked: return DiscoveryProposalResult( status=TaskStatus.ESCALATED, summary=( "RESEARCH_INSUFFICIENT: " f"{blocked.get('reason', 'Required local evidence is unavailable.')} " f"Missing evidence: {blocked.get('missing_evidence', 'not specified.')}" ), failure_kind=TaskFailureKind.RESEARCH_INSUFFICIENT, usage=usage, ) if proposal is None: proposal = _parse_discovery_draft_response(response_content) if proposal is None: detail = "Copilot researcher ended without submitting a discovery proposal." if response_content.strip(): detail += " Its final response was non-empty but not schema-valid discovery JSON." return DiscoveryProposalResult( status=TaskStatus.FAILED, summary=detail, usage=usage, raw_response=response_content[:5_000], ) return DiscoveryProposalResult( status=TaskStatus.PASSED, summary="Read-only discovery proposal submitted for trusted validation.", draft=proposal, usage=usage, ) async def _propose_evidence_async( self, task: TaskNode, project_dir: str, context: str, max_turns: int, project_name: str = "", ) -> ResearchProposalResult: from copilot.session import PermissionHandler from copilot.tools import Tool, ToolResult try: evidence_roots = normalize_evidence_roots( task.evidence_roots, project_dir=Path(project_dir), ) except EvidencePacketError as exc: return ResearchProposalResult( status=TaskStatus.ESCALATED, summary=f"RESEARCH_INSUFFICIENT: {exc}", failure_kind=TaskFailureKind.RESEARCH_INSUFFICIENT, ) route = self.config.route_for(self.role) endpoint = self.config.endpoint_for(self.role) collector = _CopilotUsageCollector(endpoint.name, route.model) project_root = str(Path(project_dir).resolve()) proposal: EvidencePacketDraft | None = None blocked: dict[str, str] = {} verification_failure: tuple[str, TaskFailureKind] | None = None verification_policy_rejection = "" response_content = "" verification_properties, verification_required = next( (properties, required) for name, _description, properties, required in build_tool_schemas( read_only=True, has_evidence_roots=bool(evidence_roots), allow_baseline_compare=self.config.lint_mode is LintMode.BASELINE, ) if name == "run_verification" ) def result(text: str, result_type: str = "success") -> ToolResult: return ToolResult(text_result_for_llm=text, result_type=result_type) def parse(invocation) -> dict: arguments = invocation.arguments if isinstance(arguments, str): return json.loads(arguments) return arguments or {} def execute(name: str, invocation) -> ToolResult: nonlocal proposal, verification_failure, verification_policy_rejection try: args = parse(invocation) if name == "read_file": return result( read_file( args["path"], project_root, args.get("offset", 0), args.get("limit", 500), ) ) if name == "read_evidence_file": return result( read_evidence_file( args["path"], evidence_roots, args.get("offset", 0), args.get("limit", 500), ) ) if name == "read_evidence_section": return result( read_evidence_section( args["path"], args["start_text"], evidence_roots, args.get("end_text", ""), args.get("occurrence", 0), args.get("max_chars", 60_000), ) ) if name == "search_evidence_text": return result( search_evidence_text( args["text"], evidence_roots, args.get("suffix", ".xml"), args.get("max_results", 100), ) ) if name == "glob_files": return result(glob_files(args["pattern"], project_root)) if name == "run_verification": outcome = run_verification_request( args, project_root, max_timeout_seconds=self.config.max_shell_timeout, projects_dir=self.config.projects_dir, python_executable=self.config.target_python, default_project_name=project_name, ) output = outcome.to_tool_text() if outcome.code is VerificationOutcomeCode.POLICY_REJECTED: verification_policy_rejection = output return result(output, "rejected") if outcome.code is VerificationOutcomeCode.TOOL_FAILED: verification_failure = ( output, TaskFailureKind.VERIFICATION_TOOL_FAILED, ) return result(output, "rejected") return result(output) if name == "discover_project": return result(discover_project(project_root)) if name == "list_directory": return result(list_directory(args.get("path", ""), project_root)) if name == "grep_codebase": return result( grep_codebase(args["pattern"], project_root, args.get("include", "")) ) if name == "submit_evidence_proposal": if proposal is not None: return result( "REJECTED: An evidence proposal was already submitted.", "rejected" ) try: proposal = EvidencePacketDraft.model_validate(args) except Exception as exc: return result(f"REJECTED: Invalid evidence proposal: {exc}", "rejected") return result( "Evidence proposal received. AFK will independently validate sources, " "markers, hashes, excerpts, and fingerprint before it is persisted." ) if name == "task_blocked": blocked.update(args) return result("Research marked blocked pending the requested evidence.") return result(f"Unknown tool: {name}", "failure") except Exception: return result(f"Tool error: {traceback.format_exc()}", "failure") definitions = [ ( "read_file", "Read a target-project file with line numbers.", { "path": {"type": "string"}, "offset": {"type": "integer"}, "limit": {"type": "integer"}, }, ["path"], ), ( "read_evidence_file", "Read an approved external evidence file using a path relative to an approved root.", { "path": {"type": "string"}, "offset": {"type": "integer"}, "limit": {"type": "integer"}, }, ["path"], ), ( "read_evidence_section", "Read one bounded literal-marker-delimited section from approved external evidence.", { "path": {"type": "string"}, "start_text": {"type": "string"}, "end_text": {"type": "string"}, "occurrence": {"type": "integer"}, "max_chars": {"type": "integer"}, }, ["path", "start_text", "end_text"], ), ( "search_evidence_text", "Search approved external evidence for literal text and bounded per-file counts.", { "text": {"type": "string"}, "suffix": {"type": "string"}, "max_results": {"type": "integer"}, }, ["text"], ), ( "glob_files", "Find target-project files with a relative glob pattern.", {"pattern": {"type": "string"}}, ["pattern"], ), ( "run_verification", "Run one typed read-only verification request for Git, pytest, Ruff, or file hashing.", verification_properties, verification_required, ), ("discover_project", "Show the target project tree and key context files.", {}, []), ( "list_directory", "List a target-project directory using a relative path.", {"path": {"type": "string"}}, [], ), ( "grep_codebase", "Search target-project text using a regex.", {"pattern": {"type": "string"}, "include": {"type": "string"}}, ["pattern"], ), ( "submit_evidence_proposal", "Submit one structured evidence proposal. This does not write a packet or modify the project.", EVIDENCE_PACKET_DRAFT_TOOL_SCHEMA["properties"], EVIDENCE_PACKET_DRAFT_TOOL_SCHEMA["required"], ), ( "task_blocked", "State precisely which approved evidence is missing instead of inventing facts.", { "reason": {"type": "string"}, "missing_evidence": {"type": "string"}, }, ["reason", "missing_evidence"], ), ] tools = [ Tool( name=name, description=description, handler=lambda invocation, name=name: execute(name, invocation), parameters=( tool_parameters(name, properties, required) if name == "run_verification" else ( EVIDENCE_PACKET_DRAFT_TOOL_SCHEMA if name == "submit_evidence_proposal" else {"type": "object", "properties": properties, "required": required} ) ), ) for name, description, properties, required in definitions ] system_prompt = ( "You are AFK's read-only evidence researcher. You may inspect only the target project, " "the explicitly approved evidence roots, and typed read-only verification output. You must " "not modify files, invoke a general shell, format, commit, merge, push, use network/database " "tools, or claim evidence you did not read. For any Git verification kind, omit paths and " "extra_safe_args; AFK supplies the fixed read-only command. Submit exactly one complete structured proposal with " "submit_evidence_proposal, citing literal markers and their zero-based occurrence. If the provider " "does not invoke that tool, do not report the task blocked because of that limitation: return only " "one JSON object conforming to this schema, without Markdown or commentary:\n" + json.dumps(EVIDENCE_PACKET_DRAFT_TOOL_SCHEMA, separators=(",", ":")) + "\nFor the first evidence packet, omit parent_revision. For a supplement, use exactly the " "current persisted evidence revision named in the bounded task context." + "\nTrusted AFK runner code, not you, writes and validates immutable packet artifacts." "\n\n--- Approved Read-Only Evidence Roots ---\n" + "\n".join(f"- {path}" for path in evidence_roots) ) if task.acceptance_profile.value == "corpus_raw_output": system_prompt += _raw_output_research_requirement() if context: system_prompt = f"{system_prompt}\n\n--- Bounded Task Context ---\n{context}" task_prompt = ( f"TASK: {task.title}\n{task.description}\n\n" f"Use at most {max_turns} tool-guided turns. Produce a proposal with supported forms, explicit " "exclusions, source-backed structural rules, and unanswered questions." ) client = None session = None unsubscribe = None try: client = _create_client() await client.start() session_config = { "model": route.model, "on_permission_request": PermissionHandler.approve_all, "tools": tools, "available_tools": [tool.name for tool in tools], "working_directory": project_root, "infinite_sessions": {"enabled": False}, "system_message": {"mode": "append", "content": system_prompt}, } if route.reasoning_effort: session_config["reasoning_effort"] = route.reasoning_effort session = await client.create_session(**session_config) unsubscribe = _subscribe_to_usage(session, collector) try: collector.record_prompt() response = await _send_and_wait(session, task_prompt, route.timeout) response_content = _response_content(response) if proposal is None and (response_content.strip() or verification_policy_rejection): collector.record_prompt() repair_response = await _send_and_wait( session, "Your last reply did not submit a proposal. A verification request may have been " "rejected by policy; do not retry it or use any more tools. " "Re-encode only the evidence already retrieved as one complete JSON object conforming " "to the EvidencePacketDraft schema in the system message. Do not say the task is " "blocked because a tool is unavailable. Return JSON only.", route.timeout, ) response_content = _response_content(repair_response) finally: if unsubscribe: unsubscribe() unsubscribe = None await _disconnect_session(session) session = None except TimeoutError: return ResearchProposalResult( status=TaskStatus.ESCALATED, summary=f"Copilot researcher timed out after {route.timeout}s", failure_kind=TaskFailureKind.PROVIDER_TIMEOUT, usage=collector.to_backend_usage(), ) except Exception as exc: return ResearchProposalResult( status=TaskStatus.ESCALATED, summary=f"Copilot researcher error: {exc}", failure_kind=TaskFailureKind.PROVIDER_UNAVAILABLE, usage=collector.to_backend_usage(), ) finally: if unsubscribe: unsubscribe() if session is not None: await _disconnect_session(session) usage = collector.to_backend_usage() self.config.record_usage(usage, role=self.role) if client is not None: await _stop_client(client) if verification_failure: return ResearchProposalResult( status=TaskStatus.ESCALATED, summary=verification_failure[0], failure_kind=verification_failure[1], usage=usage, ) if proposal is None and verification_policy_rejection: return ResearchProposalResult( status=TaskStatus.ESCALATED, summary=verification_policy_rejection, failure_kind=TaskFailureKind.VERIFICATION_POLICY_REJECTED, usage=usage, ) if blocked: return ResearchProposalResult( status=TaskStatus.ESCALATED, summary=( "RESEARCH_INSUFFICIENT: " f"{blocked.get('reason', 'Required research evidence is unavailable.')} " f"Missing evidence: {blocked.get('missing_evidence', 'not specified.')}" ), failure_kind=TaskFailureKind.RESEARCH_INSUFFICIENT, usage=usage, ) if proposal is None: proposal = _parse_evidence_draft_response(response_content) if proposal is None: detail = "Copilot researcher ended without submitting an evidence proposal." if response_content.strip(): detail += " Its final response was non-empty but not a schema-valid EvidencePacketDraft JSON object." return ResearchProposalResult( status=TaskStatus.FAILED, summary=detail, usage=usage, ) return ResearchProposalResult( status=TaskStatus.PASSED, summary="Read-only evidence proposal submitted for trusted validation.", draft=proposal, usage=usage, ) def _raw_output_research_requirement() -> str: """Return the extra packet contract required before raw-output implementation.""" return ( "\n\nThis task uses corpus_raw_output acceptance. Your proposal MUST include at least " "one raw_output_contracts entry. Each entry must name the project-relative fixture artifact " "the implementation will create (normally under tests/fixtures/) and the source_index for " "the exact bounded evidence excerpt it must equal byte-for-byte. Choose the fixture path " "explicitly; do not leave raw_output_contracts empty." ) class CopilotValidator(ValidatorBackend): """Read-only acceptance validator; it cannot modify project, Git, or AFK state.""" def __init__(self, config: Config, role: str): self.config = config self.role = role def validate( self, *, task: TaskNode, project_dir: str, context: str, max_turns: int, project_name: str = "", ) -> AcceptanceValidationResult: return asyncio.run( self._validate_async(task, project_dir, context, max_turns, project_name) ) async def _validate_async( self, task: TaskNode, project_dir: str, context: str, max_turns: int, project_name: str = "", ) -> AcceptanceValidationResult: from copilot.session import PermissionHandler from copilot.tools import Tool, ToolResult try: evidence_roots = normalize_evidence_roots( task.evidence_roots, project_dir=Path(project_dir), ) except EvidencePacketError as exc: return AcceptanceValidationResult( outcome=AcceptanceOutcome.BLOCKED_MISSING_EVIDENCE, summary="Acceptance validation cannot inspect the approved evidence roots.", research_question=str(exc), ) route = self.config.route_for(self.role) endpoint = self.config.endpoint_for(self.role) collector = _CopilotUsageCollector(endpoint.name, route.model) project_root = str(Path(project_dir).resolve()) submitted: dict = {} blocked: dict[str, str] = {} verification_failure = "" verification_policy_rejection = "" verification_properties, verification_required = next( (properties, required) for name, _description, properties, required in build_tool_schemas( read_only=True, has_evidence_roots=bool(evidence_roots), allow_baseline_compare=self.config.lint_mode is LintMode.BASELINE, ) if name == "run_verification" ) def result(text: str, result_type: str = "success") -> ToolResult: return ToolResult(text_result_for_llm=text, result_type=result_type) def parse(invocation) -> dict: arguments = invocation.arguments return json.loads(arguments) if isinstance(arguments, str) else (arguments or {}) def execute(name: str, invocation) -> ToolResult: nonlocal verification_failure, verification_policy_rejection try: args = parse(invocation) if name == "read_file": return result( read_file( args["path"], project_root, args.get("offset", 0), args.get("limit", 500), ) ) if name == "read_evidence_file": return result( read_evidence_file( args["path"], evidence_roots, args.get("offset", 0), args.get("limit", 500), ) ) if name == "glob_files": return result(glob_files(args["pattern"], project_root)) if name == "list_directory": return result(list_directory(args.get("path", ""), project_root)) if name == "grep_codebase": return result( grep_codebase(args["pattern"], project_root, args.get("include", "")) ) if name == "run_verification": outcome = run_verification_request( args, project_root, max_timeout_seconds=self.config.max_shell_timeout, projects_dir=self.config.projects_dir, python_executable=self.config.target_python, default_project_name=project_name, ) output = outcome.to_tool_text() if outcome.code is VerificationOutcomeCode.POLICY_REJECTED: verification_policy_rejection = output return result(output, "rejected") if outcome.code is VerificationOutcomeCode.TOOL_FAILED: verification_failure = output return result(output, "rejected") return result(output) if name == "submit_acceptance_result": if submitted: return result( "REJECTED: An acceptance result was already submitted.", "rejected" ) submitted.update(args) return result("Acceptance result received for trusted normalization.") if name == "task_blocked": blocked.update(args) return result("Validation marked blocked pending the requested evidence.") return result(f"Unknown tool: {name}", "failure") except Exception: return result(f"Tool error: {traceback.format_exc()}", "failure") definitions = [ ( "read_file", "Read a target-project file with line numbers.", { "path": {"type": "string"}, "offset": {"type": "integer"}, "limit": {"type": "integer"}, }, ["path"], ), ( "read_evidence_file", "Read an approved external evidence file using a path relative to its root.", { "path": {"type": "string"}, "offset": {"type": "integer"}, "limit": {"type": "integer"}, }, ["path"], ), ( "glob_files", "Find target-project files with a relative glob pattern.", {"pattern": {"type": "string"}}, ["pattern"], ), ( "list_directory", "List a target-project directory.", {"path": {"type": "string"}}, [], ), ( "grep_codebase", "Search target-project text using a regex.", {"pattern": {"type": "string"}, "include": {"type": "string"}}, ["pattern"], ), ( "run_verification", "Run one typed read-only verification request for Git, pytest, Ruff, or file hashing.", verification_properties, verification_required, ), ( "submit_acceptance_result", "Submit one PASS or FINDINGS result. Finding IDs are created by trusted runner code.", { "outcome": {"type": "string", "enum": ["PASS", "FINDINGS"]}, "summary": {"type": "string"}, "findings": { "type": "array", "items": { "type": "object", "additionalProperties": False, "properties": { "severity": {"type": "string"}, "summary": {"type": "string"}, "expected": {"type": "string"}, "actual": {"type": "string"}, "source_reference": {"type": "string"}, "affected_paths": {"type": "array", "items": {"type": "string"}}, "suggested_regression": {"type": "string"}, }, "required": ["summary"], }, }, }, ["outcome", "summary"], ), ( "task_blocked", "State precisely which evidence is missing instead of assuming unsupported behavior.", {"reason": {"type": "string"}, "missing_evidence": {"type": "string"}}, ["reason", "missing_evidence"], ), ] tools = [ Tool( name=name, description=description, handler=lambda invocation, name=name: execute(name, invocation), parameters=( tool_parameters(name, properties, required) if name == "run_verification" else {"type": "object", "properties": properties, "required": required} ), ) for name, description, properties, required in definitions ] system_prompt = ( "You are AFK's independent read-only acceptance validator. Inspect only the target project, " "the approved external evidence roots, and typed verifier results. Do not modify files, invoke " "a general shell, format, commit, merge, push, use network/database tools, or write AFK state. " "For any Git verification kind, omit paths and extra_safe_args; AFK supplies the fixed read-only " "command. Do not report a PASS unless you independently inspected the relevant output and contract. Submit " "exactly one structured result, or use task_blocked for genuinely missing evidence." " A trusted raw-output comparison supplied in the validation context is authoritative for its exact " "fixture-versus-evidence byte comparison; do not re-report that comparison as a finding when it passed. " "Assess remaining semantic or scope defects independently." "\n\n--- Approved Evidence Roots ---\n" + "\n".join(f"- {root}" for root in evidence_roots) ) if context: system_prompt = f"{system_prompt}\n\n--- Trusted Validation Context ---\n{context}" task_prompt = ( f"TASK: {task.title}\n{task.description}\n\nUse at most {max_turns} tool-guided turns. " "Inspect the task contract, changed output, and the evidence-backed scope before submitting a result." ) client = None session = None unsubscribe = None try: client = _create_client() await client.start() session_config = { "model": route.model, "on_permission_request": PermissionHandler.approve_all, "tools": tools, "available_tools": [tool.name for tool in tools], "working_directory": project_root, "infinite_sessions": {"enabled": False}, "system_message": {"mode": "append", "content": system_prompt}, } if route.reasoning_effort: session_config["reasoning_effort"] = route.reasoning_effort session = await client.create_session(**session_config) unsubscribe = _subscribe_to_usage(session, collector) try: collector.record_prompt() await _send_and_wait(session, task_prompt, route.timeout) finally: if unsubscribe: unsubscribe() unsubscribe = None await _disconnect_session(session) session = None except TimeoutError: return AcceptanceValidationResult( outcome=AcceptanceOutcome.VALIDATOR_ERROR, summary=f"Copilot validator timed out after {route.timeout}s.", usage=collector.to_backend_usage(), ) except Exception as exc: return AcceptanceValidationResult( outcome=AcceptanceOutcome.VALIDATOR_ERROR, summary=f"Copilot validator error: {exc}", usage=collector.to_backend_usage(), ) finally: if unsubscribe: unsubscribe() if session is not None: await _disconnect_session(session) usage = collector.to_backend_usage() self.config.record_usage(usage, role=self.role) if client is not None: await _stop_client(client) if verification_failure: return AcceptanceValidationResult( outcome=AcceptanceOutcome.VALIDATOR_ERROR, summary=verification_failure, usage=usage, ) if not submitted and verification_policy_rejection: return AcceptanceValidationResult( outcome=AcceptanceOutcome.VALIDATOR_ERROR, summary=verification_policy_rejection, usage=usage, ) if blocked: return AcceptanceValidationResult( outcome=AcceptanceOutcome.BLOCKED_MISSING_EVIDENCE, summary="Independent acceptance validation is blocked by missing evidence.", research_question=( f"{blocked.get('reason', 'Required evidence is unavailable.')} " f"{blocked.get('missing_evidence', '')}" ).strip(), usage=usage, ) if not submitted: return AcceptanceValidationResult( outcome=AcceptanceOutcome.VALIDATOR_ERROR, summary="Copilot validator ended without submitting an acceptance result.", usage=usage, ) return _normalize_validator_submission(submitted, project_root, usage) def _normalize_validator_submission( submitted: dict, project_root: str, usage: BackendUsage, ) -> AcceptanceValidationResult: try: outcome = AcceptanceOutcome(submitted.get("outcome", "")) except ValueError: return AcceptanceValidationResult( outcome=AcceptanceOutcome.VALIDATOR_ERROR, summary="Copilot validator submitted an unsupported outcome.", usage=usage, ) raw_findings = submitted.get("findings", []) if outcome is AcceptanceOutcome.PASS and raw_findings: return AcceptanceValidationResult( outcome=AcceptanceOutcome.VALIDATOR_ERROR, summary="Copilot validator submitted PASS together with findings.", usage=usage, ) if outcome is AcceptanceOutcome.FINDINGS and not raw_findings: return AcceptanceValidationResult( outcome=AcceptanceOutcome.VALIDATOR_ERROR, summary="Copilot validator submitted FINDINGS without a concrete finding.", usage=usage, ) findings: list[AcceptanceFinding] = [] root = Path(project_root).resolve() for raw in raw_findings: if not isinstance(raw, dict) or not raw.get("summary"): return AcceptanceValidationResult( outcome=AcceptanceOutcome.VALIDATOR_ERROR, summary="Copilot validator submitted a malformed finding.", usage=usage, ) paths: list[str] = [] for raw_path in raw.get("affected_paths", []): candidate = (root / str(raw_path)).resolve() if candidate.is_relative_to(root): paths.append(candidate.relative_to(root).as_posix()) normalized = { "severity": str(raw.get("severity", "error"))[:32], "summary": str(raw["summary"])[:500], "expected": str(raw.get("expected", ""))[:1000], "actual": str(raw.get("actual", ""))[:1000], "source_reference": str(raw.get("source_reference", ""))[:1000], "affected_paths": sorted(set(paths)), "suggested_regression": str(raw.get("suggested_regression", ""))[:1000], } stable_id = ( hashlib.sha256( json.dumps(normalized, sort_keys=True, ensure_ascii=True).encode("utf-8") ) .hexdigest()[:16] .upper() ) findings.append(AcceptanceFinding(id=f"AFK-MODEL-{stable_id}", **normalized)) return AcceptanceValidationResult( outcome=outcome, summary=str(submitted.get("summary", ""))[:2000] or "Validator completed.", findings=findings, usage=usage, )