"""Classify failed task attempts without relying on provider-specific exceptions.""" from __future__ import annotations from typing import TYPE_CHECKING from afk_developer.planner.task_model import TaskFailureKind, TaskStatus from afk_developer.recovery import RecoveryMode if TYPE_CHECKING: from afk_developer.scheduler.reviewer import ReviewResult _PROVIDER_UNAVAILABLE_MARKERS = ( "failed to fetch authenticated user", "fetch authenticated", "authenticated github user", "authentication failed", "not authenticated", "connection refused", "connection reset", "connection aborted", "network is unreachable", "network error", "name resolution", "dns", "service unavailable", "bad gateway", "gateway timeout", "rate limit", "too many requests", "http 429", "http 502", "http 503", "http 504", ) def classify_worker_failure(status: TaskStatus, summary: str) -> TaskFailureKind | None: """Return a durable category for a non-passing worker result. Provider failures must be explicit in the worker summary before they are treated as transient. This prevents model-reported coding errors from being misclassified as a reason to bypass normal implementation retries. """ if status == TaskStatus.PASSED: return None normalized = summary.lower() if normalized.startswith(("research insufficient:", "research_insufficient:")): return TaskFailureKind.RESEARCH_INSUFFICIENT if normalized.startswith("task_command_policy_rejected:"): return TaskFailureKind.COMMAND_POLICY_REJECTED if normalized.startswith("verification_policy_rejected:"): return TaskFailureKind.VERIFICATION_POLICY_REJECTED if normalized.startswith("verification_tool_failed:"): return TaskFailureKind.VERIFICATION_TOOL_FAILED if normalized.startswith("discovery_progress_stalled:"): return TaskFailureKind.DISCOVERY_PROGRESS_STALLED if status == TaskStatus.ESCALATED and "user aborted" in normalized: return TaskFailureKind.USER_ABORTED is_provider_error = normalized.startswith(("copilot error:", "api error on turn")) if "copilot timed out" in normalized or (is_provider_error and "timed out" in normalized): return TaskFailureKind.PROVIDER_TIMEOUT if is_provider_error and any(marker in normalized for marker in _PROVIDER_UNAVAILABLE_MARKERS): return TaskFailureKind.PROVIDER_UNAVAILABLE return TaskFailureKind.WORKER_FAILED def is_transient_provider_failure(kind: TaskFailureKind | None) -> bool: """Whether the user should restore provider access before retrying manually.""" return kind in { TaskFailureKind.PROVIDER_UNAVAILABLE, TaskFailureKind.PROVIDER_TIMEOUT, } def should_bypass_immediate_escalation( kind: TaskFailureKind | None, recovery_mode: RecoveryMode ) -> bool: """Whether a worker-reported ESCALATED status should flow through the normal retry/decompose path instead of hard-escalating immediately. Only ``VERIFICATION_POLICY_REJECTED``, and only when bounded recovery is active. Trying a disallowed verification option is often just a benign wrong guess (e.g. an unsupported pytest flag) rather than a fundamentally unrecoverable situation -- a plain retry can genuinely fix it, the same way an ordinary failed-test retry can. Every other ESCALATED reason (provider timeouts/unavailability, insufficient research evidence, etc.) still escalates immediately regardless of recovery mode -- those are not helped by blindly retrying the same request. """ return ( kind is TaskFailureKind.VERIFICATION_POLICY_REJECTED and recovery_mode is RecoveryMode.BOUNDED ) def worker_failure_should_escalate( status: TaskStatus, worker_failure: TaskFailureKind | None, recovery_mode: RecoveryMode ) -> bool: """Whether a worker's own result should hard-escalate the task immediately. A transient provider failure always escalates without counting as an implementation failure (see ``is_transient_provider_failure``) -- there is nothing to learn from retrying the exact same request against an outage. Otherwise, only escalates if the worker itself reported ``ESCALATED`` and that specific failure kind isn't one bounded recovery lets stay retriable instead (see ``should_bypass_immediate_escalation``). Shared by every site in ``queue.py`` that classifies a worker's outcome right after a call to ``execute_task`` (the initial attempt and the single in-process retry after a deterministic review failure) -- previously the same compound condition hand-duplicated at each site. """ if worker_failure is TaskFailureKind.COMMAND_POLICY_REJECTED: return True if is_transient_provider_failure(worker_failure): return True return status == TaskStatus.ESCALATED and not should_bypass_immediate_escalation( worker_failure, recovery_mode ) def classify_review_failure(review: ReviewResult) -> TaskFailureKind | None: """Return the most actionable failed deterministic review gate.""" if review.passed: return None if not getattr(review, "contract_passed", True): return TaskFailureKind.CONTRACT_FAILED if not review.tests_passed: return TaskFailureKind.TESTS_FAILED if not review.lint_passed: return TaskFailureKind.LINT_FAILED if not review.diff_passed: return TaskFailureKind.DIFF_CHECK_FAILED if not review.scope_passed: return TaskFailureKind.MUTATION_SCOPE_EXCEEDED if not review.required_artifacts_passed: return TaskFailureKind.REQUIRED_ARTIFACT_MISSING if not review.artifact_contract_passed: return TaskFailureKind.REQUIRED_ARTIFACT_MISSING return TaskFailureKind.REVIEW_REJECTED