"""Bounded recovery decisions for validator findings and missing evidence. This module owns policy only. Queue code persists a selected transition before starting another agent and owns the actual provider calls. """ from __future__ import annotations import hashlib from contextlib import contextmanager from dataclasses import dataclass, replace from itertools import pairwise from afk_developer.config import Config, RoleRoute from afk_developer.planner.task_model import ( AcceptanceProfile, TaskFailureKind, TaskLifecyclePhase, TaskNode, TaskStatus, ) from afk_developer.recovery import RecoveryAction, RecoveryMode, RecoverySettings @dataclass(frozen=True) class RecoveryDecision: """One safe next step, or a concrete reason why AFK must stop.""" action: RecoveryAction reason: str automatic: bool = False requires_override: bool = False @property def is_actionable(self) -> bool: return self.action is not RecoveryAction.NONE DECOMPOSABLE_FAILURE_KINDS = frozenset( { TaskFailureKind.WORKER_FAILED, TaskFailureKind.TESTS_FAILED, TaskFailureKind.LINT_FAILED, TaskFailureKind.DIFF_CHECK_FAILED, TaskFailureKind.REQUIRED_ARTIFACT_MISSING, TaskFailureKind.REVIEW_REJECTED, TaskFailureKind.CONTRACT_FAILED, } ) def decompose_fingerprint(task: TaskNode) -> str: """A stable fingerprint of the task's current failure, to dedup repeat foreman consults.""" data = f"{task.failure_kind.value if task.failure_kind else ''}|{task.failure_detail}".encode( "utf-8" ) return hashlib.sha256(data).hexdigest() def decompose_recovery_decision( task: TaskNode, settings: RecoverySettings, *, decompositions_used: int ) -> RecoveryDecision: """Return whether asking the foreman to split this stuck task is a permitted next step. Only a root-level (never-decomposed) task with a genuine capability failure -- never a provider failure or a policy/acceptance/mutation-guard rejection -- and an unspent plan-wide decomposition budget is eligible. A task carrying an acceptance profile is never decomposable: splitting it would break the human-owned evidence/acceptance-profile immutability invariant. Eligibility is checked against every failure kind seen across the task's whole attempt history (``task.attempts``), not just the most recent one. A task can genuinely be stuck on a capability failure (e.g. repeatedly failing tests or a worker context-window overflow) for several attempts, then happen to hit an unrelated one-off rejection (e.g. a verification policy rejection from trying a disallowed pytest flag) on the exact attempt that exhausts its retry budget -- checking only that last failure would incorrectly skip decomposition for a task that was clearly too complex for a single attempt, purely due to failure-order bad luck. """ if settings.mode is not RecoveryMode.BOUNDED: return RecoveryDecision(RecoveryAction.NONE, "Automatic recovery is disabled.") if task.acceptance_profile is not AcceptanceProfile.NONE: return RecoveryDecision(RecoveryAction.NONE, "Profiled tasks are never decomposable.") if task.decomposition_depth >= settings.max_decomposition_depth: return RecoveryDecision(RecoveryAction.NONE, "Decomposition depth limit reached.") if decompositions_used >= settings.max_decompositions: return RecoveryDecision( RecoveryAction.NONE, "No decomposition budget remains for this plan." ) observed_failure_kinds = { attempt.failure_kind for attempt in task.attempts if attempt.failure_kind is not None } if task.failure_kind is not None: observed_failure_kinds.add(task.failure_kind) if not observed_failure_kinds & DECOMPOSABLE_FAILURE_KINDS: return RecoveryDecision( RecoveryAction.NONE, "No attempt on this task hit a decomposable capability failure.", ) if decompose_fingerprint(task) in task.decomposition_fingerprints: return RecoveryDecision( RecoveryAction.NONE, "This exact failure was already offered to the foreman once.", ) return RecoveryDecision( RecoveryAction.DECOMPOSE, "Ask the foreman to split this stuck task into independent subtasks.", automatic=True, ) def automatic_recovery_decision(task: TaskNode, settings: RecoverySettings) -> RecoveryDecision: """Return the one permitted automatic follow-up for the current failure.""" if settings.mode is not RecoveryMode.BOUNDED: return RecoveryDecision( RecoveryAction.NONE, "Automatic recovery is disabled; use an explicit manual retry.", ) return _recovery_decision(task, automatic=True) def manual_recovery_decision(task: TaskNode, settings: RecoverySettings) -> RecoveryDecision: """Describe the route a human retry should use without spending any budget.""" if task.failure_kind is TaskFailureKind.VALIDATOR_FINDINGS or task.validator_findings: if not task.validator_finding_fingerprint: return RecoveryDecision( RecoveryAction.NONE, "Independent validation returned findings without a stable fingerprint.", ) exhausted = settings.mode is RecoveryMode.BOUNDED and ( task.semantic_repairs_remaining <= 0 or task.high_reasoning_repairs_remaining <= 0 or task.validator_finding_fingerprint in task.semantic_repair_fingerprints ) return RecoveryDecision( RecoveryAction.SEMANTIC_REPAIR, "Run a coder repair with high reasoning effort using the structured validator findings.", requires_override=exhausted, ) if task.failure_kind is TaskFailureKind.VALIDATOR_MISSING_EVIDENCE or ( task.acceptance_profile is not AcceptanceProfile.NONE and not task.evidence_packet_id ): if not task.evidence_roots: return RecoveryDecision( RecoveryAction.NONE, "No human-approved evidence roots are available for a research supplement.", ) exhausted = settings.mode is RecoveryMode.BOUNDED and ( task.research_supplements_remaining <= 0 ) return RecoveryDecision( RecoveryAction.RESEARCH_SUPPLEMENT, "Run a read-only researcher supplement against the approved evidence roots.", requires_override=exhausted, ) return RecoveryDecision(RecoveryAction.NONE, "The failure kind has no recovery route.") def schedule_recovery(task: TaskNode, decision: RecoveryDecision) -> None: """Persist a budgeted transition before the next external agent call.""" if not decision.automatic or not decision.is_actionable: raise ValueError("Only an actionable automatic recovery decision may be scheduled.") if decision.action is RecoveryAction.SEMANTIC_REPAIR: fingerprint = task.validator_finding_fingerprint if not fingerprint or fingerprint in task.semantic_repair_fingerprints: raise ValueError( "A repeated or missing validator fingerprint cannot be repaired automatically." ) if task.semantic_repairs_remaining <= 0: raise ValueError("No semantic repair budget remains.") task.semantic_repairs_remaining -= 1 task.semantic_repairs_used += 1 task.high_reasoning_repairs_remaining = max(task.high_reasoning_repairs_remaining - 1, 0) task.high_reasoning_repairs_used += 1 task.semantic_repair_fingerprints.append(fingerprint) task.recovery_action = RecoveryAction.SEMANTIC_REPAIR task.lifecycle_phase = TaskLifecyclePhase.REPAIRING elif decision.action is RecoveryAction.RESEARCH_SUPPLEMENT: if task.research_supplements_remaining <= 0: raise ValueError("No research supplement budget remains.") task.research_supplements_remaining -= 1 task.research_supplements_used += 1 task.recovery_action = RecoveryAction.RESEARCH_SUPPLEMENT task.lifecycle_phase = TaskLifecyclePhase.RESEARCHING else: raise ValueError(f"Unsupported recovery action: {decision.action.value}") task.status = TaskStatus.RETRYING def semantic_repair_route(config: Config) -> RoleRoute: """Raise only the repair attempt's reasoning effort; never select xhigh automatically.""" return replace(config.route_for("coder"), reasoning_effort="high") # Escalation ladder, cheapest first. ``None`` after the top means "human". MUTATING_ALTITUDES = ("coder_light", "coder", "reasoner") READ_ONLY_ALTITUDES = ("researcher", "reasoner") def default_altitude(task: TaskNode, config: Config | None = None) -> str: """The cheap model satisfies contracts by default; fall back to the coder if none is configured.""" if task.read_only: return "researcher" if config is not None and config.coder_light is not None: return "coder_light" return "coder" def current_altitude(task: TaskNode, config: Config | None = None) -> str: return task.altitude or default_altitude(task, config) def next_altitude(role: str, *, read_only: bool) -> str | None: """Return the role one step up the ladder, or None when only a human is above.""" ladder = READ_ONLY_ALTITUDES if read_only else MUTATING_ALTITUDES if role not in ladder: return ladder[-1] if role != ladder[-1] else None index = ladder.index(role) return ladder[index + 1] if index + 1 < len(ladder) else None def escalate_altitude(task: TaskNode, config: Config | None = None) -> str | None: """Move the task one altitude up. Returns the new role, or None if the ladder is exhausted.""" upward = next_altitude(current_altitude(task, config), read_only=task.read_only) if upward is not None: task.altitude = upward return upward def degenerate_altitude_rungs(config: Config) -> list[str]: """Adjacent rungs that resolve to the same route, so 'one altitude up' changes nothing. The ladder is by role on purpose (the envelope owner may legitimately run one model at two effort levels), but a step that changes neither model nor effort is a sideways retry wearing an upward label and must be visible as such. """ degenerate: list[str] = [] for ladder in (MUTATING_ALTITUDES, READ_ONLY_ALTITUDES): rungs = [ role for role in ladder if role not in {"coder_light", "researcher"} or getattr(config, role) is not None ] for lower, upper in pairwise(rungs): if config.route_for(lower) == config.route_for(upper): degenerate.append(f"{lower}->{upper}") return degenerate @contextmanager def use_coder_route(config: Config, route: RoleRoute | None): """Temporarily route one serial worker call without mutating saved configuration.""" if route is None: yield return original = config.coder config.coder = route try: yield finally: config.coder = original def repair_context(task: TaskNode) -> str: """Build bounded structured validation context without mutating task descriptions.""" lines = [ "Recovery mode: semantic repair after independent acceptance findings.", f"Evidence packet: {task.evidence_packet_id} revision={task.evidence_revision}.", "Resolve each finding below, then complete the normal deterministic and acceptance checks.", ] for finding in task.validator_findings[:20]: summary = str(finding.get("summary", ""))[:500] full_expected = str(finding.get("expected", "")) full_actual = str(finding.get("actual", "")) expected = full_expected[:1000] actual = full_actual[:1000] paths = ", ".join(str(path) for path in finding.get("affected_paths", [])[:20]) lines.append( "- " f"{summary}\n expected: {expected}\n actual: {actual}" + (f"\n affected paths: {paths}" if paths else "") ) if "\r\n" in full_actual and "\r\n" not in full_expected and "\n" in full_expected: lines.append( " Raw EOL repair: expected output uses LF but the actual artifact uses CRLF. " "Use normalize_line_endings with style='lf' on the affected raw-output fixture, " "then verify the exact contract." ) return "\n".join(lines) def _recovery_decision(task: TaskNode, *, automatic: bool) -> RecoveryDecision: if task.failure_kind is TaskFailureKind.VALIDATOR_FINDINGS: fingerprint = task.validator_finding_fingerprint if not fingerprint: return RecoveryDecision( RecoveryAction.NONE, "Independent validation returned findings without a stable fingerprint.", ) if fingerprint in task.semantic_repair_fingerprints: return RecoveryDecision( RecoveryAction.NONE, "The validator finding fingerprint is unchanged from an earlier semantic repair.", ) if task.semantic_repairs_remaining <= 0: return RecoveryDecision( RecoveryAction.NONE, "No semantic repair budget remains for this task.", ) if task.high_reasoning_repairs_remaining <= 0: return RecoveryDecision( RecoveryAction.NONE, "No high-reasoning repair budget remains for this task.", ) return RecoveryDecision( RecoveryAction.SEMANTIC_REPAIR, "Run one coder repair with high reasoning effort using the structured validator findings.", automatic=automatic, ) if task.failure_kind is TaskFailureKind.VALIDATOR_MISSING_EVIDENCE: if not task.evidence_roots: return RecoveryDecision( RecoveryAction.NONE, "No human-approved evidence roots are available for a research supplement.", ) if task.research_supplements_remaining <= 0: return RecoveryDecision( RecoveryAction.NONE, "No research supplement budget remains for this task.", ) return RecoveryDecision( RecoveryAction.RESEARCH_SUPPLEMENT, "Run one read-only researcher supplement against the approved evidence roots.", automatic=automatic, ) return RecoveryDecision( RecoveryAction.NONE, "The failure kind has no automatic recovery route." )