import hashlib import threading from collections.abc import Callable from contextlib import AbstractContextManager, nullcontext from dataclasses import dataclass from datetime import datetime, timedelta, timezone from pathlib import Path from typing import Any from afk_developer.backends.models import ( AcceptanceOutcome, AcceptanceValidationResult, DiscoveryProposalResult, ) from afk_developer.backends.registry import BackendRegistry from afk_developer.campaign_supervision import ( SupervisorAmendmentError, build_foreman_children, parent_contract_items, ) from afk_developer.config import Config, LintMode from afk_developer.cortex.db import CortexDB from afk_developer.environment import changed_dependency_inputs, resolve_environment_contract from afk_developer.evidence import ( EvidenceConclusion, EvidencePacketDuplicateError, EvidencePacketError, EvidencePacketStore, ) from afk_developer.events import emit from afk_developer.event_store import DurableEventStore, EventProjector from afk_developer.planner.task_model import ( ENABLED_ACCEPTANCE_PROFILES, AcceptanceProfile, ProductValidationStatus, ForemanDecompositionProposal, ForemanSubtaskProposal, ParentCoherenceEvidence, TaskFailureKind, TaskLifecyclePhase, TaskNode, TaskPlan, TaskStatus, ) from afk_developer.recovery import RecoveryAction from afk_developer.scheduler.acceptance import validate_profiled_task from afk_developer.scheduler.attempts import ( finish_agent_attempt, initialize_plan_recovery, start_agent_attempt, ) from afk_developer.scheduler.failure_classification import ( classify_review_failure, classify_worker_failure, is_transient_provider_failure, should_bypass_immediate_escalation, worker_failure_should_escalate, ) from afk_developer.scheduler.git_manager import GitManager from afk_developer.scheduler.lint_baseline import LintBaseline from afk_developer.scheduler.ledger_judge import ( check_hypothesis, research_contract_satisfied, run_contract_command, write_finding_from_research, write_scar_on_trip, ) from afk_developer.ledger import LedgerStore, working_tree_hash from afk_developer.scheduler.recovery_coordinator import ( RecoveryDecision, automatic_recovery_decision, current_altitude, decompose_fingerprint, decompose_recovery_decision, degenerate_altitude_rungs, escalate_altitude, next_altitude, repair_context, schedule_recovery, semantic_repair_route, use_coder_route, ) from afk_developer.scheduler.reviewer import review_task, verify_red_regression_tests from afk_developer.scheduler.quarantine import QuarantinedArtifact, quarantine_unreported_untracked from afk_developer.scheduler.best_of_n import execute_best_of_n # noqa: F401 (re-exported for callers/tests) from afk_developer.scheduler.discovery_checkpoint import ( DiscoveryCheckpointError, DiscoveryCheckpointStore, checkpoint_from_draft, resolve_inputs, ) from afk_developer.scheduler.task_context import assemble_task_context from afk_developer.scheduler.worker import Worker from afk_developer.utils import extract_json # Guards TaskPlan.decompositions_used (a whole-plan shared budget counter) # against concurrent overspend when multiple `--workers` threads each decide # to decompose a stuck task around the same time. _DECOMPOSE_BUDGET_LOCK = threading.Lock() _GOVERNANCE_EVENT_LOCK = threading.Lock() def _dependency_blockers(task, plan: TaskPlan) -> list[str]: task_map = {item.id: item for item in plan.tasks} blockers: list[str] = [] for dependency_id in task.dependencies: dependency = task_map.get(dependency_id) if dependency is None: blockers.append(f"{dependency_id} (missing)") elif dependency.status is TaskStatus.NOT_APPLICABLE: if not task.accepts_not_applicable_dependencies: blockers.append(f"{dependency_id} ({dependency.status.value})") elif dependency.status != TaskStatus.PASSED: blockers.append(f"{dependency_id} ({dependency.status.value})") return blockers def _evidence_gate_decision(task: TaskNode, plan: TaskPlan, config: Config) -> tuple[bool, str]: """Return whether verified paired evidence makes this task intentionally inapplicable. Evidence gates are opt-in plan metadata. A missing, stale, or mismatched packet is never treated as negative evidence: it blocks mutation safely. """ if not task.evidence_gated_by: return False, "" task_map = {item.id: item for item in plan.tasks} store = EvidencePacketStore(config.projects_dir) for dependency_id in task.evidence_gated_by: dependency = task_map[dependency_id] if not dependency.evidence_packet_id or dependency.evidence_revision is None: return ( False, f"Evidence-gate dependency {dependency_id} has no attached evidence packet.", ) try: packet = store.load_packet( project_name=plan.project_name, task_id=dependency_id, revision=dependency.evidence_revision, ) if packet.fingerprint != dependency.evidence_fingerprint: raise EvidencePacketError( "attached evidence fingerprint does not match the immutable packet" ) store.validate_packet_sources(packet) except EvidencePacketError as exc: return False, f"Evidence-gate dependency {dependency_id} is not trustworthy: {exc}" if packet.conclusion is EvidenceConclusion.INSUFFICIENT: return ( True, "Paired discovery " f"{dependency_id} has verified insufficient source evidence " f"(packet revision {packet.revision}); implementation was not attempted.", ) return False, "" def _is_evidence_gate_source(task: TaskNode, plan: TaskPlan) -> bool: """Return whether a read-only task must produce evidence for a dependent. An ``evidence_gated_by`` edge is meaningful only when its discovery task has an immutable packet attached. Ordinary read-only workers produce a narrative result, so source tasks run the trusted researcher instead. """ return task.read_only and any( task.id in candidate.evidence_gated_by for candidate in plan.tasks ) def _evidence_gate_acceptance_profile(task: TaskNode, plan: TaskPlan) -> AcceptanceProfile: """Return the strongest profile a discovery packet must satisfy for its dependents.""" profiles = [ candidate.acceptance_profile for candidate in plan.tasks if task.id in candidate.evidence_gated_by ] if AcceptanceProfile.CORPUS_RAW_OUTPUT in profiles: return AcceptanceProfile.CORPUS_RAW_OUTPUT return AcceptanceProfile.NONE def _inherit_evidence_gate_packet(task: TaskNode, plan: TaskPlan) -> None: """Bind a mutation to its immutable, already validated discovery packet.""" if task.evidence_packet_id or not task.evidence_gated_by: return source = {candidate.id: candidate for candidate in plan.tasks}[task.evidence_gated_by[0]] task.evidence_packet_id = source.evidence_packet_id task.evidence_revision = source.evidence_revision task.evidence_fingerprint = source.evidence_fingerprint def _red_regression_review_kwargs(task: TaskNode) -> dict[str, list[str]]: return ( {"excluded_test_files": task.red_regression_test_files} if task.red_regression_test_files else {} ) def _scoped_test_review_kwargs(task: TaskNode) -> dict[str, bool]: return {"disallow_unscoped_pytest": True} if task.disallow_unscoped_pytest else {} def _read_only_failure_is_baseline_only(review) -> bool: """True when a read-only review failed solely on inherited baseline state. A read-only task changes no files, so failing tests or lint describe the baseline it was asked to audit, not work it can repair. Contract breaches (missing files, scope, artifacts, ownership, whitespace) stay fatal. """ return all( ( review.files_exist, review.diff_passed, review.scope_passed, review.artifact_contract_passed, review.ownership_passed, getattr(review, "contract_passed", True), ) ) def _review_environment_kwargs(config: Config | None) -> dict[str, Any]: """Target interpreter and command budget shared by every deterministic review.""" if config is None: return {} kwargs: dict[str, Any] = {"test_timeout": config.max_shell_timeout} if config.target_python is not None: kwargs["python_executable"] = config.target_python return kwargs def _attach_current_discovery_checkpoint( task: TaskNode, plan: TaskPlan, config: Config, project_dir: Path, ) -> None: """Attach only an exact content-addressed local-discovery cache hit. A cache miss deliberately leaves the task untouched for the forthcoming structured discovery stage. Existing tasks have no contract and never reach this helper. """ if task.discovery_contract is None: return try: checkpoint = DiscoveryCheckpointStore(config.projects_dir).load_current( project_name=plan.project_name, contract=task.discovery_contract, project_dir=project_dir, evidence_fingerprint=task.evidence_fingerprint, ) except DiscoveryCheckpointError as exc: task.discovery_checkpoint_id = "" task.discovery_checkpoint_fingerprint = "" emit( "info", f" [yellow]Discovery checkpoint unavailable[/yellow] — {exc}", task_id=task.id, ) return if checkpoint is None: task.discovery_checkpoint_id = "" task.discovery_checkpoint_fingerprint = "" emit("info", " [dim]Discovery checkpoint miss.[/dim]", task_id=task.id) return task.discovery_checkpoint_id = checkpoint.fingerprint task.discovery_checkpoint_fingerprint = checkpoint.fingerprint task.discovery_checkpoint_used_count += 1 emit( "info", " [green]Using verified discovery checkpoint.[/green]", task_id=task.id, checkpoint_fingerprint=checkpoint.fingerprint, ) def _run_discovery_for_missing_checkpoint( *, task: TaskNode, plan: TaskPlan, config: Config, project_dir: Path, save_callback=None, ) -> bool: """Create one verified local-discovery checkpoint before mutation begins.""" contract = task.discovery_contract if contract is None: return True try: inputs = resolve_inputs(contract, project_dir) except DiscoveryCheckpointError as exc: _record_failure(task, TaskFailureKind.RESEARCH_STALLED, str(exc)) task.status = TaskStatus.ESCALATED task.lifecycle_phase = TaskLifecyclePhase.ESCALATED emit( "task_escalated", f" [yellow]Discovery input rejected[/yellow] — {exc}", task_id=task.id, ) return False manifest = "\n".join(f"- {item.path} sha256={item.sha256}" for item in inputs) questions = "\n".join(f"- {question}" for question in contract.questions) context = ( "Perform bounded local discovery before implementation.\n" f"Questions:\n{questions}\n" f"Declared input manifest:\n{manifest}\n" f"Allowed outputs after discovery: {', '.join(contract.allowed_output_paths)}\n" f"Exclusions: {', '.join(contract.exclusions) or '(none)'}\n" "Return only source-cited conclusions grounded in the declared manifest." ) task.lifecycle_phase = TaskLifecyclePhase.RESEARCHING start_agent_attempt( task, config, role="researcher", selection_reason="discovery_checkpoint_create", context_source_ids=["discovery-contract", "discovery-input-manifest"], context_characters=len(context), context_token_estimate=(len(context) + 3) // 4, ) if save_callback: save_callback() try: result: DiscoveryProposalResult = ( BackendRegistry(config) .get_researcher() .propose_discovery( task=task, project_dir=str(project_dir), contract=contract, context=context, max_turns=12, project_name=plan.project_name, ) ) except Exception as exc: result = DiscoveryProposalResult( status=TaskStatus.ESCALATED, summary=f"Could not run the configured discovery researcher: {exc}", failure_kind=TaskFailureKind.RECOVERY_TOOL_FAILED, ) if result.status is not TaskStatus.PASSED or result.draft is None: failure_kind = result.failure_kind or TaskFailureKind.RESEARCH_STALLED failure_detail = result.summary if result.raw_response: failure_detail += ( "\n\nProvider final response (bounded diagnostic excerpt):\n" + result.raw_response ) _record_failure(task, failure_kind, failure_detail) task.status = TaskStatus.ESCALATED task.lifecycle_phase = TaskLifecyclePhase.ESCALATED finish_agent_attempt( task, config, outcome_status=TaskStatus.ESCALATED, failure_kind=failure_kind, outcome_summary=result.summary, ) emit( "task_escalated", f" [yellow]Discovery checkpoint unavailable[/yellow] — {result.summary[:300]}", task_id=task.id, ) if save_callback: save_callback() return False try: checkpoint = checkpoint_from_draft( contract=contract, inputs=inputs, source_task_id=task.id, source_attempt_id=task.attempts[-1].id if task.attempts else "", draft=result.draft, evidence_fingerprint=task.evidence_fingerprint, ) checkpoint = DiscoveryCheckpointStore(config.projects_dir).save( plan.project_name, checkpoint ) except DiscoveryCheckpointError as exc: _record_failure(task, TaskFailureKind.RESEARCH_STALLED, str(exc)) task.status = TaskStatus.ESCALATED task.lifecycle_phase = TaskLifecyclePhase.ESCALATED finish_agent_attempt( task, config, outcome_status=TaskStatus.ESCALATED, failure_kind=TaskFailureKind.RESEARCH_STALLED, outcome_summary=task.failure_detail, ) if save_callback: save_callback() return False task.discovery_checkpoint_id = checkpoint.fingerprint task.discovery_checkpoint_fingerprint = checkpoint.fingerprint task.lifecycle_phase = TaskLifecyclePhase.READY_TO_IMPLEMENT _clear_failure(task) finish_agent_attempt( task, config, outcome_status=TaskStatus.PASSED, failure_kind=None, outcome_summary=f"Created discovery checkpoint {checkpoint.fingerprint}.", ) emit( "info", " [green]Created verified discovery checkpoint.[/green]", task_id=task.id, checkpoint_fingerprint=checkpoint.fingerprint, ) if save_callback: save_callback() return True def _red_regression_predecessor(task: TaskNode, plan: TaskPlan) -> TaskNode | None: """Return the retained red-test predecessor that this task must repair.""" predecessors = [ candidate for candidate in plan.tasks if candidate.id in task.dependencies and candidate.red_regression_test_files ] return predecessors[0] if len(predecessors) == 1 else None def _red_regression_successor(task: TaskNode, plan: TaskPlan) -> TaskNode | None: """Return the sole implementation task that will integrate a red-test branch.""" successors = [candidate for candidate in plan.tasks if task.id in candidate.dependencies] return successors[0] if len(successors) == 1 else None def _verify_red_regression_predecessor_files( task: TaskNode, plan: TaskPlan, project_dir: Path ) -> tuple[bool, str]: """Require a repair branch to retain every staged red witness file.""" predecessor = _red_regression_predecessor(task, plan) if predecessor is None: return True, "" missing = [ path for path in predecessor.red_regression_test_files if not (project_dir / path).is_file() ] if missing: return ( False, f"Implementation task is missing retained red-regression witnesses: {sorted(missing)}.", ) return True, "" def _primary_artifact_paths(task: TaskNode, red_predecessor: TaskNode | None) -> list[str]: """Return declared artifacts that must survive task integration on primary.""" paths = set(task.files_created) | set(task.required_artifacts) if red_predecessor is not None: paths.update(red_predecessor.red_regression_test_files) return sorted(paths) def _verify_red_regression_contract( task: TaskNode, project_dir: Path, test_framework: str, review_files: list[str] ) -> tuple[bool, str]: """Prevent a red-first task from hiding implementation or unrelated changes.""" if not task.red_regression_test_files: return True, "" changed = set(review_files) declared = set(task.red_regression_test_files) if not changed or not changed <= declared: return ( False, "Red-regression task may modify only its declared test files; " f"declared={sorted(declared)}, changed={sorted(changed)}.", ) return verify_red_regression_tests(project_dir, test_framework, task.red_regression_test_files) def _finalize_task_branch( git: GitManager | None, branch_name: str | None, task: TaskNode, *, commit_git: GitManager | None = None, worktree_path: Path | None = None, ) -> bool: if git is None or branch_name is None: return True committer = commit_git or git if committer.has_changes() and not committer.commit_changes(f"AFK: {task.title} [{task.id}]"): emit( "merge", f" [red]Could not commit {branch_name}. Manual recovery needed.[/red]", task_id=task.id, ) return False if worktree_path is not None and committer is not git: # Release the worktree's own Repo handle before removal -- an open handle can # otherwise block directory deletion on Windows. committer.repo.close() # A worktree's branch is never the primary checkout's "active" branch, so it must be # named explicitly; the plain in-place path is unchanged from before worktree support. merged = ( git.merge_branch_into(branch_name) if worktree_path is not None else git.merge_to_branch() ) if not merged: emit( "merge", f" [red]Merge conflict on {branch_name}. Manual resolution needed.[/red]", task_id=task.id, ) return False if worktree_path is not None: git.remove_task_worktree(worktree_path, force=True) git.delete_branch(branch_name) return True def _refresh_environment_contract_after_merge( *, plan: TaskPlan, config: Config, task: TaskNode, project_dir: Path, git: GitManager, ) -> str: """Accept reviewed dependency drift attributable to the just-merged task.""" reviewed_inputs = set(changed_dependency_inputs(task.files_created)) if not reviewed_inputs: return "" primary_commit = git.repo.head.commit if len(primary_commit.parents) < 2: return ( "The accepted task revision is not a merge commit; environment provenance is missing." ) merged_paths = git.repo.git.diff( "--name-only", primary_commit.parents[0].hexsha, primary_commit.hexsha ).splitlines() dependency_inputs = sorted(reviewed_inputs & set(changed_dependency_inputs(merged_paths))) if not dependency_inputs: return "" state_dir = config.resolve_project_dir(plan.project_name) store = DurableEventStore(state_dir / "governance-events.jsonl") snapshot_path = state_dir / "governance-projection.json" projector = EventProjector() with _GOVERNANCE_EVENT_LOCK: prior = projector.rebuild(store, snapshot_path) if not prior.environment_fingerprint: return "No accepted preflight environment exists to rebase after the task merge." environment = resolve_environment_contract( project_dir, target_python=config.target_python, ) if not environment.passed: detail = ( "The reviewed task merge changed dependency inputs, but its resulting environment " f"could not be resolved ({environment.code}): {environment.detail}" ) store.append("environment_rejected", {"code": environment.code, "detail": detail}) projector.save_snapshot(snapshot_path, projector.rebuild(store, snapshot_path)) return detail assert environment.contract is not None store.append( "environment_contract_rebased", { "fingerprint": environment.contract.target.fingerprint, "contract": environment.contract.to_record(), "task_id": task.id, "dependency_inputs": dependency_inputs, "primary_revision": primary_commit.hexsha, }, ) projector.save_snapshot(snapshot_path, projector.rebuild(store, snapshot_path)) emit( "environment", " [dim]Accepted post-merge environment contract for reviewed dependency inputs: " f"{dependency_inputs}.[/dim]", task_id=task.id, ) return "" def _clear_failure(task: TaskNode) -> None: task.failure_kind = None task.failure_detail = "" def _record_failure(task: TaskNode, kind: TaskFailureKind, detail: str) -> None: task.failure_kind = kind task.failure_detail = detail[:1000] def _trip_breaker( task: TaskNode, plan: TaskPlan, config: Config, project_dir: Path, review_files: list[str], ) -> None: """Breaker tripped: the raw log goes up and the judging altitude writes the scar. Must be called after the task's failure is recorded. If the scar budget is already spent, the ledger signals escalation instead of appending. """ scar = write_scar_on_trip( task=task, plan=plan, config=config, project_dir=project_dir, review_files=review_files ) if scar is None: _record_failure( task, TaskFailureKind.LEDGER_SCAR_BUDGET_EXCEEDED, f"Ledger scar budget exhausted; campaign needs human review. Last failure: " f"{task.failure_kind.value if task.failure_kind else 'unknown'}: {task.failure_detail}", ) emit( "task_escalated", " [red]Ledger scar budget exhausted[/red] -- escalating instead of appending.", task_id=task.id, ) return emit("info", f" [dim]Scar recorded by {scar.author_role}: {scar.one_line()[:200]}[/dim]", task_id=task.id) def _return_upward( task: TaskNode, config: Config, kind: TaskFailureKind, detail: str, save_callback ) -> None: """Send a task up to the next authority without dispatching a worker.""" task.status = TaskStatus.ESCALATED task.lifecycle_phase = TaskLifecyclePhase.ESCALATED _record_failure(task, kind, detail) emit( "task_escalated", f" [yellow]Returned up one altitude[/yellow] -- {detail[:300]}", task_id=task.id, ) config.stats.tasks_failed += 1 if save_callback: save_callback() def _ledger_preflight( task: TaskNode, plan: TaskPlan, config: Config, project_dir: Path, save_callback, ) -> bool: """Contract, budget, research-contract and hypothesis gates. Returns True when the task must not dispatch. Every refusal here goes UP (planner or human), never sideways to a worker. """ if plan.require_executable_contracts and not task.has_executable_contract(): _return_upward( task, config, TaskFailureKind.CONTRACT_MISSING, "Task has no executable acceptance test (contract_command, red_regression_test_files, " "acceptance profile, or a read-only hypothesis); the planner could not write one, so " "a human must.", save_callback, ) return True spent = task.budget_exhausted() if spent: _return_upward( task, config, TaskFailureKind.BUDGET_EXHAUSTED, f"Contract budget exhausted before dispatch: {spent}. Last failure: " f"{task.failure_kind.value if task.failure_kind else 'none'}: {task.failure_detail}", save_callback, ) _trip_breaker(task, plan, config, project_dir, list(task.files_created)) if save_callback: save_callback() return True try: research = research_contract_satisfied( task=task, plan=plan, config=config, project_dir=project_dir ) if research.satisfied: task.status = TaskStatus.PASSED task.lifecycle_phase = TaskLifecyclePhase.PASSED _clear_failure(task) emit("task_passed", f" [green]{research.detail[:300]}[/green]", task_id=task.id) config.stats.tasks_completed += 1 if save_callback: save_callback() return True verdict = check_hypothesis(task=task, plan=plan, config=config, project_dir=project_dir) except Exception as exc: # noqa: BLE001 - fail closed: an unchecked hypothesis never dispatches _return_upward( task, config, TaskFailureKind.PROVIDER_UNAVAILABLE, f"Ledger check unavailable, so the hypothesis could not be verified against the scar " f"list: {exc}. Restore provider access, then run 'afk retry {plan.project_name} {task.id}'.", save_callback, ) return True if not verdict.already_scarred: return False _return_upward( task, config, TaskFailureKind.HYPOTHESIS_ALREADY_SCARRED if verdict.entry is not None else TaskFailureKind.HYPOTHESIS_MISSING, verdict.detail, save_callback, ) return True def _apply_contract_command(task: TaskNode, review, project_dir: Path, config: Config) -> None: """Run the task's executable acceptance test; a failure is a review failure.""" if not task.contract_command.strip() or not review.passed: return ok, detail = run_contract_command( task.contract_command, project_dir, target_python=config.target_python, timeout=config.max_shell_timeout, ) if ok: return review.passed = False review.contract_passed = False review.summary = f"Contract test failed: {detail}" review.test_output = detail def _record_click( task: TaskNode, plan: TaskPlan, config: Config, project_dir: Path, git: GitManager | None ) -> bool: """Hash the tree after a merged click; a return to an earlier state trips the breaker.""" tree_hash = ( git.repo.head.commit.tree.hexsha if getattr(git, "repo", None) is not None else working_tree_hash(project_dir) ) _ledger, cycling = LedgerStore(config.projects_dir).record_click( plan.effective_ledger_name, tree_hash ) if not cycling: return False task.status = TaskStatus.ESCALATED task.lifecycle_phase = TaskLifecyclePhase.ESCALATED _record_failure( task, TaskFailureKind.CAMPAIGN_CYCLE_DETECTED, "Working tree hash after this click matches an earlier click in this campaign; " "the campaign is cycling.", ) emit( "task_escalated", " [red]Campaign is cycling[/red] -- working tree returned to an earlier state.", task_id=task.id, ) return True def _record_deterministic_failure( task: TaskNode, kind: TaskFailureKind, detail: str, project_dir: Path, review_files: list[str], ) -> bool: """Record one review state and return whether it has already occurred unchanged.""" file_hashes: dict[str, str] = {} root = project_dir.resolve() for raw_path in sorted(set(review_files)): candidate = (root / raw_path).resolve() if candidate.is_relative_to(root) and candidate.is_file(): file_hashes[raw_path] = hashlib.sha256(candidate.read_bytes()).hexdigest() material = "\n".join( ( kind.value, detail[:6000], task.evidence_packet_id, str(task.evidence_revision or ""), task.evidence_fingerprint, *[f"{path}:{digest}" for path, digest in file_hashes.items()], ) ) fingerprint = hashlib.sha256(material.encode("utf-8", errors="replace")).hexdigest() repeated = fingerprint in task.deterministic_failure_fingerprints if not repeated: task.deterministic_failure_fingerprints.append(fingerprint) _record_failure(task, kind, detail) return repeated def _review_diagnostic_dir(config: Config, plan: TaskPlan, task: TaskNode) -> Path: task_key = hashlib.sha256(task.id.encode("utf-8", errors="replace")).hexdigest()[:16] attempt_key = task.attempts[-1].id if task.attempts else "preflight" return config.resolve_project_dir(plan.project_name) / "diagnostics" / task_key / attempt_key def _attach_review_command_evidence(task: TaskNode, review) -> None: if task.attempts and getattr(review, "command_evidence", None): task.attempts[-1].review_commands.extend(review.command_evidence) def _required_artifact_review_kwargs(task: TaskNode) -> dict[str, list[str]]: """Avoid changing legacy review call shapes when no contract was declared.""" return {"required_artifacts": task.required_artifacts} if task.required_artifacts else {} def _requires_acceptance(task: TaskNode) -> bool: return task.acceptance_profile is not AcceptanceProfile.NONE def _awaits_product_validation(task: TaskNode) -> bool: return ( task.product_validation is not None and task.product_validation.status is ProductValidationStatus.AWAITING_HUMAN ) def _supports_validate_existing(task: TaskNode) -> bool: """Whether a retained branch has a deterministic validation path without a worker.""" return _requires_acceptance(task) or bool(task.red_regression_test_files) def _checkout_or_recreate_task_branch( git: GitManager, task_id: str, *, start_point: str | None = None ) -> str: """Check out (or create) a task's branch, first discarding a stale dirty branch left behind by an unrelated earlier failure (discard_branch_on_failure defaults to False) and retrying once. Raises RuntimeError only when the branch genuinely cannot be prepared even after that one discard attempt -- e.g. the currently checked-out branch is dirty, isn't this task's own, and could not be safely discarded either. Shared by both the acceptance- required and general per-task branch setup below so both get the same resilience. """ try: if start_point is None: return git.checkout_or_create_task_branch(task_id) return git.checkout_or_create_task_branch(task_id, start_point=start_point) except RuntimeError: stale_branch = git.current_branch if git.discard_task_branch(stale_branch): emit( "warning", f" [yellow]Discarded stale dirty branch {stale_branch} " "to continue with git isolation.[/yellow]", task_id=task_id, ) if start_point is None: return git.checkout_or_create_task_branch(task_id) return git.checkout_or_create_task_branch(task_id, start_point=start_point) raise def _ensure_red_predecessor_witnesses_in_branch( git: GitManager, branch_name: str, task: TaskNode, plan: TaskPlan, project_dir: Path, *, start_point: str, ) -> str: """Rebuild a stale repair branch that has lost its retained red witnesses. ``checkout_or_create_task_branch`` deliberately resumes an existing clean task branch. That is normally correct, but a failed red-successor branch can be a clean branch based on ``main`` after cleanup. Its required witnesses must win over that resumability rule: discard only that unaccepted branch and recreate it from the retained predecessor. """ present, _ = _verify_red_regression_predecessor_files(task, plan, project_dir) if present: return branch_name if not git.discard_task_branch(branch_name): raise RuntimeError(f"Could not discard witnessless red-successor branch {branch_name}.") emit( "warning", " [yellow]Rebuilt witnessless implementation branch from its retained " "red-regression predecessor.[/yellow]", task_id=task.id, ) return _checkout_or_recreate_task_branch(git, task.id, start_point=start_point) def _acceptance_failure_kind(outcome: AcceptanceOutcome) -> TaskFailureKind: if outcome is AcceptanceOutcome.FINDINGS: return TaskFailureKind.VALIDATOR_FINDINGS if outcome is AcceptanceOutcome.BLOCKED_MISSING_EVIDENCE: return TaskFailureKind.VALIDATOR_MISSING_EVIDENCE return TaskFailureKind.VALIDATOR_ERROR def _acceptance_failure_detail(result) -> str: if result.outcome is AcceptanceOutcome.FINDINGS: finding_ids = ", ".join(finding.id for finding in result.findings) return f"{result.summary} Finding IDs: {finding_ids}" if result.outcome is AcceptanceOutcome.BLOCKED_MISSING_EVIDENCE: return f"{result.summary} Research question: {result.research_question}" return result.summary def _record_validator_findings(task: TaskNode, result: AcceptanceValidationResult) -> None: task.validator_finding_ids = [finding.id for finding in result.findings] task.validator_findings = [finding.model_dump(mode="json") for finding in result.findings] if task.validator_finding_ids: fingerprint_data = "\n".join(sorted(task.validator_finding_ids)).encode("utf-8") task.validator_finding_fingerprint = hashlib.sha256(fingerprint_data).hexdigest() else: task.validator_finding_fingerprint = "" if task.attempts: task.attempts[-1].validator_finding_ids = list(task.validator_finding_ids) task.attempts[-1].validator_finding_fingerprint = task.validator_finding_fingerprint def _schedule_acceptance_recovery( task: TaskNode, plan: TaskPlan, *, save_callback=None, ) -> str: """Persist an allowed bounded follow-up, returning an empty string when none is allowed.""" decision = automatic_recovery_decision(task, plan.recovery) if not decision.is_actionable: return decision.reason try: schedule_recovery(task, decision) except ValueError as exc: return str(exc) if save_callback: save_callback() return "" def _run_research_supplement( *, task: TaskNode, plan: TaskPlan, config: Config, project_dir: Path, save_callback=None, restore_automatic_budget: bool = True, retry_invalid_evidence_proposal: bool = False, ) -> bool: """Run one read-only supplement and attach only new verified evidence. Automatic recovery reserves its research budget before calling this helper. An explicit human retry does not consume that automatic budget and therefore must not restore it if its provider call fails. Initial evidence-gate source discovery may request one extra, budgeted correction when its first proposal is rejected by trusted literal-marker validation or is absent/malformed. """ if task.recovery_action is not RecoveryAction.RESEARCH_SUPPLEMENT: return True task.lifecycle_phase = TaskLifecyclePhase.RESEARCHING lineage_instruction = ( "This is the first evidence revision: omit parent_revision from the proposal." if task.evidence_revision is None else f"This is a supplement: parent_revision must be {task.evidence_revision}." ) context = ( "Acceptance validation needs an evidence supplement.\n" f"Current evidence packet: {task.evidence_packet_id or '(none)'}\n" f"{lineage_instruction}\n" f"Research question: {task.failure_detail[:1000]}\n" "Submit a source-backed packet proposal that adds a newly verified source excerpt." ) start_agent_attempt( task, config, role="researcher", selection_reason="validator_missing_evidence_supplement", context_source_ids=["recovery-state", "validator-missing-evidence"], context_characters=len(context), context_token_estimate=(len(context) + 3) // 4, ) if save_callback: save_callback() try: research_task = task required_profile = _evidence_gate_acceptance_profile(task, plan) if required_profile is not AcceptanceProfile.NONE: research_task = task.model_copy(update={"acceptance_profile": required_profile}) result = ( BackendRegistry(config) .get_researcher() .propose_evidence( task=research_task, project_dir=str(project_dir), context=context, max_turns=12, project_name=plan.project_name, ) ) except Exception as exc: result = None error = f"Could not run the configured researcher: {exc}" caught_failure_kind = TaskFailureKind.RECOVERY_TOOL_FAILED else: error = "" caught_failure_kind = None task.recovery_action = RecoveryAction.NONE if result is not None and result.status is TaskStatus.PASSED and result.draft is not None: previous_fingerprint = task.evidence_fingerprint try: packet = EvidencePacketStore(config.projects_dir).persist_research_result( config=config, project_name=plan.project_name, task=task, result=result, ) if packet.fingerprint == previous_fingerprint: raise EvidencePacketDuplicateError( "Research supplement repeated the current evidence fingerprint." ) except EvidencePacketDuplicateError as exc: _record_failure(task, TaskFailureKind.REPEATED_EVIDENCE, str(exc)) finish_agent_attempt( task, config, outcome_status=TaskStatus.ESCALATED, failure_kind=task.failure_kind, outcome_summary=task.failure_detail, ) except EvidencePacketError as exc: detail = str(exc) _record_failure(task, TaskFailureKind.RESEARCH_STALLED, detail) finish_agent_attempt( task, config, outcome_status=TaskStatus.ESCALATED, failure_kind=task.failure_kind, outcome_summary=task.failure_detail, ) if retry_invalid_evidence_proposal: _record_failure( task, TaskFailureKind.VALIDATOR_MISSING_EVIDENCE, "The prior evidence proposal was rejected by trusted literal-marker validation: " f"{detail} Submit one corrected proposal using markers returned by the approved " "evidence-reading tool.", ) decision = automatic_recovery_decision(task, plan.recovery) if decision.is_actionable: try: schedule_recovery(task, decision) except ValueError: pass else: if save_callback: save_callback() return _run_research_supplement( task=task, plan=plan, config=config, project_dir=project_dir, save_callback=save_callback, retry_invalid_evidence_proposal=False, ) else: task.lifecycle_phase = TaskLifecyclePhase.READY_TO_IMPLEMENT _clear_failure(task) finish_agent_attempt( task, config, outcome_status=TaskStatus.PASSED, failure_kind=None, outcome_summary=( f"Attached evidence packet {packet.packet_id} revision {packet.revision}." ), ) if save_callback: save_callback() return True else: failure_kind = ( result.failure_kind if result is not None and result.failure_kind is not None else caught_failure_kind or TaskFailureKind.RESEARCH_STALLED ) detail = error or (result.summary if result is not None else "Researcher did not return.") if retry_invalid_evidence_proposal and failure_kind is TaskFailureKind.RESEARCH_STALLED: _record_failure( task, TaskFailureKind.VALIDATOR_MISSING_EVIDENCE, "The prior evidence researcher response did not produce a usable proposal: " f"{detail} Submit one complete source-backed proposal using the approved evidence tools.", ) finish_agent_attempt( task, config, outcome_status=TaskStatus.ESCALATED, failure_kind=failure_kind, outcome_summary=detail, ) decision = automatic_recovery_decision(task, plan.recovery) if decision.is_actionable: try: schedule_recovery(task, decision) except ValueError: pass else: if save_callback: save_callback() return _run_research_supplement( task=task, plan=plan, config=config, project_dir=project_dir, save_callback=save_callback, retry_invalid_evidence_proposal=False, ) if restore_automatic_budget and failure_kind in { TaskFailureKind.PROVIDER_UNAVAILABLE, TaskFailureKind.PROVIDER_TIMEOUT, TaskFailureKind.VERIFICATION_POLICY_REJECTED, TaskFailureKind.VERIFICATION_TOOL_FAILED, TaskFailureKind.RECOVERY_TOOL_FAILED, }: task.research_supplements_remaining += 1 task.research_supplements_used = max(task.research_supplements_used - 1, 0) _record_failure(task, failure_kind, detail) finish_agent_attempt( task, config, outcome_status=TaskStatus.ESCALATED, failure_kind=failure_kind, outcome_summary=detail, ) task.status = TaskStatus.ESCALATED task.lifecycle_phase = TaskLifecyclePhase.ESCALATED if save_callback: save_callback() return False def _trusted_change_summary(project_dir: Path) -> tuple[list[str], str]: """Collect the current branch's changed paths and stat without trusting agent declarations.""" try: git = GitManager(project_dir) changed = set(git.repo.git.diff("--name-only", "HEAD").splitlines()) changed.update(git.repo.untracked_files) diff_stat = git.repo.git.diff("--stat", "HEAD").strip() return sorted(path for path in changed if path), diff_stat or "No tracked diff stat." except Exception as exc: return [], f"Trusted Git change summary unavailable: {exc}" def _review_files_from_worktree( project_dir: Path, git: GitManager | None, declared_files: list[str], ) -> list[str]: """Choose review ownership from Git when it is available. A coder's ``files_changed`` response is useful diagnostics but not a reliable ownership source: agents can create and delete temporary repair scripts before calling ``task_complete``. Git provides the authoritative current tree for a branch-isolated task. Non-Git projects retain the prior existing-file fallback. """ if git is not None and hasattr(git, "worktree_files"): return git.worktree_files() root = project_dir.resolve() files: list[str] = [] for raw_path in declared_files: candidate = (root / raw_path).resolve() if candidate.is_relative_to(root) and candidate.is_file(): files.append(candidate.relative_to(root).as_posix()) return sorted(set(files)) def _review_failure_detail(review) -> str: """Preserve concise deterministic diagnostics for the next repair attempt.""" details = [review.summary] if not review.tests_passed and review.test_output: details.append(f"Test output:\n{review.test_output}") if not review.lint_passed and review.lint_output: details.append(f"Lint output:\n{review.lint_output}") if not review.diff_passed and review.diff_output: details.append(f"Diff output:\n{review.diff_output}") return "\n\n".join(part for part in details if part)[:6000] def _ownership_failure_is_mechanically_recoverable(review) -> bool: return ( not review.ownership_passed and bool(review.unreported_untracked_files) and review.tests_passed and review.lint_passed and review.files_exist and review.diff_passed and review.scope_passed and review.artifact_contract_passed and review.required_artifacts_passed ) def _record_quarantine_effect( config: Config, plan: TaskPlan, task: TaskNode, artifact: QuarantinedArtifact, *, completed: bool, project_dir: Path, ) -> None: effect_id = f"quarantine:{task.id}:{artifact.sha256}" state_dir = config.resolve_project_dir(plan.project_name) store = DurableEventStore(state_dir / "governance-events.jsonl") snapshot_path = state_dir / "governance-projection.json" kind = "effect_completed" if completed else "effect_intended" payload = ( { "effect_id": effect_id, "outcome": "quarantined", "project_path": artifact.project_path, "sha256": artifact.sha256, "quarantine_path": str(artifact.quarantine_path), } if completed else { "effect_id": effect_id, "operation": "quarantine", "project_path": artifact.project_path, "source_path": str(project_dir / artifact.project_path), "sha256": artifact.sha256, "quarantine_path": str(artifact.quarantine_path), } ) with _GOVERNANCE_EVENT_LOCK: store.append(kind, payload) EventProjector().save_snapshot( snapshot_path, EventProjector().rebuild(store, snapshot_path) ) def _quarantine_scratch_and_rereview( *, task: TaskNode, plan: TaskPlan, config: Config, project_dir: Path, linter: str, test_framework: str, review_files: list[str], reported_files: list[str], lint_mode: LintMode, lint_baseline: LintBaseline | None, save_callback=None, ): quarantine_root = ( config.resolve_project_dir(plan.project_name) / "quarantine" / task.id.replace("/", "_") ) result = quarantine_unreported_untracked( project_dir, reported_files, quarantine_root, before_move=lambda artifact: _record_quarantine_effect( config, plan, task, artifact, completed=False, project_dir=project_dir ), after_move=lambda artifact: _record_quarantine_effect( config, plan, task, artifact, completed=True, project_dir=project_dir ), ) if not result.passed: emit( "warning", " [yellow]Scratch quarantine blocked[/yellow] — " f"{', '.join(result.blocked_paths) or 'no safe artifacts moved'}.", task_id=task.id, ) return None task.mechanical_rereviews_used += 1 if save_callback: save_callback() emit( "review", " [cyan]Quarantined unreported scratch artifacts[/cyan] — rerunning deterministic review.", task_id=task.id, artifacts=[item.project_path for item in result.moved], mechanical_repair=True, ) quarantined_paths = {item.project_path for item in result.moved} rereview_files = [path for path in review_files if path not in quarantined_paths] task.files_created = [path for path in task.files_created if path not in quarantined_paths] review = review_task( project_dir, linter, test_framework, files_changed=rereview_files, lint_mode=lint_mode, lint_baseline=lint_baseline, **_review_environment_kwargs(config), max_changed_files=task.max_changed_files, max_changed_lines=task.max_changed_lines, require_raw_contract_artifacts=task.require_raw_contract_artifacts, **_red_regression_review_kwargs(task), **_scoped_test_review_kwargs(task), **_required_artifact_review_kwargs(task), reported_files=reported_files, diagnostic_dir=_review_diagnostic_dir(config, plan, task), ) _attach_review_command_evidence(task, review) return review def _run_independent_validator( *, task: TaskNode, config: Config, project_dir: Path, review, task_context: str = "", project_name: str = "", ) -> AcceptanceValidationResult: """Call the configured read-only validator only after trusted profile checks pass.""" changed_paths, diff_stat = _trusted_change_summary(project_dir) trusted_context = ( f"Acceptance profile: {task.acceptance_profile.value}\n" f"Evidence packet: {task.evidence_packet_id} revision={task.evidence_revision} " f"fingerprint={task.evidence_fingerprint}\n" f"Trusted changed paths: {', '.join(changed_paths) or '(none detected)'}\n" f"Trusted Git diff stat:\n{diff_stat}\n" f"Deterministic review: {review.summary}\n" f"Tests passed: {review.tests_passed}; lint passed: {review.lint_passed}; " f"diff passed: {review.diff_passed}." ) context = f"{task_context}\n\n--- Trusted Validation Facts ---\n{trusted_context}".strip() try: validator = BackendRegistry(config).get_validator() return validator.validate( task=task, project_dir=str(project_dir), context=context, max_turns=12, project_name=project_name, ) except Exception as exc: return AcceptanceValidationResult( outcome=AcceptanceOutcome.VALIDATOR_ERROR, summary=f"Could not run the configured independent validator: {exc}", ) def _run_acceptance_gate( *, task: TaskNode, config: Config, project_dir: Path, review, save_callback=None, task_context: str = "", context_source_ids: list[str] | None = None, context_characters: int = 0, context_token_estimate: int = 0, project_name: str = "", ) -> AcceptanceValidationResult: """Run trusted and provider-backed validation before any profiled task may merge.""" task.lifecycle_phase = TaskLifecyclePhase.VALIDATING acceptance = validate_profiled_task( task=task, config=config, project_dir=project_dir, ) if acceptance.passed: start_agent_attempt( task, config, role="validator", selection_reason="independent_acceptance_validation", context_source_ids=context_source_ids, context_characters=context_characters, context_token_estimate=context_token_estimate, ) if save_callback: save_callback() acceptance = _run_independent_validator( task=task, config=config, project_dir=project_dir, review=review, task_context=task_context, project_name=project_name, ) _record_validator_findings(task, acceptance) finish_agent_attempt( task, config, outcome_status=TaskStatus.PASSED if acceptance.passed else TaskStatus.ESCALATED, failure_kind=( None if acceptance.passed else _acceptance_failure_kind(acceptance.outcome) ), outcome_summary=_acceptance_failure_detail(acceptance), ) _record_validator_findings(task, acceptance) return acceptance def _handle_acceptance_failure( *, task: TaskNode, plan: TaskPlan, acceptance: AcceptanceValidationResult, save_callback=None, ) -> bool: """Either persist the one permitted recovery step or leave the task escalated.""" _record_failure( task, _acceptance_failure_kind(acceptance.outcome), _acceptance_failure_detail(acceptance), ) blocked_reason = _schedule_acceptance_recovery(task, plan, save_callback=save_callback) if not blocked_reason: emit( "warning", " [yellow]Acceptance recovery scheduled[/yellow] — " f"{task.recovery_action.value.replace('_', ' ')}.", task_id=task.id, ) return True task.status = TaskStatus.ESCALATED task.lifecycle_phase = TaskLifecyclePhase.ESCALATED emit( "task_escalated", " [yellow]Acceptance blocked merge[/yellow] — " f"{acceptance.summary[:300].encode('ascii', 'replace').decode('ascii')} " f"Recovery stopped: {blocked_reason}", task_id=task.id, ) return False def _maybe_decompose_task( *, task: TaskNode, plan: TaskPlan, config: Config, save_callback=None, ) -> bool: """Ask the foreman to split one retries-exhausted task into independent subtasks. The task's current failure must already be recorded (``_record_failure``) before this is called. Returns whether the task was decomposed; the caller is expected to fall through to its normal escalation path when this returns ``False``. """ pending_proposals = sum( proposal.status.value == "pending" for proposal in plan.foreman_proposals ) decision = decompose_recovery_decision( task, plan.recovery, decompositions_used=plan.decompositions_used + pending_proposals ) if not decision.is_actionable: return False fingerprint = decompose_fingerprint(task) max_subtasks = plan.recovery.max_subtasks_per_decomposition context = ( f"TASK: {task.title}\n{task.description}\n\n" f"FAILURE AFTER {task.retry_count} RETRIES " f"({task.failure_kind.value if task.failure_kind else 'unknown'}): " f"{task.failure_detail[:1500]}" ) contract_items = sorted(parent_contract_items(task)) context += f"\n\nPARENT TASK ID: {task.id}" context += "\n\nPARENT CONTRACT ITEMS (cover every item exactly):\n" + "\n".join( f"- {item}" for item in contract_items ) start_agent_attempt( task, config, role="foreman", selection_reason="decompose_stuck_task", context_source_ids=["failure-detail"], context_characters=len(context), context_token_estimate=(len(context) + 3) // 4, ) if save_callback: save_callback() try: response = ( BackendRegistry(config) .get_foreman() .complete( system_prompt=( "You are a bounded foreman reviewing one task that has exhausted its " "retry budget. Decide only between 'decompose' (split the task into 2-" f"{max_subtasks} atomic subtasks that together cover the original " "goal without narrowing or changing the acceptance bar) or 'escalate' (a human must " 'decide). Return ONLY JSON: {"decision":"decompose|escalate",' '"subtasks":[{"title":"...","description":"...","hypothesis":"one sentence",' '"contract_command":"shell command from project root, exit 0 = satisfied, {python} = target interpreter, empty only if no runnable test exists",' '"covers":["criterion:"],"depends_on":[1]}],' '"summary":"..."}. Assign every listed parent contract item to exactly one child. ' "A preparatory child may use an empty covers list. " "Use depends_on only for earlier 1-based child indexes when staged work is required; " "each child must be completable once those dependencies pass. Never request credentials, " "new network access, or destructive actions." ), user_prompt=context, temperature=0.0, ) ) except Exception as exc: finish_agent_attempt( task, config, outcome_status=TaskStatus.ESCALATED, failure_kind=TaskFailureKind.RECOVERY_TOOL_FAILED, outcome_summary=f"Could not run the configured foreman: {exc}", ) task.decomposition_fingerprints.append(fingerprint) if save_callback: save_callback() return False config.record_usage(response.usage, role="foreman") raw = extract_json(response.content) raw_decision = str(raw.get("decision", "escalate")).strip().lower() raw_subtasks = raw.get("subtasks", []) summary = str(raw.get("summary", ""))[:2000] subtasks: list[tuple[str, str, list[str], list[int], str, str]] = [] if isinstance(raw_subtasks, list): for index, item in enumerate(raw_subtasks, start=1): if not isinstance(item, dict): continue title = str(item.get("title", "")).strip() description = str(item.get("description", "")).strip() hypothesis = str(item.get("hypothesis", "")).strip()[:300] contract_command = str(item.get("contract_command", "")).strip()[:1_000] covers = item.get("covers", []) depends_on = item.get("depends_on", []) valid_dependencies = ( isinstance(depends_on, list) and len(set(depends_on)) == len(depends_on) and all( isinstance(value, int) and not isinstance(value, bool) and 1 <= value < index for value in depends_on ) ) if title and description and isinstance(covers, list) and valid_dependencies: normalized_covers = [str(value).strip() for value in covers if str(value).strip()] subtasks.append( ( title[:200], description[:4000], normalized_covers, depends_on, hypothesis, contract_command, ) ) if raw_decision != "decompose" or not (2 <= len(subtasks) <= max_subtasks): finish_agent_attempt( task, config, outcome_status=TaskStatus.ESCALATED, failure_kind=task.failure_kind, outcome_summary=summary or "Foreman did not propose a valid independent subtask split.", ) task.decomposition_fingerprints.append(fingerprint) if save_callback: save_callback() return False with _DECOMPOSE_BUDGET_LOCK: # Re-check the plan-wide budget now that we hold the lock: another # worker thread may have spent the last slot while our foreman call # was in flight. Treat exhaustion here exactly like the earlier # (unlocked) gate check would have -- escalate instead of overspending. pending_proposals = sum( proposal.status.value == "pending" for proposal in plan.foreman_proposals ) if plan.decompositions_used + pending_proposals >= plan.recovery.max_decompositions: budget_spent_summary = ( "No decomposition budget remains for this plan (spent by a concurrent decompose)." ) finish_agent_attempt( task, config, outcome_status=TaskStatus.ESCALATED, failure_kind=task.failure_kind, outcome_summary=budget_spent_summary, ) task.decomposition_fingerprints.append(fingerprint) if save_callback: save_callback() return False proposal = ForemanDecompositionProposal( parent_task_id=task.id, failure_fingerprint=fingerprint, summary=summary, subtasks=[ ForemanSubtaskProposal( id=f"{task.id}-sub-{index}", title=title, description=description, hypothesis=hypothesis, contract_command=contract_command, covers=covers, depends_on=[f"{task.id}-sub-{dependency}" for dependency in depends_on], ) for index, ( title, description, covers, depends_on, hypothesis, contract_command, ) in enumerate(subtasks, start=1) ], ) try: new_tasks = build_foreman_children(task, proposal) except SupervisorAmendmentError as exc: finish_agent_attempt( task, config, outcome_status=TaskStatus.ESCALATED, failure_kind=task.failure_kind, outcome_summary=f"Foreman proposed an invalid child contract: {exc}"[:1000], ) task.decomposition_fingerprints.append(fingerprint) if save_callback: save_callback() return False if plan.recovery.require_supervisor_decomposition_approval: plan.foreman_proposals.append(proposal) task.status = TaskStatus.ESCALATED task.lifecycle_phase = TaskLifecyclePhase.ESCALATED finish_agent_attempt( task, config, outcome_status=TaskStatus.ESCALATED, failure_kind=task.failure_kind, outcome_summary=( f"Foreman proposed {len(subtasks)} subtasks awaiting supervisor approval. {summary}" )[:1000], ) if save_callback: save_callback() return True plan.tasks.extend(new_tasks) initialize_plan_recovery(plan, plan.recovery) task.subtask_ids = [subtask.id for subtask in new_tasks] task.status = TaskStatus.DECOMPOSED task.lifecycle_phase = TaskLifecyclePhase.DECOMPOSED task.decomposition_fingerprints.append(fingerprint) plan.decompositions_used += 1 finish_agent_attempt( task, config, outcome_status=TaskStatus.PASSED, failure_kind=None, outcome_summary=f"Decomposed into {len(new_tasks)} subtasks. {summary}"[:1000], ) if save_callback: save_callback() return True def _rollup_decomposed_parent( plan: TaskPlan, subtask: TaskNode, *, config: Config | None = None, project_dir: Path | None = None, linter: str = "", test_framework: str = "", lint_mode: LintMode = LintMode.STRICT, lint_baseline: LintBaseline | None = None, save_callback=None, ) -> None: """Verify the merged child set before a supervisor may close its parent.""" if not subtask.parent_task_id: return parent = next((item for item in plan.tasks if item.id == subtask.parent_task_id), None) if parent is None or parent.status is not TaskStatus.DECOMPOSED: return siblings = [item for item in plan.tasks if item.id in parent.subtask_ids] if siblings and all(sibling.status is TaskStatus.PASSED for sibling in siblings): if project_dir is not None: review_files = sorted({path for sibling in siblings for path in sibling.files_created}) coherence = review_task( project_dir, linter, test_framework, files_changed=review_files, apply_format=False, lint_mode=lint_mode, lint_baseline=lint_baseline, **_scoped_test_review_kwargs(parent), **_review_environment_kwargs(config), required_artifacts=parent.required_artifacts, diagnostic_dir=( _review_diagnostic_dir(config, plan, subtask) if config is not None else None ), ) _attach_review_command_evidence(subtask, coherence) parent.parent_coherence_evidence = ParentCoherenceEvidence( child_task_ids=[sibling.id for sibling in siblings], files_checked=review_files, tests_passed=coherence.tests_passed, lint_passed=coherence.lint_passed, files_exist=coherence.files_exist, diff_passed=coherence.diff_passed, required_artifacts_passed=coherence.required_artifacts_passed, passed=coherence.passed, summary=coherence.summary, ) if not coherence.passed: parent.blocked_reason = ( f"Merged child coherence verification failed: {coherence.summary}" ) emit( "task_blocked", f" [yellow]{parent.blocked_reason}[/yellow]", task_id=parent.id ) if save_callback: save_callback() return if plan.recovery.require_supervisor_parent_coherence: parent.blocked_reason = ( "Merged child coherence verification passed; await supervisor acceptance." ) emit("task_blocked", f" [yellow]{parent.blocked_reason}[/yellow]", task_id=parent.id) if save_callback: save_callback() return parent.status = TaskStatus.PASSED parent.lifecycle_phase = TaskLifecyclePhase.PASSED emit( "task_passed", f" [green]Parent task {parent.id} PASSED[/green] — all " f"{len(siblings)} subtasks completed.", task_id=parent.id, ) if save_callback: save_callback() @dataclass class _ExecutionContext: """Values execute_plan() computes once before the per-task loop starts and that stay read-only for the rest of the call -- shared, unchanging context passed to _execute_one_task. This is distinct from branch_name/task_workdir/ task_git/worktree_active, which are genuinely fresh per task and stay local to _execute_one_task itself. """ plan: TaskPlan config: Config cortex: CortexDB project_dir: Path linter: str test_framework: str hitl_mode: bool save_callback: Callable[[], None] | None lint_mode: LintMode lint_baseline: LintBaseline | None lease_seconds: int | None lease_owner: str isolation: str git: GitManager | None git_unavailable_reason: str worktree_root: Path lock_ctx: AbstractContextManager # The following are only ever set by a manual `afk retry` dispatch # (scheduler/manual_retry.py); every other caller uses the defaults below, # which reproduce the automatic scheduler's original behavior exactly. # See execute_plan's docstring for what manual_dispatch=True implies. recovery_decision: RecoveryDecision | None = None manual_dispatch: bool = False validate_existing: bool = False def execute_plan( plan: TaskPlan, config: Config, cortex: CortexDB, project_dir: Path, linter: str, test_framework: str, hitl_mode: bool = False, save_callback=None, lint_mode: LintMode = LintMode.STRICT, lint_baseline: LintBaseline | None = None, only_task_id: str | None = None, lease_seconds: int | None = None, lease_owner: str = "", isolation: str = "inplace", git_lock: "threading.Lock | None" = None, recovery_decision: RecoveryDecision | None = None, manual_dispatch: bool = False, validate_existing: bool = False, ) -> bool: """Execute the plan's runnable tasks. ``only_task_id`` bounds this call to exactly one task -- every other task is skipped without side effects -- so a durable campaign can dispatch one bounded sprint at a time using the same worker/review/acceptance pipeline as an ordinary run. ``lease_seconds``/``lease_owner`` are stamped on the task the moment it is marked ``IN_PROGRESS`` (and persisted immediately via ``save_callback``), so an abandoned in-flight task becomes eligible again once its lease expires -- see ``campaign.reap_expired_leases``. The remaining keyword-only parameters exist so a manual `afk retry` (``scheduler/manual_retry.py::run_manual_retry``) can dispatch its single task through this exact same pipeline instead of hand-duplicating it. ``recovery_decision``, when given, overrides the automatic ``task.recovery_action`` check with a freshly-computed ``manual_recovery_decision(...)`` result (a human retry never persists an automatic ``schedule_recovery`` transition, so there is nothing for ``task.recovery_action`` to have been set to). ``manual_dispatch=True`` preserves several manual-retry-only invariants at once: it never triggers foreman decompose (only the automatic scheduler loop may), it never adds an automatic second worker attempt after a deterministic review failure (manual retry's original exactly-one-worker-call contract), it is never blocked by a dependency that hasn't (re)passed (a human is explicitly targeting one task), and it skips the whole-session git dirty/staleness preflight below (designed for cleaning up cross-task staleness at the START of a whole scheduler pass -- the wrong granularity for resuming or validating one already-dirty retained task branch; ``_execute_one_task``'s own per-task branch setup already discards an unrelated stale branch or resumes the task's own branch at the correct granularity). ``validate_existing=True`` (only meaningful with ``manual_dispatch=True``) skips constructing a Worker entirely and instead runs review + acceptance directly against the retained branch's already-present (uncommitted) changes. Every default reproduces the automatic scheduler's original, ``validate_existing=True`` (only meaningful with ``manual_dispatch=True``) skips constructing a Worker entirely and instead runs review + acceptance directly against the retained branch's already-present (uncommitted) changes. Every default reproduces the automatic scheduler's original, unchanged behavior. ``isolation`` selects how a mutating task's branch is checked out. The default ``"inplace"`` checks the branch out directly in the shared ``project_dir`` working tree (today's original behavior, unchanged). ``"worktree"`` instead creates an isolated ``git worktree`` per task under ``//worktrees/``, so a task's branch never has to be checked out in the shared tree -- a prerequisite for ever running more than one task at a time against the same repository. ``git_lock``, when provided, serializes only the operations that touch the *primary* checkout's shared refs/worktree metadata (branch/worktree creation, merge, discard) -- never the worker/test/review work itself, so a caller running several ``execute_plan`` calls concurrently (each its own ``only_task_id``, each ``isolation="worktree"``) gets genuine parallelism for the slow part while the fast git metadata operations stay safe. """ lock_ctx = git_lock if git_lock is not None else nullcontext() sorted_tasks = plan.topological_sort() mode_label = "[yellow]HITL[/yellow]" if hitl_mode else "[green]AFK[/green]" emit( "info", f"\n[bold]Executing {len(sorted_tasks)} tasks ({mode_label})[/bold] for [cyan]{plan.project_name}[/cyan]", ) if not hitl_mode and plan.intent != "analyze": emit( "warning", "[dim yellow]Warning: Commands run directly on your machine (no sandbox). " "Use --hitl for approval mode.[/dim yellow]", ) degenerate_rungs = degenerate_altitude_rungs(config) if degenerate_rungs: emit( "warning", "[yellow]Altitude ladder is degenerate: " f"{', '.join(degenerate_rungs)} resolve to the same model and effort, so an " "escalated retry there is a sideways retry. Configure distinct routes per role.[/yellow]", code="ALTITUDE_LADDER_DEGENERATE", rungs=degenerate_rungs, ) git = None git_unavailable_reason = "" if plan.intent != "analyze": try: git = GitManager(project_dir) git.branch_namespace = plan.branch_namespace emit("info", f"[dim]On branch: {git.current_branch}[/dim]") # A manual single-task retry dispatch explicitly targets one # task's own (possibly already-dirty) retained branch -- the # whole-session staleness cleanup below is the wrong granularity # for that case (it can discard the very retained changes a # retry/--validate-existing is trying to resume or validate). # _execute_one_task's own per-task branch setup (see # _checkout_or_recreate_task_branch) already handles "already on # my branch" / "discard an unrelated stale branch" correctly. if not manual_dispatch and git.has_changes(): resumable_repair = next( ( task for task in plan.tasks if _requires_acceptance(task) and task.status is TaskStatus.RETRYING and task.recovery_action is RecoveryAction.SEMANTIC_REPAIR and git.current_branch == git.task_branch_name(task.id) ), None, ) if resumable_repair is not None: emit( "info", "[dim]Resuming the retained acceptance branch for " f"semantic repair: {resumable_repair.id}[/dim]", ) elif git.current_branch.startswith("afk/") and git.discard_task_branch( git.current_branch ): # A prior invocation/pass ended with an unrelated task's # branch left dirty (discard_branch_on_failure defaults to # False). That task's own outcome is already recorded, so # nothing here is waiting to be resumed -- safe to clean up # and keep git isolation for this session instead of # silently losing it entirely. Only ever touches AFK's own # "afk/" branches, never a human's own branch. emit( "warning", "[yellow]Discarded a stale dirty task branch left over " "from a previous run to restore git isolation: " f"{git.current_branch}[/yellow]", ) else: git_unavailable_reason = "The target Git worktree is dirty." emit( "warning", "[yellow]Warning: uncommitted changes detected. " "Running without git branch isolation for this session.[/yellow]", ) git = None except ValueError as e: git_unavailable_reason = str(e) emit("warning", f"[yellow]Git: {e} — running without branch isolation.[/yellow]") worktree_root = config.resolve_project_dir(plan.project_name) / "worktrees" if isolation == "worktree" and git is not None: with lock_ctx: git.prune_worktrees() emit("info", f"[dim]Git isolation: worktree ({worktree_root})[/dim]") ctx = _ExecutionContext( plan=plan, config=config, cortex=cortex, project_dir=project_dir, linter=linter, test_framework=test_framework, hitl_mode=hitl_mode, save_callback=save_callback, lint_mode=lint_mode, lint_baseline=lint_baseline, lease_seconds=lease_seconds, lease_owner=lease_owner, isolation=isolation, git=git, git_unavailable_reason=git_unavailable_reason, worktree_root=worktree_root, lock_ctx=lock_ctx, recovery_decision=recovery_decision, manual_dispatch=manual_dispatch, validate_existing=validate_existing, ) for i, task in enumerate(sorted_tasks): if only_task_id is not None and task.id != only_task_id: continue _execute_one_task(ctx, task, task_number=i + 1, total_tasks=len(sorted_tasks)) return plan.all_done() def _execute_one_task( ctx: _ExecutionContext, task: TaskNode, *, task_number: int, total_tasks: int ) -> None: """Run one task through the full escalation ladder: evidence gates, acceptance preflight, worker execution, deterministic review (with one retry), then finalize/merge or decompose/discard on failure. This is execute_plan's former per-task loop body, unchanged except that every ``continue`` (there is no ``break`` or other early exit in the original) became a ``return`` -- both mean exactly the same thing here: "this task's processing is done, move on to the next one." """ plan = ctx.plan config = ctx.config cortex = ctx.cortex project_dir = ctx.project_dir linter = ctx.linter test_framework = ctx.test_framework hitl_mode = ctx.hitl_mode save_callback = ctx.save_callback lint_mode = ctx.lint_mode lint_baseline = ctx.lint_baseline lease_seconds = ctx.lease_seconds lease_owner = ctx.lease_owner isolation = ctx.isolation git = ctx.git git_unavailable_reason = ctx.git_unavailable_reason worktree_root = ctx.worktree_root lock_ctx = ctx.lock_ctx recovery_decision = ctx.recovery_decision manual_dispatch = ctx.manual_dispatch validate_existing = ctx.validate_existing emit( "task_started", f"\n[bold]Task {task_number}/{total_tasks}[/bold]: {task.id} — {task.title}", task_id=task.id, ) if task.status in {TaskStatus.PASSED, TaskStatus.NOT_APPLICABLE}: emit("info", " [dim]Skipping — task already passed.[/dim]", task_id=task.id) return if task.status == TaskStatus.DECOMPOSED: emit("info", " [dim]Skipping — decomposed into subtasks.[/dim]", task_id=task.id) return if task.status == TaskStatus.ESCALATED: emit("info", " [yellow]Skipping — task requires manual retry.[/yellow]", task_id=task.id) return if _awaits_product_validation(task): emit( "task_blocked", " [yellow]Awaiting human product validation[/yellow] — " f"{task.product_validation.kind}.", task_id=task.id, human_validation=True, ) return blockers = [] if manual_dispatch else _dependency_blockers(task, plan) if blockers: task.status = TaskStatus.BLOCKED task.blocked_reason = f"Waiting for: {', '.join(blockers)}" emit("info", f" [yellow]Blocked[/yellow] — {task.blocked_reason}", task_id=task.id) if save_callback: save_callback() return if task.status == TaskStatus.BLOCKED: task.status = TaskStatus.PENDING task.blocked_reason = "" emit("info", " [dim]Dependencies recovered — task is ready.[/dim]", task_id=task.id) 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=save_callback, restore_automatic_budget=False, retry_invalid_evidence_proposal=True, ): emit( "task_escalated", " [yellow]Evidence discovery escalated[/yellow] — packet was not attached.", task_id=task.id, ) config.stats.tasks_failed += 1 return task.status = TaskStatus.PASSED task.lifecycle_phase = TaskLifecyclePhase.PASSED emit( "task_passed", " [green]Evidence discovery complete[/green] — immutable packet attached.", task_id=task.id, ) config.stats.tasks_completed += 1 if save_callback: save_callback() 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) emit("info", f" [cyan]Not applicable[/cyan] — {evidence_gate_detail}", task_id=task.id) config.stats.tasks_completed += 1 if save_callback: save_callback() return if evidence_gate_detail: task.status = TaskStatus.ESCALATED task.lifecycle_phase = TaskLifecyclePhase.ESCALATED _record_failure(task, TaskFailureKind.VALIDATOR_MISSING_EVIDENCE, evidence_gate_detail) emit( "task_escalated", f" [yellow]Evidence gate blocked mutation[/yellow] — {evidence_gate_detail}", task_id=task.id, ) config.stats.tasks_failed += 1 if save_callback: save_callback() return _inherit_evidence_gate_packet(task, plan) if task.status == TaskStatus.PENDING and task.files_created: all_exist = ( git.primary_contains_files(task.files_created) if git is not None else all((project_dir / f).exists() for f in task.files_created) ) if all_exist: prereview = review_task( project_dir, linter, test_framework, files_changed=task.files_created, apply_format=False, lint_mode=lint_mode, lint_baseline=lint_baseline, **_review_environment_kwargs(config), **_red_regression_review_kwargs(task), **_scoped_test_review_kwargs(task), **_required_artifact_review_kwargs(task), ) if prereview.passed: task.status = TaskStatus.PASSED emit( "task_passed", " [dim]Skipping — files exist and tests pass.[/dim]", task_id=task.id, ) config.stats.tasks_completed += 1 if save_callback: save_callback() return branch_name = None task_workdir = project_dir task_git = git worktree_active = False red_predecessor = _red_regression_predecessor(task, plan) if not manual_dispatch and _ledger_preflight(task, plan, config, project_dir, save_callback): return if _requires_acceptance(task): if task.acceptance_profile not in ENABLED_ACCEPTANCE_PROFILES: task.status = TaskStatus.ESCALATED task.lifecycle_phase = TaskLifecyclePhase.ESCALATED _record_failure( task, TaskFailureKind.ACCEPTANCE_POLICY_REJECTED, f"Acceptance profile '{task.acceptance_profile.value}' is not enabled.", ) emit( "task_escalated", " [yellow]Acceptance preflight rejected[/yellow] — profile has no trusted " "validator implementation.", task_id=task.id, ) config.stats.tasks_failed += 1 if save_callback: save_callback() return if task.read_only: task.status = TaskStatus.ESCALATED task.lifecycle_phase = TaskLifecyclePhase.ESCALATED _record_failure( task, TaskFailureKind.ACCEPTANCE_POLICY_REJECTED, "Required acceptance profiles only apply to branch-isolated mutating tasks.", ) emit( "task_escalated", " [yellow]Acceptance preflight rejected[/yellow] — a required profile needs " "an isolated mutating task branch.", task_id=task.id, ) config.stats.tasks_failed += 1 if save_callback: save_callback() return if git is None: task.status = TaskStatus.ESCALATED task.lifecycle_phase = TaskLifecyclePhase.ESCALATED _record_failure( task, TaskFailureKind.ACCEPTANCE_POLICY_REJECTED, "Required acceptance validation needs a clean Git worktree and an AFK task branch. " + (git_unavailable_reason or "Git branch isolation is unavailable."), ) emit( "task_escalated", " [yellow]Acceptance preflight rejected[/yellow] — required profiles cannot " "run in a dirty or non-Git worktree.", task_id=task.id, ) config.stats.tasks_failed += 1 if save_callback: save_callback() return resumed_research = task.recovery_action is RecoveryAction.RESEARCH_SUPPLEMENT if _requires_acceptance(task) and not task.evidence_packet_id: if not resumed_research: _record_failure( task, TaskFailureKind.VALIDATOR_MISSING_EVIDENCE, "A source-backed evidence packet is required before a profiled task can mutate code.", ) blocked_reason = _schedule_acceptance_recovery( task, plan, save_callback=save_callback, ) if blocked_reason: task.status = TaskStatus.ESCALATED task.lifecycle_phase = TaskLifecyclePhase.ESCALATED emit( "task_escalated", f" [yellow]Evidence preflight blocked mutation[/yellow] — {blocked_reason}", task_id=task.id, ) config.stats.tasks_failed += 1 if save_callback: save_callback() return resumed_research = task.recovery_action is RecoveryAction.RESEARCH_SUPPLEMENT if not resumed_research or not _run_research_supplement( task=task, plan=plan, config=config, project_dir=project_dir, save_callback=save_callback, ): emit( "task_escalated", " [yellow]Research supplement escalated[/yellow] — " f"{task.failure_detail[:300].encode('ascii', 'replace').decode('ascii')}", task_id=task.id, ) config.stats.tasks_failed += 1 return if _requires_acceptance(task) and not task.evidence_packet_id: task.status = TaskStatus.ESCALATED task.lifecycle_phase = TaskLifecyclePhase.ESCALATED _record_failure( task, TaskFailureKind.VALIDATOR_MISSING_EVIDENCE, "Evidence research completed without attaching a source-backed evidence packet.", ) emit( "task_escalated", " [yellow]Evidence preflight blocked mutation[/yellow] — packet is absent.", task_id=task.id, ) config.stats.tasks_failed += 1 if save_callback: save_callback() return if _requires_acceptance(task): try: if isolation == "worktree": with lock_ctx: branch_name, task_workdir = git.create_task_worktree( task.id, worktree_root, start_point=( git.task_branch_name(red_predecessor.id) if red_predecessor is not None else None ), ) task_git = GitManager(task_workdir) task_git.branch_namespace = plan.branch_namespace worktree_active = True emit( "info", f" [dim]Acceptance worktree: {branch_name} at {task_workdir}[/dim]", task_id=task.id, ) else: branch_name = _checkout_or_recreate_task_branch( git, task.id, start_point=( git.task_branch_name(red_predecessor.id) if red_predecessor is not None else None ), ) if red_predecessor is not None: branch_name = _ensure_red_predecessor_witnesses_in_branch( git, branch_name, task, plan, project_dir, start_point=git.task_branch_name(red_predecessor.id), ) emit("info", f" [dim]Acceptance branch: {branch_name}[/dim]", task_id=task.id) except RuntimeError as exc: task.status = TaskStatus.ESCALATED task.lifecycle_phase = TaskLifecyclePhase.ESCALATED _record_failure(task, TaskFailureKind.ACCEPTANCE_POLICY_REJECTED, str(exc)) emit( "task_escalated", f" [yellow]Acceptance preflight rejected[/yellow] — {exc}", task_id=task.id, ) config.stats.tasks_failed += 1 if save_callback: save_callback() return # A manual retry computes its own fresh RecoveryDecision every invocation # (see manual_retry.py) instead of relying on a previously-persisted # task.recovery_action -- ctx.recovery_decision, when injected, takes # precedence so the repair-route/context logic below stays fully shared. semantic_repair = ( recovery_decision.action is RecoveryAction.SEMANTIC_REPAIR if recovery_decision is not None else task.recovery_action is RecoveryAction.SEMANTIC_REPAIR ) repair_route = semantic_repair_route(config) if semantic_repair else None # Altitude routing: a task that failed lower on the ladder dispatches one step up; # a fresh task starts at the cheapest configured rung. altitude_route = config.route_for(current_altitude(task, config)) if not task.read_only else None if task.altitude: altitude_route = config.route_for(task.altitude) dispatch_route = ( repair_route or altitude_route or (config.route_for("researcher") if task.read_only else None) ) dispatch_role = "researcher" if task.read_only and not semantic_repair else "coder" repair_details = repair_context(task) if semantic_repair else "" task.status = TaskStatus.IN_PROGRESS task.lifecycle_phase = ( TaskLifecyclePhase.REPAIRING if semantic_repair else TaskLifecyclePhase.RESEARCHING if task.read_only else TaskLifecyclePhase.IMPLEMENTING ) if lease_seconds is not None: task.leased_at = datetime.now(timezone.utc) task.lease_expires_at = task.leased_at + timedelta(seconds=lease_seconds) task.lease_owner = lease_owner if git and not task.read_only and not _requires_acceptance(task): try: if isolation == "worktree": with lock_ctx: branch_name, task_workdir = git.create_task_worktree( task.id, worktree_root, start_point=( git.task_branch_name(red_predecessor.id) if red_predecessor is not None else None ), ) task_git = GitManager(task_workdir) task_git.branch_namespace = plan.branch_namespace worktree_active = True emit( "info", f" [dim]Worktree: {branch_name} at {task_workdir}[/dim]", task_id=task.id, ) else: # Use the resume-aware helper (see _checkout_or_recreate_task_branch's # docstring for the resume/discard contract): this task may be # getting a fresh attempt within THIS pass, but still have a # branch left behind by an earlier failed attempt (discard_ # branch_on_failure defaults to False) from a prior invocation # or an earlier pass in this same --auto-resume run. branch_name = _checkout_or_recreate_task_branch( git, task.id, start_point=( git.task_branch_name(red_predecessor.id) if red_predecessor is not None else None ), ) if red_predecessor is not None: branch_name = _ensure_red_predecessor_witnesses_in_branch( git, branch_name, task, plan, project_dir, start_point=git.task_branch_name(red_predecessor.id), ) emit("info", f" [dim]Branch: {branch_name}[/dim]", task_id=task.id) except RuntimeError as e: emit("warning", f" [yellow]{e}[/yellow]", task_id=task.id) # A local discovery checkpoint must describe the exact source tree the # coder will see. For isolated tasks that is the prepared branch/worktree, # not the shared primary checkout (which may advance through sibling merges). _attach_current_discovery_checkpoint(task, plan, config, task_workdir) if task.discovery_contract is not None and not task.discovery_checkpoint_fingerprint: if not _run_discovery_for_missing_checkpoint( task=task, plan=plan, config=config, project_dir=task_workdir, save_callback=save_callback, ): config.stats.tasks_failed += 1 return attempt_context = assemble_task_context( task=task, plan=plan, config=config, cortex=cortex, project_dir=task_workdir, ) if semantic_repair: task.recovery_action = RecoveryAction.NONE if validate_existing: # No new coder attempt is being made -- re-validate a retained branch's # already-present (uncommitted) changes instead. Deliberately never # constructs a Worker at all. Matches manual_retry.py's original # validate_existing contract exactly, including that these two early # refusals leave task.status untouched (harmless: IN_PROGRESS is never # persisted here, and the CLI process exits right after) rather than # escalating -- this is a pre-existing, narrow edge case (passing # --validate-existing for a task with no acceptance profile or no # retained branch), not something this refactor should start treating # differently. if not _supports_validate_existing(task) or git is None or branch_name is None: emit( "warning", "[red]--validate-existing requires a retained acceptance-profile or red-regression task branch.[/red]", task_id=task.id, ) return review_files = git.worktree_files() if not review_files: emit( "warning", "[red]No retained task-branch changes are available for validation.[/red]", task_id=task.id, ) return task.files_created = review_files status = TaskStatus.PASSED summary = "Validating retained branch changes without starting a new coder." worker_failure = None else: worker = Worker( config, cortex, task_workdir, hitl_mode=hitl_mode, project_name=plan.project_name, lint_mode=lint_mode, ) if hasattr(worker, "set_task_context"): worker.set_task_context(attempt_context.content) start_agent_attempt( task, config, role=dispatch_role, selection_reason=( ("manual_semantic_repair" if semantic_repair else "manual_retry") if recovery_decision is not None else ( "semantic_validator_repair" if semantic_repair else "post_research_implementation" if resumed_research else "initial_task_execution" ) ), route_override=dispatch_route, context_source_ids=attempt_context.source_ids, context_characters=attempt_context.character_count, context_token_estimate=attempt_context.token_estimate, ) if save_callback: save_callback() with use_coder_route(config, dispatch_route): if repair_details and not hasattr(worker, "set_task_context"): status, summary, files = worker.execute_task( task, recovery_context=repair_details, ) else: status, summary, files = worker.execute_task(task) if task.attempts: task.attempts[-1].tool_name_counts = dict(getattr(worker, "last_tool_name_counts", {})) task.attempts[-1].verification_events.extend( getattr(worker, "last_verification_events", []) ) review_files = _review_files_from_worktree( task_workdir, task_git, files or task.files_created, ) task.files_created = review_files # The worker's own summary is evidence for the altitude above (kept on the # attempt); it is never written into shared memory the reflector could # promote into every later worker's prompt. worker_failure = getattr(worker, "last_failure_kind", None) or classify_worker_failure( status, summary ) if worker_failure_should_escalate(status, worker_failure, plan.recovery.mode): _record_failure(task, worker_failure or TaskFailureKind.WORKER_FAILED, summary) task.status = TaskStatus.ESCALATED task.lifecycle_phase = TaskLifecyclePhase.ESCALATED finish_agent_attempt( task, config, outcome_status=TaskStatus.ESCALATED, failure_kind=task.failure_kind, outcome_summary=summary, ) if is_transient_provider_failure(worker_failure): emit( "task_escalated", " [yellow]Provider unavailable[/yellow] — task paused without using " "an implementation retry. Restore provider access, then run " f"'afk retry {plan.project_name} {task.id}'.", task_id=task.id, ) else: emit( "task_escalated", f" [yellow]Task ESCALATED[/yellow] — {summary[:200]}", task_id=task.id, ) config.stats.tasks_failed += 1 if save_callback: save_callback() return if task.read_only: task.status = status task.lifecycle_phase = TaskLifecyclePhase.DETERMINISTIC_REVIEW safe_summary = summary[:500].encode("ascii", "replace").decode("ascii") emit("info", f" [cyan]Analysis:[/cyan] {safe_summary}", task_id=task.id) if task.status == TaskStatus.PASSED: review = review_task( project_dir, linter, test_framework, apply_format=False, lint_mode=lint_mode, lint_baseline=lint_baseline, **_review_environment_kwargs(config), **_scoped_test_review_kwargs(task), **_required_artifact_review_kwargs(task), diagnostic_dir=_review_diagnostic_dir(config, plan, task), ) _attach_review_command_evidence(task, review) _apply_contract_command(task, review, project_dir, config) if not review.passed: if _read_only_failure_is_baseline_only(review): emit( "info", " [yellow]Baseline not green[/yellow] (recorded, not charged to this " f"read-only task) — Tests: {'PASS' if review.tests_passed else 'FAIL'}, " f"Lint: {_lint_label(review)}", task_id=task.id, ) else: task.status = TaskStatus.FAILED _record_failure( task, classify_review_failure(review) or TaskFailureKind.REVIEW_REJECTED, review.summary, ) emit( "task_failed", " [yellow]Baseline validation FAILED[/yellow] — " f"Tests: {'PASS' if review.tests_passed else 'FAIL'}, " f"Lint: {_lint_label(review)}", task_id=task.id, ) if task.status == TaskStatus.PASSED: _clear_failure(task) task.lifecycle_phase = TaskLifecyclePhase.PASSED config.stats.tasks_completed += 1 finding = write_finding_from_research( task=task, plan=plan, config=config, project_dir=project_dir, worker_summary=summary, ) if finding is not None: emit( "info", f" [dim]Finding recorded by {finding.author_role}: {finding.one_line()[:200]}[/dim]", task_id=task.id, ) else: if worker_failure: _record_failure(task, worker_failure, summary) if task.retry_count < task.max_retries: task.retry_count += 1 # Never retry sideways: the next attempt runs one altitude up or not at all. ladder_exhausted = escalate_altitude(task, config) is None if ladder_exhausted or task.retry_count >= task.max_retries: if ladder_exhausted: _record_failure( task, TaskFailureKind.ALTITUDE_EXHAUSTED, f"No altitude above {current_altitude(task, config)} remains; human decision " f"required. Last failure: {task.failure_detail}", ) task.status = TaskStatus.ESCALATED task.lifecycle_phase = TaskLifecyclePhase.ESCALATED emit( "task_escalated", f" [yellow]Task ESCALATED[/yellow] after {task.retry_count} retries — " f"{(task.failure_detail or summary)[:200]}", task_id=task.id, ) _trip_breaker(task, plan, config, project_dir, review_files=[]) config.stats.tasks_failed += 1 finish_agent_attempt( task, config, outcome_status=task.status, failure_kind=task.failure_kind, outcome_summary=task.failure_detail or summary, ) if save_callback: save_callback() return task.lifecycle_phase = TaskLifecyclePhase.DETERMINISTIC_REVIEW review = review_task( task_workdir, linter, test_framework, files_changed=review_files, lint_mode=lint_mode, lint_baseline=lint_baseline, **_review_environment_kwargs(config), max_changed_files=task.max_changed_files, max_changed_lines=task.max_changed_lines, require_raw_contract_artifacts=task.require_raw_contract_artifacts, **_red_regression_review_kwargs(task), **_scoped_test_review_kwargs(task), **_required_artifact_review_kwargs(task), reported_files=None if validate_existing else files, diagnostic_dir=_review_diagnostic_dir(config, plan, task), ) _attach_review_command_evidence(task, review) if ( not validate_existing and task.mechanical_rereviews_used == 0 and _ownership_failure_is_mechanically_recoverable(review) ): rereview = _quarantine_scratch_and_rereview( task=task, plan=plan, config=config, project_dir=task_workdir, linter=linter, test_framework=test_framework, review_files=review_files, reported_files=files, lint_mode=lint_mode, lint_baseline=lint_baseline, save_callback=save_callback, ) if rereview is not None: review = rereview _apply_contract_command(task, review, task_workdir, config) red_regression_ok, red_regression_summary = _verify_red_regression_contract( task, task_workdir, test_framework, review_files ) if not red_regression_ok: review.passed = False review.tests_passed = False review.summary = red_regression_summary review.test_output = "" predecessor_files_ok, predecessor_files_summary = _verify_red_regression_predecessor_files( task, plan, task_workdir ) if not predecessor_files_ok: review.passed = False review.tests_passed = False review.summary = predecessor_files_summary if status == TaskStatus.PASSED and review.passed: finish_agent_attempt( task, config, outcome_status=TaskStatus.PASSED, failure_kind=None, outcome_summary=summary, ) if _requires_acceptance(task): acceptance_context = assemble_task_context( task=task, plan=plan, config=config, cortex=cortex, ) acceptance = _run_acceptance_gate( task=task, config=config, project_dir=task_workdir, review=review, save_callback=save_callback, task_context=acceptance_context.content, context_source_ids=acceptance_context.source_ids, context_characters=acceptance_context.character_count, context_token_estimate=acceptance_context.token_estimate, project_name=plan.project_name, ) if acceptance.passed: task.status = TaskStatus.PASSED _clear_failure(task) task.lifecycle_phase = TaskLifecyclePhase.PASSED emit( "task_passed", " [green]Acceptance PASSED[/green] — " f"{acceptance.summary[:200].encode('ascii', 'replace').decode('ascii')}", task_id=task.id, ) else: _handle_acceptance_failure( task=task, plan=plan, acceptance=acceptance, save_callback=save_callback, ) else: task.status = TaskStatus.PASSED _clear_failure(task) task.lifecycle_phase = TaskLifecyclePhase.PASSED emit( "task_passed", f" [green]Review PASSED[/green] — {summary[:200].encode('ascii', 'replace').decode('ascii')}", task_id=task.id, ) else: failure_kind = ( worker_failure or classify_review_failure(review) or TaskFailureKind.WORKER_FAILED ) failure_detail = summary if worker_failure else _review_failure_detail(review) repeated_failure = _record_deterministic_failure( task, failure_kind, failure_detail, task_workdir, review_files, ) finish_agent_attempt( task, config, outcome_status=TaskStatus.FAILED, failure_kind=failure_kind, outcome_summary=failure_detail, ) if ( not manual_dispatch and not task.red_regression_test_files and task.retry_count < task.max_retries and review.scope_passed and review.artifact_contract_passed and not repeated_failure and (retry_altitude := next_altitude(current_altitude(task, config), read_only=False)) is not None ): task.retry_count += 1 task.status = TaskStatus.RETRYING task.lifecycle_phase = TaskLifecyclePhase.REPAIRING # Breaker direction: the retry runs one altitude up, with the review log attached # via the deterministic-review context section, never sideways on the same route. task.altitude = retry_altitude retry_route = config.route_for(retry_altitude) emit( "task_failed", f" [yellow]Review FAILED[/yellow] (attempt {task.retry_count}/{task.max_retries}, " f"escalating to {retry_altitude})\n" f" Tests: {'PASS' if review.tests_passed else 'FAIL'}, " f"Lint: {_lint_label(review)}", task_id=task.id, ) retry_context = assemble_task_context( task=task, plan=plan, config=config, cortex=cortex, project_dir=task_workdir, ) if hasattr(worker, "set_task_context"): worker.set_task_context(retry_context.content) start_agent_attempt( task, config, role="coder", selection_reason="deterministic_review_retry", route_override=retry_route, context_source_ids=retry_context.source_ids, context_characters=retry_context.character_count, context_token_estimate=retry_context.token_estimate, ) if save_callback: save_callback() with use_coder_route(config, retry_route): status2, summary2, files2 = worker.execute_task(task) if task.attempts: task.attempts[-1].tool_name_counts = dict( getattr(worker, "last_tool_name_counts", {}) ) task.attempts[-1].verification_events.extend( getattr(worker, "last_verification_events", []) ) retry_review_files = _review_files_from_worktree( task_workdir, task_git, files2 or task.files_created, ) task.files_created = retry_review_files retry_worker_failure = getattr( worker, "last_failure_kind", None ) or classify_worker_failure(status2, summary2) if worker_failure_should_escalate(status2, retry_worker_failure, plan.recovery.mode): _record_failure( task, retry_worker_failure or TaskFailureKind.WORKER_FAILED, summary2, ) task.status = TaskStatus.ESCALATED task.lifecycle_phase = TaskLifecyclePhase.ESCALATED finish_agent_attempt( task, config, outcome_status=TaskStatus.ESCALATED, failure_kind=task.failure_kind, outcome_summary=summary2, ) emit( "task_escalated", " [yellow]Retry paused for provider recovery[/yellow] — " "the retry budget was not decremented again.", task_id=task.id, ) config.stats.tasks_failed += 1 if save_callback: save_callback() return retry_review = review_task( task_workdir, linter, test_framework, files_changed=retry_review_files, lint_mode=lint_mode, lint_baseline=lint_baseline, **_review_environment_kwargs(config), max_changed_files=task.max_changed_files, max_changed_lines=task.max_changed_lines, require_raw_contract_artifacts=task.require_raw_contract_artifacts, reported_files=files2, **_scoped_test_review_kwargs(task), **_required_artifact_review_kwargs(task), diagnostic_dir=_review_diagnostic_dir(config, plan, task), ) _attach_review_command_evidence(task, retry_review) _apply_contract_command(task, retry_review, task_workdir, config) if status2 == TaskStatus.PASSED and retry_review.passed: finish_agent_attempt( task, config, outcome_status=TaskStatus.PASSED, failure_kind=None, outcome_summary=summary2, ) if _requires_acceptance(task): acceptance_context = assemble_task_context( task=task, plan=plan, config=config, cortex=cortex, ) acceptance = _run_acceptance_gate( task=task, config=config, project_dir=task_workdir, review=retry_review, save_callback=save_callback, task_context=acceptance_context.content, context_source_ids=acceptance_context.source_ids, context_characters=acceptance_context.character_count, context_token_estimate=acceptance_context.token_estimate, project_name=plan.project_name, ) if acceptance.passed: task.status = TaskStatus.PASSED _clear_failure(task) task.lifecycle_phase = TaskLifecyclePhase.PASSED emit( "task_passed", " [green]Retry acceptance PASSED[/green] — " f"{acceptance.summary[:200].encode('ascii', 'replace').decode('ascii')}", task_id=task.id, ) else: _handle_acceptance_failure( task=task, plan=plan, acceptance=acceptance, save_callback=save_callback, ) else: task.status = TaskStatus.PASSED _clear_failure(task) task.lifecycle_phase = TaskLifecyclePhase.PASSED emit( "task_passed", f" [green]Retry review PASSED[/green] — " f"{summary2[:200].encode('ascii', 'replace').decode('ascii')}", task_id=task.id, ) else: retry_review_failure = classify_review_failure(retry_review) retry_failure = ( retry_review_failure or retry_worker_failure or TaskFailureKind.WORKER_FAILED ) retry_failure_detail = ( _review_failure_detail(retry_review) if retry_review_failure else summary2 ) repeated_retry = _record_deterministic_failure( task, retry_failure, retry_failure_detail, task_workdir, retry_review_files, ) if repeated_retry: task.status = TaskStatus.ESCALATED task.lifecycle_phase = TaskLifecyclePhase.ESCALATED _record_failure( task, TaskFailureKind.REPEATED_FAILURE, "Automatic repair reproduced the same deterministic failure without " "changed files or evidence.", ) elif escalate_altitude(task, config) is None: task.status = TaskStatus.ESCALATED task.lifecycle_phase = TaskLifecyclePhase.ESCALATED _record_failure( task, TaskFailureKind.ALTITUDE_EXHAUSTED, f"No altitude above {current_altitude(task, config)} remains; human decision " f"required. Last failure: {retry_failure.value}: {retry_failure_detail}", ) else: task.status = TaskStatus.FAILED task.lifecycle_phase = TaskLifecyclePhase.DETERMINISTIC_REVIEW finish_agent_attempt( task, config, outcome_status=task.status, failure_kind=task.failure_kind, outcome_summary=task.failure_detail, ) if task.status is TaskStatus.ESCALATED: _trip_breaker(task, plan, config, task_workdir, retry_review_files) if repeated_retry: emit( "task_escalated", " [red]Retry stopped[/red] — the repair reproduced the same failure " "without changed files or evidence.", task_id=task.id, ) else: emit( "task_failed", " [red]Retry review FAILED[/red] — " f"Tests: {'PASS' if retry_review.tests_passed else 'FAIL'}, " f"Lint: {_lint_label(retry_review)}", task_id=task.id, ) else: decomposed = False if repeated_failure and not manual_dispatch: task.status = TaskStatus.ESCALATED task.lifecycle_phase = TaskLifecyclePhase.ESCALATED _record_failure( task, TaskFailureKind.REPEATED_FAILURE, "Automatic execution reproduced a prior deterministic failure without " "changed files or evidence.", ) emit( "task_escalated", " [red]Task ESCALATED[/red] — deterministic failure repeated without " "changed files or evidence.", task_id=task.id, ) _trip_breaker(task, plan, config, task_workdir, review_files) elif not manual_dispatch and review.scope_passed and review.artifact_contract_passed: decomposed = _maybe_decompose_task( task=task, plan=plan, config=config, save_callback=save_callback, ) if repeated_failure and not manual_dispatch: pass elif decomposed: if task.status is TaskStatus.ESCALATED and any( proposal.parent_task_id == task.id and proposal.status.value == "pending" for proposal in plan.foreman_proposals ): from afk_developer.scheduler.supervisor_coordinator import ( SupervisorDecisionCoordinator, ) SupervisorDecisionCoordinator(config, plan).run_once( save_callback=save_callback ) if task.status is TaskStatus.DECOMPOSED: emit( "task_decomposed", f" [cyan]Task DECOMPOSED[/cyan] into {len(task.subtask_ids)} " f"subtasks after {task.max_retries} failures", task_id=task.id, ) else: emit( "task_escalated", " [yellow]Foreman proposal awaiting supervisor approval[/yellow]", task_id=task.id, ) elif should_bypass_immediate_escalation(failure_kind, plan.recovery.mode) and ( manual_dispatch or escalate_altitude(task, config) is not None ): # Mirrors the same bypass already applied to worker failures above: # a rejection like VERIFICATION_POLICY_REJECTED is just as often a # benign, retry-fixable mistake when it surfaces via deterministic # review instead of the worker's own run -- stay retriable under # bounded recovery rather than always hard-escalating, but the next # attempt runs one altitude up (escalate_altitude above), never sideways. # failure_kind/failure_detail were already set by _record_failure above. task.status = TaskStatus.FAILED emit( "task_failed", f" [yellow]Review FAILED[/yellow] (bounded recovery: staying " f"retriable at {current_altitude(task, config)}) after {task.max_retries} failures", task_id=task.id, ) else: task.status = TaskStatus.ESCALATED task.lifecycle_phase = TaskLifecyclePhase.ESCALATED if not review.scope_passed or not review.artifact_contract_passed: emit( "task_escalated", " [red]Task ESCALATED[/red] — mutation guard rejected the " "first implementation attempt.", task_id=task.id, ) else: emit( "task_escalated", f" [red]Task ESCALATED[/red] after {task.max_retries} failures", task_id=task.id, ) if not manual_dispatch: _trip_breaker(task, plan, config, task_workdir, review_files) if task.status == TaskStatus.PASSED: if task.product_validation is not None and ( task.product_validation.status is ProductValidationStatus.NOT_REQUESTED ): task.product_validation.status = ProductValidationStatus.AWAITING_HUMAN task.product_validation.requested_at = datetime.now(timezone.utc) task.status = TaskStatus.BLOCKED task.lifecycle_phase = TaskLifecyclePhase.PRODUCT_VALIDATION task.blocked_reason = ( f"Awaiting human {task.product_validation.kind} validation: " f"{task.product_validation.instructions}" ) emit( "task_blocked", " [yellow]Deterministic checks passed; awaiting human product validation[/yellow] — " f"{task.product_validation.kind}.", task_id=task.id, human_validation=True, artifact_paths=list(task.product_validation.artifact_paths), ) if save_callback: save_callback() return finalize_worktree_path = task_workdir if worktree_active else None red_successor = _red_regression_successor(task, plan) finalization_failure: tuple[TaskFailureKind, str] | None = None environment_refresh_failure = "" if task.red_regression_test_files and red_successor is not None: # Commit and retain the intentionally-red branch. Its sole dependent # implementation task starts from this commit and is the only task # allowed to merge the tests into main once the complete suite is green. finalized = ( task_git is None or not task_git.has_changes() or task_git.commit_changes(f"AFK: {task.title} [{task.id}]") ) if finalized: emit( "merge", " [dim]Retained red regression branch for its dependent implementation; " "it will not merge independently.[/dim]", task_id=task.id, ) else: with lock_ctx: finalized = _finalize_task_branch( git, branch_name, task, commit_git=task_git, worktree_path=finalize_worktree_path, ) if finalized and git is not None: expected_primary_artifacts = _primary_artifact_paths(task, red_predecessor) if expected_primary_artifacts and not git.primary_contains_files( expected_primary_artifacts ): finalized = False finalization_failure = ( TaskFailureKind.REQUIRED_ARTIFACT_MISSING, "Primary branch is missing declared task artifacts after merge: " f"{expected_primary_artifacts}.", ) emit( "merge", " [red]Primary branch is missing declared task artifacts after merge.[/red]", task_id=task.id, ) elif finalized: environment_refresh_failure = _refresh_environment_contract_after_merge( plan=plan, config=config, task=task, project_dir=project_dir, git=git, ) if environment_refresh_failure: task.status = TaskStatus.ESCALATED task.lifecycle_phase = TaskLifecyclePhase.ESCALATED branch_name = None _record_failure( task, TaskFailureKind.ENVIRONMENT_CONTRACT_FAILED, environment_refresh_failure, ) emit( "task_escalated", " [red]Merged task could not establish its resulting environment contract.[/red]", task_id=task.id, ) elif not finalized: if ( git is not None and branch_name is not None and (task.merge_conflict_retries_remaining > 0) ): task.merge_conflict_retries_remaining -= 1 task.status = TaskStatus.RETRYING if task.retry_count else TaskStatus.PENDING task.lifecycle_phase = TaskLifecyclePhase.IMPLEMENTING _record_failure( task, *( finalization_failure or ( TaskFailureKind.WORKER_FAILED, f"Merge conflict finalizing branch {branch_name} against the current " "primary branch (likely a concurrent worker merged first). Retrying " "once from a fresh branch against the latest primary tip.", ) ), ) with lock_ctx: if worktree_active: if task_git is not None and task_git is not git: task_git.repo.close() git.discard_task_worktree(finalize_worktree_path, branch_name) else: git.discard_task_branch(branch_name) emit( "merge", f" [yellow]Merge conflict on {branch_name}[/yellow] — retrying once " "against the latest primary branch.", task_id=task.id, ) else: task.status = TaskStatus.ESCALATED task.lifecycle_phase = TaskLifecyclePhase.ESCALATED _record_failure( task, TaskFailureKind.WORKER_FAILED, f"Could not finalize task branch {branch_name}.", ) elif task.parent_task_id: _rollup_decomposed_parent( plan, task, config=config, project_dir=project_dir, linter=linter, test_framework=test_framework, lint_mode=lint_mode, lint_baseline=lint_baseline, save_callback=save_callback, ) elif red_predecessor is not None and git is not None: # The implementation branch now contains the predecessor's committed # red tests and has passed normal (non-excluded) review, so it is safe # to remove the staging worktree and branch after the atomic merge. retained_branch = git.task_branch_name(red_predecessor.id) retained_worktree = git.worktree_path_for(red_predecessor.id, worktree_root) with lock_ctx: git.remove_task_worktree(retained_worktree, force=True) git.delete_branch(retained_branch) if ( finalized and task.status is TaskStatus.PASSED and not task.read_only and not (task.red_regression_test_files and red_successor is not None) ): # Ratchet click: checkpoint the merged tree by content hash for loop detection. _record_click(task, plan, config, project_dir, git) if ( task.status in {TaskStatus.FAILED, TaskStatus.ESCALATED, TaskStatus.DECOMPOSED} and task.discard_branch_on_failure and git is not None and branch_name is not None ): if worktree_active and task_git is not None and task_git is not git: task_git.repo.close() with lock_ctx: discarded = ( git.discard_task_worktree(task_workdir, branch_name) if worktree_active else git.discard_task_branch(branch_name) ) if discarded: emit( "merge", " [dim]Discarded unaccepted task branch and restored a clean worktree.[/dim]", task_id=task.id, ) else: task.status = TaskStatus.ESCALATED task.lifecycle_phase = TaskLifecyclePhase.ESCALATED cleanup_detail = f"Could not clean failed task branch {branch_name}." if task.failure_kind is None: _record_failure(task, TaskFailureKind.WORKER_FAILED, cleanup_detail) else: primary_detail = task.failure_detail[:750].rstrip() task.failure_detail = ( f"{primary_detail}\n\nCleanup also failed: {cleanup_detail}" if primary_detail else f"Cleanup also failed: {cleanup_detail}" )[:1000] if task.status == TaskStatus.PASSED: config.stats.tasks_completed += 1 elif task.status not in {TaskStatus.DECOMPOSED, TaskStatus.BLOCKED}: config.stats.tasks_failed += 1 if save_callback: save_callback() def _lint_label(review) -> str: if review.lint_mode == LintMode.BASELINE.value: if not review.baseline_loaded: return "FAIL (baseline unavailable)" state = "PASS" if review.lint_passed else "FAIL" return ( f"{state} (baseline: {review.baseline_diagnostic_count} existing, " f"{review.introduced_diagnostic_count} introduced)" ) return "PASS (strict)" if review.lint_passed else "FAIL (strict)"