"""Pure, typed supervisor plan amendments. This module deliberately has no Click, persistence, or campaign-store dependencies. """ from __future__ import annotations from collections import Counter from datetime import datetime, timezone from afk_developer.planner.task_model import ( ForemanDecompositionProposal, ForemanProposalStatus, SupervisorAmendment, TaskContractSnapshot, TaskLifecyclePhase, TaskNode, TaskPlan, TaskStatus, ) class SupervisorAmendmentError(ValueError): """Raised before a plan amendment can be persisted.""" def mark_task_verified(plan: TaskPlan, target_task_id: str, reason: str) -> TaskPlan: """Record a supervisor's direct verification of an eligible task. The original attempts stay intact. This operation only records a human decision backed by independently performed deterministic checks; it does not manufacture a worker attempt or discard the escalation history. """ if not reason.strip(): raise SupervisorAmendmentError("A non-empty supervisor reason is required.") amended = plan.model_copy(deep=True) target = next((task for task in amended.tasks if task.id == target_task_id), None) if target is None: raise SupervisorAmendmentError(f"Unknown target task: {target_task_id}") eligible_statuses = {TaskStatus.PENDING, TaskStatus.FAILED, TaskStatus.ESCALATED} is_completed_decomposition = target.status is TaskStatus.DECOMPOSED and _all_subtasks_passed( amended, target ) if target.status not in eligible_statuses and not is_completed_decomposition: raise SupervisorAmendmentError( "Only a pending, failed, or escalated task may be directly verified; a decomposed task may " "be reconciled only after every subtask has passed." ) if ( is_completed_decomposition and amended.recovery.require_supervisor_parent_coherence and ( target.parent_coherence_evidence is None or not target.parent_coherence_evidence.passed ) ): raise SupervisorAmendmentError( "A decomposed task requires passing deterministic post-merge coherence evidence before " "supervisor acceptance." ) before = TaskContractSnapshot.from_task(target) target.status = TaskStatus.PASSED target.lifecycle_phase = TaskLifecyclePhase.PASSED target.blocked_reason = "" target.failure_kind = None target.failure_detail = "" target.leased_at = None target.lease_expires_at = None target.lease_owner = "" amended.supervisor_amendments.append( SupervisorAmendment( reason=reason.strip(), operation="mark_task_verified", target_task_ids=[target.id], before=[before], after=[TaskContractSnapshot.from_task(target)], ) ) return amended def approve_foreman_proposal(plan: TaskPlan, proposal_id: str, reason: str) -> TaskPlan: """Apply a pending foreman split after a supervisor validates its coverage.""" if not reason.strip(): raise SupervisorAmendmentError("A non-empty supervisor reason is required.") amended = plan.model_copy(deep=True) proposal = _find_foreman_proposal(amended, proposal_id) if proposal.status is not ForemanProposalStatus.PENDING: raise SupervisorAmendmentError("Only a pending foreman proposal may be approved.") parent = _find_task(amended, proposal.parent_task_id) if parent.status is not TaskStatus.ESCALATED: raise SupervisorAmendmentError("The proposed parent must still be escalated.") if parent.subtask_ids: raise SupervisorAmendmentError("The proposed parent already has an applied subtask set.") proposed_ids = [child.id for child in proposal.subtasks] if set(proposed_ids) & {task.id for task in amended.tasks}: raise SupervisorAmendmentError("Foreman proposal child IDs must be new.") before = TaskContractSnapshot.from_task(parent) children = build_foreman_children(parent, proposal) parent.subtask_ids = proposed_ids parent.status = TaskStatus.DECOMPOSED parent.lifecycle_phase = TaskLifecyclePhase.DECOMPOSED parent.blocked_reason = "" proposal.status = ForemanProposalStatus.APPROVED proposal.supervisor_reason = reason.strip() proposal.decided_at = datetime.now(timezone.utc) amended.decompositions_used += 1 amended.tasks.extend(children) amended.supervisor_amendments.append( SupervisorAmendment( reason=reason.strip(), operation="approve_foreman_proposal", target_task_ids=[parent.id], before=[before], after=[ TaskContractSnapshot.from_task(parent), *map(TaskContractSnapshot.from_task, children), ], replacement_task_ids=proposed_ids, ) ) return amended def build_foreman_children( parent: TaskNode, proposal: ForemanDecompositionProposal ) -> list[TaskNode]: """Validate exact contract ownership and materialize runnable child tasks.""" required_coverage = parent_contract_items(parent) coverage_counts = Counter(item for child in proposal.subtasks for item in child.covers) proposed_coverage = set(coverage_counts) unknown_coverage = proposed_coverage - required_coverage missing_coverage = required_coverage - proposed_coverage duplicate_coverage = sorted(item for item, count in coverage_counts.items() if count > 1) if unknown_coverage or missing_coverage or duplicate_coverage: raise SupervisorAmendmentError( "Foreman proposal coverage must assign every parent contract item exactly once; " f"missing={sorted(missing_coverage)}, unknown={sorted(unknown_coverage)}, " f"duplicates={duplicate_coverage}." ) return [ TaskNode( id=child.id, title=child.title, description=child.description, # Children start at the cheapest rung on purpose: a smaller contract is what # makes the cheap model viable again. They need their own hypothesis/contract # because the parent's cannot be split. hypothesis=child.hypothesis or parent.hypothesis, contract_command=child.contract_command, dependencies=list(dict.fromkeys([*parent.dependencies, *child.depends_on])), evidence_gated_by=list(parent.evidence_gated_by), accepts_not_applicable_dependencies=parent.accepts_not_applicable_dependencies, estimated_effort=parent.estimated_effort, priority=parent.priority, read_only=parent.read_only, assigned_to=parent.assigned_to, max_retries=parent.max_retries, required_artifacts=_covered_values(child.covers, "artifact:"), red_regression_test_files=_covered_values(child.covers, "red-test:"), disallow_unscoped_pytest=parent.disallow_unscoped_pytest, acceptance_criteria=( _covered_values(child.covers, "criterion:") or [child.description] ), evidence_roots=list(parent.evidence_roots), max_changed_files=parent.max_changed_files, max_changed_lines=parent.max_changed_lines, require_raw_contract_artifacts=parent.require_raw_contract_artifacts, discard_branch_on_failure=parent.discard_branch_on_failure, acceptance_profile=parent.acceptance_profile, parent_task_id=parent.id, decomposition_depth=parent.decomposition_depth + 1, terra_stall_retries_remaining=parent.terra_stall_retries_remaining, ) for child in proposal.subtasks ] def reject_foreman_proposal(plan: TaskPlan, proposal_id: str, reason: str) -> TaskPlan: """Record a supervisor rejection without changing the runnable queue.""" if not reason.strip(): raise SupervisorAmendmentError("A non-empty supervisor reason is required.") amended = plan.model_copy(deep=True) proposal = _find_foreman_proposal(amended, proposal_id) if proposal.status is not ForemanProposalStatus.PENDING: raise SupervisorAmendmentError("Only a pending foreman proposal may be rejected.") proposal.status = ForemanProposalStatus.REJECTED proposal.supervisor_reason = reason.strip() proposal.decided_at = datetime.now(timezone.utc) amended.supervisor_amendments.append( SupervisorAmendment( reason=reason.strip(), operation="reject_foreman_proposal", target_task_ids=[proposal.parent_task_id], ) ) return amended def _find_foreman_proposal(plan: TaskPlan, proposal_id: str) -> ForemanDecompositionProposal: proposal = next((item for item in plan.foreman_proposals if item.id == proposal_id), None) if proposal is None: raise SupervisorAmendmentError(f"Unknown foreman proposal: {proposal_id}") return proposal def _find_task(plan: TaskPlan, task_id: str) -> TaskNode: task = next((item for item in plan.tasks if item.id == task_id), None) if task is None: raise SupervisorAmendmentError(f"Unknown target task: {task_id}") return task def parent_contract_items(task: TaskNode) -> set[str]: criteria = task.acceptance_criteria or [task.description] return {f"criterion:{item}" for item in criteria} | { f"artifact:{path}" for path in task.required_artifacts } | { f"red-test:{path}" for path in task.red_regression_test_files } def _covered_values(coverage: list[str], prefix: str) -> list[str]: return [item.removeprefix(prefix) for item in coverage if item.startswith(prefix)] def _all_subtasks_passed(plan: TaskPlan, task: TaskNode) -> bool: """Return whether a decomposed task has a complete, passing replacement set.""" if not task.subtask_ids: return False tasks_by_id = {item.id: item for item in plan.tasks} return all( tasks_by_id.get(subtask_id) is not None and tasks_by_id[subtask_id].status is TaskStatus.PASSED for subtask_id in task.subtask_ids ) def replace_unstarted_phase_tasks( plan: TaskPlan, replacements: list[TaskNode], reason: str ) -> TaskPlan: """Retire an entirely unstarted queue and append a narrower replacement DAG. This is deliberately restricted to a pristine queue: it cannot hide or rewrite work that has started. Each retired task and the replacement DAG are preserved in the append-only supervisor amendment journal. """ if not reason.strip(): raise SupervisorAmendmentError("A non-empty supervisor reason is required.") if not replacements: raise SupervisorAmendmentError("At least one replacement task is required.") amended = plan.model_copy(deep=True) if any(task.status is not TaskStatus.PENDING or task.attempts for task in amended.tasks): raise SupervisorAmendmentError("Only an entirely unstarted task queue may be replaced.") original_ids = {task.id for task in amended.tasks} replacement_ids = [task.id for task in replacements] if len(set(replacement_ids)) != len(replacement_ids) or original_ids & set(replacement_ids): raise SupervisorAmendmentError("Replacement task IDs must be new and unique.") replacement_set = set(replacement_ids) for task in replacements: if set(task.dependencies) - replacement_set: raise SupervisorAmendmentError( f"Replacement {task.id} may depend only on replacement tasks." ) if task.status is not TaskStatus.PENDING or task.attempts or task.lease_owner: raise SupervisorAmendmentError( "Replacement specifications cannot supply runtime task state." ) _assert_acyclic(replacements) before = [TaskContractSnapshot.from_task(task) for task in amended.tasks] for task in amended.tasks: task.status = TaskStatus.NOT_APPLICABLE task.not_applicable_reason = reason.strip() amended.tasks.extend(replacements) amended.supervisor_amendments.append( SupervisorAmendment( reason=reason.strip(), operation="replace_unstarted_phase_tasks", target_task_ids=[task.id for task in before], before=before, after=[TaskContractSnapshot.from_task(task) for task in replacements], replacement_task_ids=replacement_ids, ) ) return amended def replace_task( plan: TaskPlan, target_task_id: str, replacements: list[TaskNode], reason: str ) -> TaskPlan: """Return an amended plan that retires one task and rewires its direct dependents.""" if not reason.strip(): raise SupervisorAmendmentError("A non-empty supervisor reason is required.") amended = plan.model_copy(deep=True) task_map = {task.id: task for task in amended.tasks} target = task_map.get(target_task_id) if target is None: raise SupervisorAmendmentError(f"Unknown target task: {target_task_id}") if target.status is TaskStatus.PASSED: raise SupervisorAmendmentError("A passed task cannot be replaced.") if target.status is TaskStatus.NOT_APPLICABLE: raise SupervisorAmendmentError("An already retired task cannot be replaced.") if not replacements: raise SupervisorAmendmentError("At least one replacement task is required.") replacement_ids = [task.id for task in replacements] if len(set(replacement_ids)) != len(replacement_ids) or set(replacement_ids) & set(task_map): raise SupervisorAmendmentError("Replacement task IDs must be new and unique.") replacement_set = set(replacement_ids) passed_ids = {task.id for task in amended.tasks if task.status is TaskStatus.PASSED} for task in replacements: forbidden = set(task.dependencies) - replacement_set - passed_ids if forbidden: raise SupervisorAmendmentError( f"Replacement {task.id} has dependencies that are not passed or replacements: {sorted(forbidden)}" ) if task.status is not TaskStatus.PENDING or task.attempts or task.lease_owner: raise SupervisorAmendmentError( "Replacement specifications cannot supply runtime task state." ) _assert_acyclic([*amended.tasks, *replacements]) terminals = [ task.id for task in replacements if not any(task.id in candidate.dependencies for candidate in replacements) ] downstream = [task for task in amended.tasks if target.id in task.dependencies] before = [ TaskContractSnapshot.from_task(target), *map(TaskContractSnapshot.from_task, downstream), ] target.status = TaskStatus.NOT_APPLICABLE target.not_applicable_reason = reason.strip() target.leased_at = None target.lease_expires_at = None target.lease_owner = "" for task in downstream: task.dependencies = [ dependency for dependency in task.dependencies if dependency != target.id ] task.dependencies.extend( terminal for terminal in terminals if terminal not in task.dependencies ) amended.tasks.extend(replacements) amended.supervisor_amendments.append( SupervisorAmendment( reason=reason.strip(), target_task_ids=[target.id], before=before, after=[ TaskContractSnapshot.from_task(target), *map(TaskContractSnapshot.from_task, replacements), ], replacement_task_ids=replacement_ids, affected_downstream_ids=[task.id for task in downstream], ) ) return amended def logical_task_count(plan: TaskPlan) -> int: """Count current logical tasks while retaining superseded nodes as history.""" retired_ids = { task_id for amendment in plan.supervisor_amendments if amendment.replacement_task_ids for task_id in amendment.target_task_ids } return len(plan.tasks) - len(retired_ids) def _assert_acyclic(tasks: list[TaskNode]) -> None: task_map = {task.id: task for task in tasks} visiting: set[str] = set() visited: set[str] = set() def visit(task_id: str) -> None: if task_id in visiting: raise SupervisorAmendmentError("Replacement would make the task plan cyclic.") if task_id in visited: return visiting.add(task_id) for dependency in task_map[task_id].dependencies: if dependency not in task_map: raise SupervisorAmendmentError( f"Task {task_id} references unknown dependency {dependency}." ) visit(dependency) visiting.remove(task_id) visited.add(task_id) for task in tasks: visit(task.id)