import hashlib import json import traceback from collections import Counter from dataclasses import replace from datetime import timedelta from pathlib import Path from typing import Any import click from openai import OpenAI from rich.console import Console from rich.panel import Panel from afk_developer.config import Config, EndpointType, LintMode from afk_developer.cortex.db import CortexDB from afk_developer.events import emit from afk_developer.planner.task_model import ( TaskFailureKind, TaskNode, TaskStatus, VerificationAttemptEvent, ) 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, to_openai_tool_definitions from afk_developer.scheduler.verification import ( VerificationOutcomeCode, run_verification_request, verification_attempt_event, ) from afk_developer.secrets import resolve_secret_ref console = Console() DESTRUCTIVE_TOOLS = {"write_file", "edit_file", "run_command"} SAFE_TOOLS = { "read_file", "read_evidence_file", "read_evidence_metadata", "read_evidence_section", "search_evidence_text", "glob_files", "discover_project", "list_directory", "grep_codebase", "task_complete", "task_blocked", "run_verification", } # Canonical tool schemas now live in scheduler/tools/schemas.py (shared with # backends/copilot.py's agent loop -- see docs/refactor-handoffs/02-dedup.md # Task 2). build_tool_schemas() applies the same read_only/evidence_roots # filtering both loops need; to_openai_tool_definitions() adapts the result # to this loop's OpenAI-compatible `tools=[...]` wire format. def _build_progress_summary( turn: int, max_turns: int, tool_name_counts: Counter, files_changed: list[str], ) -> str: """Build a compact, deterministic recap of a task attempt's progress so far. Used by `_compact_transcript` to replace turns older than `worker.summarization_window_turns` so a long unproductive research tangent (e.g. repeatedly introspecting a library's internals instead of writing code) can't grow the context window unbounded before the turn budget forces a failure. No LLM call is involved -- this is built purely from counters the caller already tracks turn by turn. """ lines = [ "--- Progress summary (earlier turns were compacted to save context) ---", f"You are on turn {turn + 1} of {max_turns}.", ] if tool_name_counts: counts = ", ".join(f"{name} x{count}" for name, count in tool_name_counts.most_common()) lines.append(f"Tool calls so far: {counts}") if files_changed: lines.append(f"Files changed so far: {', '.join(files_changed)}") else: lines.append( "No files have been written or edited yet. If you are still exploring/" "researching, stop and start implementing with what you already know instead " "of continuing to investigate further -- you do not need to fully understand " "every internal API detail before writing code." ) lines.append( "Continue the task using the above as your memory of what you've already done. " "Do not repeat exploration already summarized above." ) return "\n".join(lines) def _compact_transcript( messages: list[dict[str, Any]], turn_start_indices: list[int], keep_recent_turns: int, summary_content: str, max_context_chars: int = 0, ) -> tuple[list[dict[str, Any]], list[int]]: """Collapse turns older than the most recent `keep_recent_turns` into one summary message. `messages[0]` (the system prompt) and `messages[1]` (the initial task message) are always preserved untouched. `turn_start_indices[i]` must be the index into `messages` marking where turn `i`'s own messages begin -- callers append `len(messages)` to this list at the top of every turn, before that turn's messages are appended, so every recorded index always falls on a clean turn boundary (never mid tool-call/tool-result pairing). When `max_context_chars` is non-zero, compacts further whole turns as needed to stay within that serialized-message budget. Returns the input unchanged if there isn't yet more than `keep_recent_turns` turns recorded and the budget is not exceeded. """ kept_start = len(turn_start_indices) - 1 - keep_recent_turns context_chars = len(json.dumps(messages, ensure_ascii=False)) if kept_start < 1 and (not max_context_chars or context_chars <= max_context_chars): return messages, turn_start_indices kept_start = max(1, kept_start) while kept_start < len(turn_start_indices): cutoff = turn_start_indices[kept_start] if cutoff <= 2: return messages, turn_start_indices summary_message = {"role": "user", "content": summary_content} new_messages = messages[:2] + [summary_message] + messages[cutoff:] shift = (cutoff - 2) - 1 new_turn_start_indices = [idx - shift for idx in turn_start_indices[kept_start:]] if not max_context_chars or len(json.dumps(new_messages, ensure_ascii=False)) <= max_context_chars: return new_messages, new_turn_start_indices kept_start += 1 return messages, turn_start_indices class Worker: def __init__( self, config: Config, cortex: CortexDB, project_dir: Path, hitl_mode: bool = False, project_name: str = "", lint_mode: LintMode | None = None, ): self.config = replace(config, lint_mode=lint_mode or config.lint_mode) self.cortex = cortex self.project_dir = project_dir self.project_dir_str = str(project_dir) self.hitl_mode = hitl_mode self.project_name = project_name self._evidence_roots: list[str] = [] self._task_context = "" self._disallow_unscoped_pytest = False self._allowed_output_paths: list[str] | None = None self._checkpoint_read_budget = CheckpointReadBudget() self._discovery_progress_governor = DiscoveryProgressGovernor( turn_limit=0, tool_limit=0 ) self.last_failure_kind = None self.last_tool_name_counts: dict[str, int] = {} self.last_verification_events: list[VerificationAttemptEvent] = [] self._verification_artifact_dir: Path | None = None def set_task_context(self, context: str) -> None: """Set trusted, bounded context for the next worker attempt.""" self._task_context = context def execute_task( self, task: TaskNode, max_turns: int | None = None, recovery_context: str = "", ) -> tuple[TaskStatus, str, list[str]]: self.last_failure_kind = None self.last_tool_name_counts = {} self.last_verification_events = [] self._verification_artifact_dir = None if self.project_name and task.attempts: task_key = hashlib.sha256(task.id.encode("utf-8", errors="replace")).hexdigest()[:16] self._verification_artifact_dir = ( self.config.resolve_project_dir(self.project_name) / "diagnostics" / task_key / task.attempts[-1].id / "verification" ) self._evidence_roots = task.evidence_roots self._disallow_unscoped_pytest = task.disallow_unscoped_pytest self._allowed_output_paths = ( list(task.discovery_contract.allowed_output_paths) if task.discovery_contract is not None else None ) self._checkpoint_read_budget = CheckpointReadBudget( task.discovery_contract.input_paths if task.discovery_checkpoint_fingerprint else None ) self._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, ) if max_turns is None: max_turns = self.config.max_turns_for(task.estimated_effort) context = self._task_context self._task_context = "" if recovery_context: context = f"{context}\n\n--- Recovery Context ---\n{recovery_context}".strip() if self.config.endpoint_for("coder").type is EndpointType.COPILOT: from afk_developer.backends.registry import BackendRegistry result = ( BackendRegistry(self.config) .get_coder() .execute_task( task=task, project_dir=self.project_dir_str, context=context, hitl_mode=self.hitl_mode, max_turns=max_turns, project_name=self.project_name, ) ) self.last_failure_kind = result.failure_kind self.last_tool_name_counts = dict(result.tool_name_counts) self.last_verification_events = list(result.verification_events) return result.status, result.summary, result.files_changed route = self.config.route_for("coder") endpoint = self.config.endpoint_for("coder") api_key = ( resolve_secret_ref(endpoint.api_key_ref) if endpoint.api_key_ref else self.config.api_key ) if not api_key: return TaskStatus.FAILED, f"Endpoint '{endpoint.name}' requires an API key.", [] client = OpenAI(api_key=api_key, base_url=endpoint.base_url or self.config.base_url) system_prompt = self._build_system_prompt(task, context) messages: list[dict[str, Any]] = [ {"role": "system", "content": system_prompt}, ] if task.read_only: messages.append( { "role": "user", "content": f"TASK: {task.title}\n{task.description}\n\nThis is a read-only analysis. Explore the codebase and report your findings. Do NOT modify any files. Call task_complete only after verifying the requested evidence; call task_blocked with precise missing evidence otherwise.", } ) else: messages.append( { "role": "user", "content": f"TASK: {task.title}\n{task.description}\n\nStart by exploring the relevant files, then implement the changes. Run tests after making changes. Call task_complete when done.", } ) files_changed: list[str] = [] has_written_files = False turn_start_indices: list[int] = [] tool_name_counts: Counter = Counter() summarization_window = self.config.summarization_window_turns summarization_max_context_chars = self.config.summarization_max_context_chars tool_definitions = to_openai_tool_definitions( build_tool_schemas( read_only=task.read_only, has_evidence_roots=bool(self._evidence_roots), allow_baseline_compare=self.config.lint_mode is LintMode.BASELINE, ) ) for turn in range(max_turns): self._discovery_progress_governor.begin_turn(turn) self.cortex.write_fading( key=f"worker-turn-{task.id}", content=f"Turn {turn + 1}/{max_turns} for task '{task.title}'", ttl=timedelta(hours=2), ) if self.cortex.needs_reflection(self.config.reflection_interval): from afk_developer.cortex.reflector import run_reflection try: run_reflection(self.cortex, self.config) except Exception: pass turn_start_indices.append(len(messages)) if summarization_window > 0: summary_text = _build_progress_summary( turn, max_turns, tool_name_counts, files_changed ) messages, turn_start_indices = _compact_transcript( messages, turn_start_indices, summarization_window, summary_text, summarization_max_context_chars, ) progress_nudge = self._discovery_progress_governor.take_nudge() if progress_nudge: messages.append({"role": "user", "content": progress_nudge}) emit( "warning", " [yellow]Discovery budget reached[/yellow] -- worker must write or block.", task_id=task.id, code="DISCOVERY_PROGRESS_ACTIVATED", activation_reason=self._discovery_progress_governor.activation_reason, completed_turns=self._discovery_progress_governor.completed_turns, exploratory_calls=self._discovery_progress_governor.exploratory_calls, failed_lookups=self._discovery_progress_governor.failed_lookups, ) saved_msg_count = len(messages) try: response = client.chat.completions.create( model=route.model, messages=messages, tools=tool_definitions, temperature=0.0, ) except Exception as e: err_str = str(e).lower() if "tool" in err_str and "tool_calls" in err_str: messages = messages[:saved_msg_count] messages.append( { "role": "user", "content": "The previous exchange hit a message-ordering error. " "Please continue from the last valid state. Re-read files if needed, then implement.", } ) continue return TaskStatus.FAILED, f"API error on turn {turn + 1}: {e}", files_changed self.config.record_usage(response.usage, role="coder") self.config.stats.total_turns += 1 message = response.choices[0].message if not message.tool_calls: if message.content: messages.append({"role": "assistant", "content": message.content}) if turn >= max_turns - 1: return ( TaskStatus.FAILED, "Task did not complete within turn limit", files_changed, ) if task.read_only: return ( TaskStatus.FAILED, "Read-only task ended without calling task_complete. " "Use task_blocked when required evidence is unavailable.", files_changed, ) messages.append( { "role": "user", "content": "Please continue. Use tools to explore/implement and call task_complete when done.", } ) continue tool_calls_data = [] for tc in message.tool_calls: tool_calls_data.append( { "id": tc.id, "type": "function", "function": {"name": tc.function.name, "arguments": tc.function.arguments}, } ) assistant_msg: dict[str, Any] = { "role": "assistant", "content": message.content or "", "tool_calls": tool_calls_data, } messages.append(assistant_msg) for tc in message.tool_calls: approved, hitl_result = self._hitl_approve(tc.function.name, tc.function.arguments) governor_decision = self._discovery_progress_governor.decision_for( tc.function.name ) if not approved: tool_result = hitl_result if hitl_result == "HITL_ABORT": return TaskStatus.ESCALATED, "User aborted task", files_changed elif governor_decision.rejection: tool_result = 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=tc.function.name, completed_turns=self._discovery_progress_governor.completed_turns, exploratory_calls=self._discovery_progress_governor.exploratory_calls, failed_lookups=self._discovery_progress_governor.failed_lookups, terminal=governor_decision.terminal, ) elif ( tc.function.name == "task_complete" and not has_written_files and not task.read_only ): tool_result = ( "REJECTED: You called task_complete without creating or editing any files. " "Use write_file/edit_file to implement the changes first, then call task_complete." ) else: tool_result = self._execute_tool(tc.function.name, tc.function.arguments) if not governor_decision.rejection: self._discovery_progress_governor.record_result( tc.function.name, tool_result ) self._log_tool_action(tc.function.name, tc.function.arguments, tool_result) tool_name_counts[tc.function.name] += 1 self.last_tool_name_counts = dict(tool_name_counts) messages.append( { "role": "tool", "tool_call_id": tc.id, "content": tool_result, } ) if governor_decision.terminal: self.last_failure_kind = TaskFailureKind.DISCOVERY_PROGRESS_STALLED return ( TaskStatus.FAILED, self._discovery_progress_governor.failure_summary(), files_changed, ) if tc.function.name == "run_verification" and tool_result.startswith( ( f"{VerificationOutcomeCode.POLICY_REJECTED.value.upper()}:", f"{VerificationOutcomeCode.TOOL_FAILED.value.upper()}:", ) ): return TaskStatus.ESCALATED, tool_result, files_changed if tool_result.startswith("TASK_COMMAND_POLICY_REJECTED:"): self.last_failure_kind = TaskFailureKind.COMMAND_POLICY_REJECTED return TaskStatus.FAILED, tool_result, files_changed if tc.function.name == "task_complete": try: args = json.loads(tc.function.arguments) result_summary = args.get("summary", "") result_files = args.get("files_changed", []) except json.JSONDecodeError: result_summary = "Task completed" result_files = [] if not has_written_files and not task.read_only: continue for fp in result_files: if fp and fp not in files_changed: files_changed.append(fp) return TaskStatus.PASSED, result_summary, files_changed if tc.function.name == "task_blocked": try: args = json.loads(tc.function.arguments) except json.JSONDecodeError: args = {} reason = args.get("reason", "Required research evidence is unavailable.") missing = args.get("missing_evidence", "not specified") return ( TaskStatus.ESCALATED, f"RESEARCH_INSUFFICIENT: {reason} Missing evidence: {missing}", files_changed, ) if tc.function.name in ("write_file", "edit_file"): if not self._discovery_progress_governor.result_succeeded(tool_result): continue has_written_files = True try: args = json.loads(tc.function.arguments) fp = args.get("path", "") if fp and fp not in files_changed: files_changed.append(fp) except json.JSONDecodeError: pass return TaskStatus.FAILED, "Exceeded maximum turns without completion", files_changed def _build_system_prompt(self, task: TaskNode, context: str) -> str: parts = [ "You are an expert software engineer working on a coding task.", f"Project directory: {self.project_dir_str}", f"Language: {self._detect_language()}", ] if context: parts.append(f"\n--- Project Memory ---\n{context}") parts.append("\n--- Instructions ---") parts.append( "1. Explore the relevant files first using read_file, glob_files, or discover_project." ) if not task.read_only: parts.append( "2. Build incrementally: implement ONE function or module at a time and verify it before moving on." ) parts.append("3. Write the code using edit_file (preferred) or write_file.") parts.append( "4. IMMEDIATELY after writing code, verify it by running tests, linter, or the program itself with run_command." ) parts.append( "5. If a command fails, read the error output carefully. Diagnose and fix the issue before continuing." ) parts.append( "6. Call task_complete ONLY when all code is written AND verified (all tests/lint pass)." ) if task.disallow_unscoped_pytest: parts.append( "7. This task forbids a full pytest suite: use only direct shell commands such as " "`python -m pytest tests/test_contract.py -q`, naming one or more project-relative " "test files. Never wrap pytest in `python -c`, `pytest.main(...)`, a script, or a " "REPL; those forms are rejected. Do not run ad-hoc probes or diagnostic scripts unless " "the task explicitly permits them." ) else: parts.append("2. Read and explore the code to form a thorough analysis.") parts.append( "3. Use run_verification for typed validation, then call task_complete or task_blocked." ) parts.append( "4. Treat policy or manifest references already supplied in the 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." ) if task.evidence_roots: roots = "\n".join(f"- {root}" for root in task.evidence_roots) parts.append(f"\n--- Approved Read-Only Evidence Roots ---\n{roots}") parts.append("\n--- Rules ---") parts.append( "- Never write an entire application in one shot. Work function-by-function or file-by-file." ) parts.append( "- After every file write/edit, verify immediately with run_command before writing more code." ) parts.append( "- If stuck after 3 failed fix attempts on the same error, report what you tried and move on." ) parts.append( "- Treat successful tool results as authoritative; do not report evidence absent after a tool returned it." ) parts.append( "- Treat every required artifact and acceptance criterion in the Task Contract as binding; " "verify each one before calling task_complete." ) parts.append("- Always use exact indentation and whitespace in edit_file.") return "\n".join(parts) def _execute_tool(self, name: str, arguments: str) -> str: try: args = json.loads(arguments) except json.JSONDecodeError: return f"Error: Invalid JSON arguments: {arguments}" if name == "task_complete": return "Task marked complete." if name == "task_blocked": return "Task marked blocked pending the requested evidence." if name == "run_verification": outcome = run_verification_request( args, self.project_dir_str, max_timeout_seconds=self.config.max_shell_timeout, projects_dir=self.config.projects_dir, python_executable=self.config.target_python, default_project_name=self.project_name, ) self.last_verification_events.append( verification_attempt_event( args, outcome, artifact_dir=self._verification_artifact_dir, event_index=len(self.last_verification_events) + 1, ) ) return outcome.to_tool_text() read_rejection = self._checkpoint_read_budget.reject_reason(name, args) if read_rejection: return read_rejection try: return dispatch_tool_call( name, args, project_dir=self.project_dir_str, evidence_roots=self._evidence_roots, config=self.config, disallow_unscoped_pytest=self._disallow_unscoped_pytest, allowed_output_paths=self._allowed_output_paths, project_name=self.project_name, ) except Exception: return f"Tool error: {traceback.format_exc()}" def _hitl_approve(self, name: str, arguments: str) -> tuple[bool, str]: if not self.hitl_mode: return True, "" if name in SAFE_TOOLS: return True, "" try: args = json.loads(arguments) except json.JSONDecodeError: return True, "" if name == "write_file": path = args.get("path", "?") content = args.get("content", "") preview = content[:600] + ("..." if len(content) > 600 else "") console.print( Panel.fit( f"[bold yellow]write_file: {path}[/bold yellow]\n\n{preview}", title="HITL — Approve?", border_style="yellow", ) ) elif name == "edit_file": path = args.get("path", "?") old_s = args.get("old_string", "") new_s = args.get("new_string", "") console.print( Panel.fit( f"[bold yellow]edit_file: {path}[/bold yellow]\n\n" f"[red]- {old_s[:300]}{'...' if len(old_s) > 300 else ''}[/red]\n" f"[green]+ {new_s[:300]}{'...' if len(new_s) > 300 else ''}[/green]", title="HITL — Approve?", border_style="yellow", ) ) elif name == "run_command": cmd = args.get("command", "?") console.print( Panel.fit( f"[bold yellow]run_command[/bold yellow]\n\n[cyan]{cmd}[/cyan]", title="HITL — Approve?", border_style="yellow", ) ) else: return True, "" console.print( " [bold][A][/bold]pprove [bold][R][/bold]eject [bold][F][/bold]ull-auto (go AFK) [bold][Q][/bold]uit" ) choice = click.getchar().lower() console.print() if choice == "a": return True, "" elif choice == "r": return ( False, "REJECTED BY USER: The user chose not to allow this tool call. Try a different approach.", ) elif choice == "f": self.hitl_mode = False console.print("[dim]Switching to full-auto (AFK) mode.[/dim]") return True, "" elif choice == "q": return False, "HITL_ABORT" else: return True, "" def _detect_language(self) -> str: indicators = { "Python": ["pyproject.toml", "setup.py", "requirements.txt"], "JavaScript": ["package.json"], "TypeScript": ["tsconfig.json"], "Rust": ["Cargo.toml"], "Go": ["go.mod"], } for lang, files in indicators.items(): for f in files: if (self.project_dir / f).exists(): return lang return "unknown" def _log_tool_action(self, name: str, arguments: str, result: str) -> None: try: args = json.loads(arguments) except json.JSONDecodeError: args = {} is_error = result.startswith("Error:") or result.startswith("Tool error:") is_rejected = result.startswith("REJECTED:") prefix = ( "[red]FAIL[/red]" if is_error else "[yellow]WAIT[/yellow]" if is_rejected else " " ) if name == "read_file": path = args.get("path", "?") offset = args.get("offset", 0) limit = args.get("limit", 500) emit( "tool_action", f" {prefix} [dim]read_file {path} (L{offset}+{limit})[/dim]", tool=name, ) elif name == "write_file": path = args.get("path", "?") size = len(args.get("content", "")) emit("tool_action", f" {prefix} [dim]write_file {path} ({size}B)[/dim]", tool=name) elif name == "edit_file": path = args.get("path", "?") old_len = len(args.get("old_string", "")) new_len = len(args.get("new_string", "")) emit( "tool_action", f" {prefix} [dim]edit_file {path} ({old_len}->{new_len}B)[/dim]", tool=name, ) elif name == "run_command": cmd = args.get("command", "?") short_cmd = cmd[:100] + ("..." if len(cmd) > 100 else "") emit("tool_action", f" {prefix} [dim]run_command {short_cmd}[/dim]", tool=name) elif name == "discover_project": emit("tool_action", f" {prefix} [dim]discover_project[/dim]", tool=name) elif name == "list_directory": emit( "tool_action", f" {prefix} [dim]list_directory {args.get('path', '')}[/dim]", tool=name, ) elif name == "grep_codebase": pattern = args.get("pattern", "?") include = args.get("include", "") inc = f" ({include})" if include else "" emit("tool_action", f" {prefix} [dim]grep_codebase '{pattern}'{inc}[/dim]", tool=name) elif name == "glob_files": emit( "tool_action", f" {prefix} [dim]glob_files {args.get('pattern', '?')}[/dim]", tool=name, ) elif name == "task_complete": summary = args.get("summary", "") short = summary[:120] + ("..." if len(summary) > 120 else "") emit("tool_action", f" {prefix} [dim]task_complete --[/dim] {short}", tool=name) if is_error: short_err = result[:200] + ("..." if len(result) > 200 else "") emit("tool_action", f" [red]{short_err}[/red]", tool=name)