"""Pure deterministic validation for newly generated task plans.""" from __future__ import annotations from afk_developer.planner.task_model import PlanPreflightEvidence, TaskPlan def preflight_plan( plan: TaskPlan, *, maximum_task_count: int | None = None, require_executable_contracts: bool | None = None, ) -> PlanPreflightEvidence: """Check executable graph invariants without making semantic or model judgments. ``require_executable_contracts`` (default: the plan's own flag) refuses any task the planner could not attach a runnable acceptance test to; such a task goes up to a human instead of down to a worker. """ if require_executable_contracts is None: require_executable_contracts = plan.require_executable_contracts failures: list[str] = [] task_by_id = {task.id: task for task in plan.tasks} if not plan.tasks: failures.append("Plan must contain at least one task.") if maximum_task_count is not None and len(plan.tasks) > maximum_task_count: failures.append(f"Plan has {len(plan.tasks)} tasks; maximum is {maximum_task_count}.") for task in plan.tasks: if not task.id.strip() or not task.title.strip() or not task.description.strip(): failures.append( f"Task {task.id or ''} requires an ID, title, and description." ) if require_executable_contracts and not task.has_executable_contract(): failures.append( f"Task {task.id} has no executable acceptance test (contract_command, " "red_regression_test_files, acceptance profile, or a read-only hypothesis); " "the planner must write one or return the task to a human." ) unknown = sorted(set(task.dependencies) - task_by_id.keys()) if unknown: failures.append(f"Task {task.id} has unknown dependencies: {', '.join(unknown)}.") if task.red_regression_test_files: successors = [ candidate.id for candidate in plan.tasks if task.id in candidate.dependencies ] if len(successors) != 1: failures.append( f"Red-regression task {task.id} must have exactly one dependent implementation task; " f"found {len(successors)}." ) visiting: set[str] = set() visited: set[str] = set() def visit(task_id: str) -> None: if task_id in visited or task_id not in task_by_id: return if task_id in visiting: failures.append(f"Task dependency cycle includes {task_id}.") return visiting.add(task_id) for dependency in task_by_id[task_id].dependencies: visit(dependency) visiting.remove(task_id) visited.add(task_id) for task_id in task_by_id: visit(task_id) evidence = PlanPreflightEvidence( passed=not failures, task_count=len(plan.tasks), maximum_task_count=maximum_task_count, failures=failures, ) plan.preflight_evidence = evidence return evidence