"""Manual single-task retry pipeline. Session 1 (docs/refactor-handoffs/01-file-splits.md) extracted this verbatim from the `afk retry` Click command in `cli.py`. Session 2 (docs/refactor-handoffs/02-dedup.md, Task 1) unified the actual dispatch: this module now keeps only the manual-only preamble (evidence-gate checks, the research-supplement recovery path -- both deliberately kept inline rather than delegated, see the comment above their code below -- and the bounded-recovery-budget override check), then delegates branch setup, worker execution, deterministic review, the acceptance gate, and finalize/merge to `scheduler/queue.py`'s `execute_plan(only_task_id=...)` pipeline -- the same one the automatic scheduler loop uses. Names resolved from cli.py's own module namespace (helpers + `console`) are accessed via `import afk_developer.cli as cli` + attribute access so existing test monkeypatches on `afk_developer.cli.X` keep working unchanged. """ from pathlib import Path import click from afk_developer.config import Config, LintMode from afk_developer.planner.task_model import ( AcceptanceProfile, TaskFailureKind, TaskLifecyclePhase, TaskStatus, ) from afk_developer.recovery import RecoveryAction from afk_developer.scheduler.attempts import ( finalize_interrupted_attempt, initialize_plan_recovery, ) from afk_developer.scheduler.lint_baseline import LintBaselineError from afk_developer.scheduler.recovery_coordinator import manual_recovery_decision def run_manual_retry( ctx: click.Context, project_name: str, task_id: str, hitl: bool, lint_mode: str | None, force_recovery: bool = False, validate_existing: bool = False, ): """Retry a single failed task without touching the others.""" import afk_developer.cli as cli config: Config = ctx.obj["config"] loaded = cli._load_plan(config, project_name) if loaded is None: cli.console.print(f"[red]No saved plan found for '{project_name}'.[/red]") return ( plan, saved_project_dir, saved_linter, saved_test_framework, saved_lint_mode, _saved_max_auto_resume_passes, ) = loaded # See the matching comment in `resume`: refresh the plan's snapshotted # recovery policy from the live config so a config.yml change takes effect # here too (this command also consults `plan.recovery` for manual repair # eligibility below). initialize_plan_recovery(plan, config.recovery) project_dir = Path(saved_project_dir) if saved_project_dir else Path.cwd() linter = saved_linter or "" test_framework = saved_test_framework or "" effective_lint_mode = LintMode(lint_mode or saved_lint_mode.value) task = next((t for t in plan.tasks if t.id == task_id), None) if task is None: cli.console.print( f"[red]Task '{task_id}' not found in plan. Tasks: {', '.join(t.id for t in plan.tasks)}[/red]" ) return from afk_developer.execution import ExecutionBoundaryError, prepare_execution_boundary try: prepare_execution_boundary(plan, config, project_dir) except ExecutionBoundaryError as exc: raise click.ClickException(str(exc)) from exc cortex = cli._init_cortex(config, project_name) from afk_developer.scheduler.queue import ( _clear_failure, _evidence_gate_decision, _is_evidence_gate_source, _run_research_supplement, execute_plan, ) cli.console.print(f"\n[bold]Retrying:[/bold] [cyan]{task.id}[/cyan] — {task.title}") if finalize_interrupted_attempt(task, config): cli._save_plan( config, plan, project_dir=project_dir, linter=linter, test_framework=test_framework, lint_mode=effective_lint_mode, max_auto_resume_passes=_saved_max_auto_resume_passes, ) cli.console.print(" [dim]Finalized the interrupted prior attempt for recovery.[/dim]") if _is_evidence_gate_source(task, plan) and not task.evidence_packet_id: task.recovery_action = RecoveryAction.RESEARCH_SUPPLEMENT task.failure_detail = ( "This read-only discovery task gates a later mutation and must attach " "one immutable, source-validated evidence packet." ) if not _run_research_supplement( task=task, plan=plan, config=config, project_dir=project_dir, save_callback=lambda: cli._save_plan( config, plan, project_dir=project_dir, linter=linter, test_framework=test_framework, lint_mode=effective_lint_mode, max_auto_resume_passes=_saved_max_auto_resume_passes, ), restore_automatic_budget=False, ): cli._save_retry_session(cortex, config, task) cli.console.print( "[yellow]Evidence discovery remains escalated; no normal worker was started.[/yellow]" ) return task.status = TaskStatus.PASSED task.lifecycle_phase = TaskLifecyclePhase.PASSED cli._save_plan( config, plan, project_dir=project_dir, linter=linter, test_framework=test_framework, lint_mode=effective_lint_mode, max_auto_resume_passes=_saved_max_auto_resume_passes, ) cli._save_retry_session(cortex, config, task) cli.console.print( " [green]Evidence discovery complete[/green] — immutable packet attached." ) return evidence_insufficient, evidence_gate_detail = _evidence_gate_decision(task, plan, config) if evidence_insufficient: task.status = TaskStatus.NOT_APPLICABLE task.lifecycle_phase = TaskLifecyclePhase.NOT_APPLICABLE task.not_applicable_reason = evidence_gate_detail _clear_failure(task) cli._save_plan( config, plan, project_dir=project_dir, linter=linter, test_framework=test_framework, lint_mode=effective_lint_mode, max_auto_resume_passes=_saved_max_auto_resume_passes, ) cli._save_retry_session(cortex, config, task) cli.console.print(f" [cyan]Not applicable[/cyan] — {evidence_gate_detail}") return if evidence_gate_detail: task.status = TaskStatus.ESCALATED task.lifecycle_phase = TaskLifecyclePhase.ESCALATED task.failure_kind = TaskFailureKind.VALIDATOR_MISSING_EVIDENCE task.failure_detail = evidence_gate_detail cli._save_plan( config, plan, project_dir=project_dir, linter=linter, test_framework=test_framework, lint_mode=effective_lint_mode, max_auto_resume_passes=_saved_max_auto_resume_passes, ) cli._save_retry_session(cortex, config, task) cli.console.print( f"[yellow]Evidence gate remains blocked[/yellow] — {evidence_gate_detail}" ) return recovery_decision = manual_recovery_decision(task, plan.recovery) if recovery_decision.is_actionable and not validate_existing: cli.console.print( " [dim]Recovery candidate:[/dim] " f"{recovery_decision.action.value.replace('_', ' ')} — {recovery_decision.reason}" ) if recovery_decision.requires_override and not force_recovery: cli.console.print( "[yellow]The bounded recovery budget is exhausted. Review the retained branch and " "use --force-recovery to explicitly override it.[/yellow]" ) return if task.acceptance_profile is not AcceptanceProfile.NONE and task.read_only: task.status = TaskStatus.ESCALATED task.lifecycle_phase = TaskLifecyclePhase.ESCALATED task.failure_kind = TaskFailureKind.ACCEPTANCE_POLICY_REJECTED task.failure_detail = ( "Required acceptance profiles only apply to branch-isolated mutating tasks." ) cli._save_plan( config, plan, project_dir=project_dir, linter=linter, test_framework=test_framework, lint_mode=effective_lint_mode, max_auto_resume_passes=_saved_max_auto_resume_passes, ) cli.console.print("[red]Cannot retry an acceptance-profile task as read-only.[/red]") return if recovery_decision.action is RecoveryAction.RESEARCH_SUPPLEMENT: task.recovery_action = RecoveryAction.RESEARCH_SUPPLEMENT if not _run_research_supplement( task=task, plan=plan, config=config, project_dir=project_dir, save_callback=lambda: cli._save_plan( config, plan, project_dir=project_dir, linter=linter, test_framework=test_framework, lint_mode=effective_lint_mode, max_auto_resume_passes=_saved_max_auto_resume_passes, ), restore_automatic_budget=False, ): cli._save_retry_session(cortex, config, task) cli.console.print( "[yellow]Evidence research remains escalated; no coder was started.[/yellow]" ) return if task.acceptance_profile is not AcceptanceProfile.NONE and not task.evidence_packet_id: task.status = TaskStatus.ESCALATED task.lifecycle_phase = TaskLifecyclePhase.ESCALATED task.failure_kind = TaskFailureKind.VALIDATOR_MISSING_EVIDENCE task.failure_detail = ( "A source-backed evidence packet is required before a profiled task can mutate code." ) cli._save_plan( config, plan, project_dir=project_dir, linter=linter, test_framework=test_framework, lint_mode=effective_lint_mode, max_auto_resume_passes=_saved_max_auto_resume_passes, ) cli._save_retry_session(cortex, config, task) cli.console.print("[yellow]Evidence packet remains absent; no coder was started.[/yellow]") return task.status = TaskStatus.IN_PROGRESS task.lifecycle_phase = ( TaskLifecyclePhase.RESEARCHING if task.read_only else TaskLifecyclePhase.IMPLEMENTING ) task.retry_count = 0 task.failure_kind = None task.failure_detail = "" try: lint_baseline = cli._prepare_lint_baseline( config, project_name, project_dir, linter, effective_lint_mode, create_if_missing=False, ) except LintBaselineError as exc: cli.console.print(f"[red]Cannot retry task: {exc}[/red]") return # From here on, dispatch delegates to the same worker/review/acceptance/ # finalize pipeline the automatic scheduler uses (Session 2 unification, # docs/refactor-handoffs/02-dedup.md Task 1) instead of hand-duplicating # it: branch/worktree setup, constructing the Worker, deterministic # review, the acceptance gate, and finalize/merge (including the merge- # conflict-retry-once resilience and decomposed-parent rollup the # automatic path already has) all happen inside execute_plan/ # _execute_one_task now. manual_dispatch=True preserves this command's # own invariants there: never decompose, no automatic second worker # attempt after a review failure (exactly one call, matching the # original contract), never blocked by an unrelated dependency, and the # whole-session git dirty preflight is skipped (the per-task branch # setup already resumes this task's own retained branch or discards an # unrelated stale one at the right granularity). recovery_decision # carries the already-computed manual decision through so the shared # semantic-repair-route/context logic applies without re-deriving it # from task.recovery_action (which a manual retry never persists via # schedule_recovery). execute_plan( plan, config, cortex, project_dir, linter, test_framework, hitl_mode=hitl, save_callback=lambda: cli._save_plan( config, plan, project_dir=project_dir, linter=linter, test_framework=test_framework, lint_mode=effective_lint_mode, max_auto_resume_passes=_saved_max_auto_resume_passes, ), lint_mode=effective_lint_mode, lint_baseline=lint_baseline, only_task_id=task.id, recovery_decision=recovery_decision, manual_dispatch=True, validate_existing=validate_existing, ) if task.status is TaskStatus.PASSED: cost_est = cli._estimate_cost(cortex, 1) if cost_est: cli.console.print(f" [dim]{cost_est}[/dim]") cli._save_retry_session(cortex, config, task) _clear_stale_campaign_escalation(config, plan, project_name, cli) cli.console.print("[dim]Plan saved with updated task status.[/dim]") def _clear_stale_campaign_escalation(config, plan, project_name: str, cli) -> None: """Clear a campaign's own escalated status once its blocking task resolves. A manual `afk retry` only ever touches the single plan it was pointed at; it has no notion of a wrapping campaign. Without this, a campaign that escalated because of exactly this task stays reported as escalated even after the retry fixes it, forcing a human to hand-edit the campaign's persisted JSON before `campaign work` will resume. """ from afk_developer.campaign_models import CampaignStatus from afk_developer.campaign_store import CampaignStore from afk_developer.planner.task_model import TaskStatus store = CampaignStore(config.projects_dir) campaign = store.find_by_plan_name(project_name) if campaign is None or campaign.status is not CampaignStatus.ESCALATED: return if any(task.status is TaskStatus.ESCALATED for task in plan.tasks): return campaign.status = CampaignStatus.READY campaign.stop_reason = "" store.save(campaign) cli.console.print( f" [dim]Cleared stale escalation on campaign '{campaign.name}'; " "it can resume with 'afk campaign work'.[/dim]" )