from datetime import datetime, timezone from enum import Enum from pathlib import Path from typing import Any, Optional from uuid import uuid4 from pydantic import BaseModel, Field, field_validator, model_validator from afk_developer.recovery import RecoveryAction, RecoverySettings class TaskStatus(str, Enum): PENDING = "pending" CLAIMED = "claimed" IN_PROGRESS = "in_progress" PASSED = "passed" FAILED = "failed" RETRYING = "retrying" BLOCKED = "blocked" ESCALATED = "escalated" DECOMPOSED = "decomposed" NOT_APPLICABLE = "not_applicable" CANCELLED = "cancelled" class TaskFailureKind(str, Enum): """The originating layer for a non-passing task attempt.""" RESEARCH_INSUFFICIENT = "research_insufficient" RESEARCH_STALLED = "research_stalled" REPEATED_EVIDENCE = "repeated_evidence" REPEATED_FAILURE = "repeated_failure" RECOVERY_TOOL_FAILED = "recovery_tool_failed" COMMAND_POLICY_REJECTED = "command_policy_rejected" VERIFICATION_POLICY_REJECTED = "verification_policy_rejected" VERIFICATION_TOOL_FAILED = "verification_tool_failed" ACCEPTANCE_POLICY_REJECTED = "acceptance_policy_rejected" VALIDATOR_FINDINGS = "validator_findings" VALIDATOR_MISSING_EVIDENCE = "validator_missing_evidence" VALIDATOR_ERROR = "validator_error" PROVIDER_UNAVAILABLE = "provider_unavailable" PROVIDER_TIMEOUT = "provider_timeout" WORKER_FAILED = "worker_failed" DISCOVERY_PROGRESS_STALLED = "discovery_progress_stalled" TESTS_FAILED = "tests_failed" LINT_FAILED = "lint_failed" DIFF_CHECK_FAILED = "diff_check_failed" ENVIRONMENT_CONTRACT_FAILED = "environment_contract_failed" MUTATION_SCOPE_EXCEEDED = "mutation_scope_exceeded" REQUIRED_ARTIFACT_MISSING = "required_artifact_missing" REVIEW_REJECTED = "review_rejected" USER_ABORTED = "user_aborted" HYPOTHESIS_ALREADY_SCARRED = "hypothesis_already_scarred" HYPOTHESIS_MISSING = "hypothesis_missing" CAMPAIGN_CYCLE_DETECTED = "campaign_cycle_detected" ALTITUDE_EXHAUSTED = "altitude_exhausted" LEDGER_SCAR_BUDGET_EXCEEDED = "ledger_scar_budget_exceeded" CONTRACT_MISSING = "contract_missing" CONTRACT_FAILED = "contract_failed" BUDGET_EXHAUSTED = "budget_exhausted" class AcceptanceProfile(str, Enum): """Human-approved validation profile for a high-risk task.""" NONE = "none" CORPUS_RAW_OUTPUT = "corpus_raw_output" API_COMPATIBILITY = "api_compatibility" MIGRATION = "migration" SECURITY = "security" DEPLOYMENT = "deployment" ENABLED_ACCEPTANCE_PROFILES = frozenset( { AcceptanceProfile.NONE, AcceptanceProfile.CORPUS_RAW_OUTPUT, } ) class TaskLifecyclePhase(str, Enum): """Durable recovery state, separate from the externally visible task status.""" PLANNED = "planned" RESEARCHING = "researching" READY_TO_IMPLEMENT = "ready_to_implement" IMPLEMENTING = "implementing" DETERMINISTIC_REVIEW = "deterministic_review" VALIDATING = "validating" REPAIRING = "repairing" PASSED = "passed" ESCALATED = "escalated" DECOMPOSED = "decomposed" NOT_APPLICABLE = "not_applicable" PRODUCT_VALIDATION = "product_validation" class ProductValidationStatus(str, Enum): NOT_REQUESTED = "not_requested" AWAITING_HUMAN = "awaiting_human" ATTESTED = "attested" class ProductValidationCheckpoint(BaseModel): """Human-only validation after deterministic engineering checks pass.""" kind: str = Field(min_length=1, max_length=80) instructions: str = Field(min_length=1, max_length=4_000) artifact_paths: list[str] = Field(default_factory=list, max_length=30) status: ProductValidationStatus = ProductValidationStatus.NOT_REQUESTED requested_at: datetime | None = None attested_at: datetime | None = None observation: str = Field(default="", max_length=4_000) artifact_sha256: dict[str, str] = Field(default_factory=dict) @field_validator("artifact_paths") @classmethod def _require_safe_artifact_paths(cls, values: list[str]) -> list[str]: if len(values) != len(set(values)): raise ValueError("product validation artifact paths must be unique") for path in values: candidate = Path(path) if not path or candidate.is_absolute() or ".." in candidate.parts or "\\" in path: raise ValueError("product validation artifact paths must be safe project-relative paths") return values class DiscoveryContract(BaseModel): """Explicit local facts a task may cache after bounded discovery. A shared ``cache_key`` is intentional: it is the only supported way for sibling tasks to reuse a checkpoint. Similar-looking task prose is never enough to select cached context. """ questions: list[str] = Field(min_length=1, max_length=20) input_paths: list[str] = Field(min_length=1, max_length=100) allowed_output_paths: list[str] = Field(min_length=1, max_length=100) exclusions: list[str] = Field(default_factory=list, max_length=50) cache_key: str = Field(default="", max_length=128) @field_validator("questions", "exclusions") @classmethod def _require_non_empty_text(cls, values: list[str]) -> list[str]: if any(not value.strip() for value in values) or len(set(values)) != len(values): raise ValueError("discovery contract text entries must be unique and non-empty") return values @field_validator("input_paths", "allowed_output_paths") @classmethod def _require_safe_project_paths(cls, values: list[str]) -> list[str]: if len(set(values)) != len(values): raise ValueError("discovery contract paths must be unique") for value in values: path = Path(value) if ( not value or "\\" in value or path.is_absolute() or value.startswith("/") or any(part in {"", ".", ".."} for part in path.parts) ): raise ValueError( "discovery contract paths must be non-empty project-relative POSIX paths" ) return values class AttemptUsage(BaseModel): """The session-usage delta attributable to one external agent attempt.""" prompt_tokens: int = 0 completion_tokens: int = 0 total_tokens: int = 0 cache_read_tokens: int = 0 cache_write_tokens: int = 0 reasoning_tokens: int = 0 api_calls: int = 0 agent_turns: int = 0 copilot_prompts_submitted: int = 0 copilot_nano_aiu: float = 0.0 @classmethod def from_stats(cls, stats: Any) -> "AttemptUsage": return cls( prompt_tokens=getattr(stats, "prompt_tokens", 0) or 0, completion_tokens=getattr(stats, "completion_tokens", 0) or 0, total_tokens=getattr(stats, "total_tokens", 0) or 0, cache_read_tokens=getattr(stats, "cache_read_tokens", 0) or 0, cache_write_tokens=getattr(stats, "cache_write_tokens", 0) or 0, reasoning_tokens=getattr(stats, "reasoning_tokens", 0) or 0, api_calls=getattr(stats, "api_calls", 0) or 0, agent_turns=getattr(stats, "total_turns", 0) or 0, copilot_prompts_submitted=getattr(stats, "copilot_prompts_submitted", 0) or 0, copilot_nano_aiu=getattr(stats, "copilot_nano_aiu", 0.0) or 0.0, ) def delta_to(self, after: "AttemptUsage") -> "AttemptUsage": return AttemptUsage( prompt_tokens=max(after.prompt_tokens - self.prompt_tokens, 0), completion_tokens=max(after.completion_tokens - self.completion_tokens, 0), total_tokens=max(after.total_tokens - self.total_tokens, 0), cache_read_tokens=max(after.cache_read_tokens - self.cache_read_tokens, 0), cache_write_tokens=max(after.cache_write_tokens - self.cache_write_tokens, 0), reasoning_tokens=max(after.reasoning_tokens - self.reasoning_tokens, 0), api_calls=max(after.api_calls - self.api_calls, 0), agent_turns=max(after.agent_turns - self.agent_turns, 0), copilot_prompts_submitted=max( after.copilot_prompts_submitted - self.copilot_prompts_submitted, 0, ), copilot_nano_aiu=max(after.copilot_nano_aiu - self.copilot_nano_aiu, 0.0), ) class VerificationAttemptEvent(BaseModel): """Safe verifier telemetry; raw model command text and evidence stay out of plans.""" kind: str command: str = Field(default="", max_length=2_000) normalized_path_count: int = Field(ge=0) elapsed_seconds: float = Field(ge=0.0) outcome_code: str return_code: int | None = None output_sha256: str = Field(default="", max_length=64) output_character_count: int = Field(default=0, ge=0) output_truncated: bool = False output_head: str = Field(default="", max_length=2_000) output_tail: str = Field(default="", max_length=2_000) output_artifact_path: str = Field(default="", max_length=4_096) rejection_reason: str = Field(default="", max_length=1_000) class ReviewCommandEvidence(BaseModel): """Runner-owned command proof with bounded display output and a full log path.""" command: str = Field(max_length=2_000) exit_code: int elapsed_seconds: float = Field(default=0.0, ge=0.0) output_sha256: str = Field(default="", max_length=64) output_character_count: int = Field(default=0, ge=0) output_truncated: bool = False output_head: str = Field(default="", max_length=2_000) output_tail: str = Field(default="", max_length=2_000) output_artifact_path: str = Field(default="", max_length=4_096) class TaskAttempt(BaseModel): """One append-only external agent attempt and its concise, auditable outcome.""" id: str = Field(default_factory=lambda: uuid4().hex) role: str endpoint: str model: str reasoning_effort: str = "" selection_reason: str started_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc)) ended_at: datetime | None = None outcome_status: TaskStatus | None = None failure_kind: TaskFailureKind | None = None outcome_summary: str = Field(default="", max_length=1000) evidence_packet_id: str = "" evidence_revision: int | None = Field(default=None, ge=1) evidence_fingerprint: str = "" validator_finding_ids: list[str] = Field(default_factory=list) validator_finding_fingerprint: str = "" usage_before: AttemptUsage = Field(default_factory=AttemptUsage) usage_delta: AttemptUsage = Field(default_factory=AttemptUsage) verification_events: list[VerificationAttemptEvent] = Field(default_factory=list) review_commands: list[ReviewCommandEvidence] = Field(default_factory=list, max_length=50) context_source_ids: list[str] = Field(default_factory=list) context_characters: int = Field(default=0, ge=0) context_token_estimate: int = Field(default=0, ge=0) tool_name_counts: dict[str, int] = Field(default_factory=dict) @property def completed(self) -> bool: return self.ended_at is not None class TaskPriority(str, Enum): CRITICAL_BUG = "critical_bug" INFRASTRUCTURE = "infrastructure" TRACER_BULLET = "tracer_bullet" FEATURE = "feature" POLISH = "polish" REFACTOR = "refactor" PRIORITY_ORDER: dict[TaskPriority, int] = { TaskPriority.CRITICAL_BUG: 0, TaskPriority.INFRASTRUCTURE: 1, TaskPriority.TRACER_BULLET: 2, TaskPriority.FEATURE: 3, TaskPriority.POLISH: 4, TaskPriority.REFACTOR: 5, } class TaskNode(BaseModel): id: str title: str description: str dependencies: list[str] = Field(default_factory=list) evidence_gated_by: list[str] = Field(default_factory=list) accepts_not_applicable_dependencies: bool = False estimated_effort: str = "medium" priority: TaskPriority = TaskPriority.FEATURE read_only: bool = False # One sentence the planner commits to before dispatch. For a read-only task it # is the expected finding; the research contract is "the findings ledger answers it". hypothesis: str = Field(default="", max_length=300) # Executable acceptance test: runs from the project root after review, exit 0 = satisfied. # ``{python}`` resolves to the target interpreter. Empty means the planner wrote no test. contract_command: str = Field(default="", max_length=1_000) # Model role currently assigned by the escalation ladder; empty = the task kind's default. altitude: str = Field(default="", max_length=40) # Hard per-contract caps across every attempt; 0 = no cap. max_tokens: int = Field(default=0, ge=0) max_seconds: int = Field(default=0, ge=0) assigned_to: Optional[str] = None status: TaskStatus = TaskStatus.PENDING retry_count: int = 0 max_retries: int = 3 files_created: list[str] = Field(default_factory=list) required_artifacts: list[str] = Field(default_factory=list) discovery_contract: DiscoveryContract | None = None discovery_checkpoint_id: str = "" discovery_checkpoint_fingerprint: str = "" discovery_checkpoint_used_count: int = Field(default=0, ge=0) red_regression_test_files: list[str] = Field(default_factory=list, max_length=10) disallow_unscoped_pytest: bool = False acceptance_criteria: list[str] = Field(default_factory=list, max_length=20) evidence_roots: list[str] = Field(default_factory=list) max_changed_files: int = Field(default=0, ge=0) max_changed_lines: int = Field(default=0, ge=0) require_raw_contract_artifacts: bool = False discard_branch_on_failure: bool = False blocked_reason: str = "" not_applicable_reason: str = "" failure_kind: TaskFailureKind | None = None failure_detail: str = "" acceptance_profile: AcceptanceProfile = AcceptanceProfile.NONE product_validation: ProductValidationCheckpoint | None = None evidence_packet_id: str = "" evidence_revision: int | None = Field(default=None, ge=1) evidence_fingerprint: str = "" validator_finding_ids: list[str] = Field(default_factory=list) validator_finding_fingerprint: str = "" validator_findings: list[dict[str, Any]] = Field(default_factory=list, max_length=100) research_supplements_used: int = Field(default=0, ge=0) semantic_repairs_used: int = Field(default=0, ge=0) high_reasoning_repairs_used: int = Field(default=0, ge=0) research_supplements_remaining: int = Field(default=0, ge=0) semantic_repairs_remaining: int = Field(default=0, ge=0) high_reasoning_repairs_remaining: int = Field(default=0, ge=0) semantic_repair_fingerprints: list[str] = Field(default_factory=list, max_length=100) deterministic_failure_fingerprints: list[str] = Field(default_factory=list, max_length=100) recovery_action: RecoveryAction = RecoveryAction.NONE lifecycle_phase: TaskLifecyclePhase = TaskLifecyclePhase.PLANNED attempts: list[TaskAttempt] = Field(default_factory=list) leased_at: datetime | None = None lease_expires_at: datetime | None = None lease_owner: str = "" terra_stall_retries_remaining: int = Field(default=1, ge=0) parent_task_id: str = "" subtask_ids: list[str] = Field(default_factory=list) parent_coherence_evidence: "ParentCoherenceEvidence | None" = None decomposition_fingerprints: list[str] = Field(default_factory=list, max_length=100) decomposition_depth: int = Field(default=0, ge=0) merge_conflict_retries_remaining: int = Field(default=1, ge=0) mechanical_rereviews_used: int = Field(default=0, ge=0, le=1) @model_validator(mode="after") def _infer_unscoped_pytest_policy(self) -> "TaskNode": """Preserve explicit no-full-suite task contracts at the tool boundary. New plans should set ``disallow_unscoped_pytest`` explicitly. The narrow inference keeps existing persisted/manual task descriptions containing the exact established wording ("no full suite") from relying on worker compliance alone. """ task_contract = "\n".join((self.description, *self.acceptance_criteria)).casefold() if self.red_regression_test_files or any( phrase in task_contract for phrase in ( "no full suite", "no pytest or ruff command", "invoke no pytest", "must not run pytest", "do not run pytest", "do not run full suite", "do not run the full suite", "never run full suite", "never run the full suite", ) ): self.disallow_unscoped_pytest = True return self @field_validator("required_artifacts") @classmethod def _require_valid_artifact_paths(cls, values: list[str]) -> list[str]: """Keep promised artifacts project-relative, exact POSIX file paths.""" if len(set(values)) != len(values): raise ValueError("required_artifacts must not contain duplicate paths") for path in values: parts = path.split("/") if ( not path or "\\" in path or path.startswith("/") or Path(path).is_absolute() or path.endswith("/") or any(part in {"", ".", ".."} for part in parts) ): raise ValueError( "required_artifacts entries must be non-empty project-relative POSIX file paths" ) return values @field_validator("red_regression_test_files") @classmethod def _require_valid_red_regression_test_paths(cls, values: list[str]) -> list[str]: """Limit red-first tasks to exact project-relative pytest test files.""" if len(set(values)) != len(values): raise ValueError("red_regression_test_files must not contain duplicate paths") for path in values: parts = path.split("/") if ( not path or "\\" in path or path.startswith("/") or Path(path).is_absolute() or any(part in {"", ".", ".."} for part in parts) or not path.startswith("tests/") or not path.endswith(".py") ): raise ValueError( "red_regression_test_files entries must be unique project-relative tests/*.py paths" ) return values @field_validator("evidence_gated_by") @classmethod def _require_unique_evidence_gate_dependencies(cls, values: list[str]) -> list[str]: if any(not value.strip() for value in values) or len(set(values)) != len(values): raise ValueError("evidence_gated_by must contain unique non-empty task IDs") return values @field_validator("acceptance_criteria") @classmethod def _require_unique_acceptance_criteria(cls, values: list[str]) -> list[str]: if any(not value.strip() for value in values) or len(set(values)) != len(values): raise ValueError("acceptance_criteria must contain unique non-empty values") return values def has_executable_contract(self) -> bool: """A dispatchable contract has a test the tooling can run, not just prose. A read-only task's test is "the findings ledger answers its hypothesis", so a declared hypothesis is its contract. """ if self.read_only: return bool(self.hypothesis.strip()) or bool(self.contract_command.strip()) return bool( self.contract_command.strip() or self.red_regression_test_files or self.acceptance_profile is not AcceptanceProfile.NONE ) def tokens_spent(self) -> int: return sum(attempt.usage_delta.total_tokens for attempt in self.attempts) def seconds_spent(self) -> float: return sum( (attempt.ended_at - attempt.started_at).total_seconds() for attempt in self.attempts if attempt.ended_at is not None ) def budget_exhausted(self) -> str: """Return the reason the per-contract budget is spent, or an empty string.""" if self.max_tokens and self.tokens_spent() >= self.max_tokens: return f"token budget spent ({self.tokens_spent()} >= {self.max_tokens})" if self.max_seconds and self.seconds_spent() >= self.max_seconds: return f"wall-clock budget spent ({self.seconds_spent():.0f}s >= {self.max_seconds}s)" return "" def start_attempt( self, *, role: str, endpoint: str, model: str, reasoning_effort: str, selection_reason: str, usage_before: AttemptUsage, context_source_ids: list[str] | None = None, context_characters: int = 0, context_token_estimate: int = 0, ) -> TaskAttempt: attempt = TaskAttempt( role=role, endpoint=endpoint, model=model, reasoning_effort=reasoning_effort, selection_reason=selection_reason, evidence_packet_id=self.evidence_packet_id, evidence_revision=self.evidence_revision, evidence_fingerprint=self.evidence_fingerprint, validator_finding_ids=list(self.validator_finding_ids), validator_finding_fingerprint=self.validator_finding_fingerprint, usage_before=usage_before, context_source_ids=list(context_source_ids or []), context_characters=context_characters, context_token_estimate=context_token_estimate, ) self.attempts.append(attempt) return attempt def finish_latest_attempt( self, *, outcome_status: TaskStatus, failure_kind: TaskFailureKind | None, outcome_summary: str, usage_after: AttemptUsage, ) -> None: if not self.attempts: return attempt = self.attempts[-1] if attempt.completed: return attempt.ended_at = datetime.now(timezone.utc) attempt.outcome_status = outcome_status attempt.failure_kind = failure_kind attempt.outcome_summary = outcome_summary[:1000] attempt.usage_delta = attempt.usage_before.delta_to(usage_after) class TaskContractSnapshot(BaseModel): """Compact immutable task state captured by a supervisor amendment.""" id: str title: str description: str dependencies: list[str] = Field(default_factory=list) required_artifacts: list[str] = Field(default_factory=list) acceptance_criteria: list[str] = Field(default_factory=list) status: TaskStatus @classmethod def from_task(cls, task: TaskNode) -> "TaskContractSnapshot": return cls( id=task.id, title=task.title, description=task.description, dependencies=list(task.dependencies), required_artifacts=list(task.required_artifacts), acceptance_criteria=list(task.acceptance_criteria), status=task.status, ) class SupervisorAmendment(BaseModel): """Append-only human intervention record, saved atomically with its plan.""" id: str = Field(default_factory=lambda: uuid4().hex) created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc)) reason: str = Field(min_length=1, max_length=2_000) operation: str = "replace_task" target_task_ids: list[str] = Field(default_factory=list) before: list[TaskContractSnapshot] = Field(default_factory=list) after: list[TaskContractSnapshot] = Field(default_factory=list) replacement_task_ids: list[str] = Field(default_factory=list) affected_downstream_ids: list[str] = Field(default_factory=list) class ForemanProposalStatus(str, Enum): """Supervisor-controlled lifecycle for an inert decomposition proposal.""" PENDING = "pending" APPROVED = "approved" REJECTED = "rejected" class ForemanSubtaskProposal(BaseModel): """A prospective child contract that does not yet exist in the runnable queue.""" id: str title: str = Field(min_length=1, max_length=200) description: str = Field(min_length=1, max_length=4_000) hypothesis: str = Field(default="", max_length=300) contract_command: str = Field(default="", max_length=1_000) covers: list[str] = Field(default_factory=list, max_length=30) depends_on: list[str] = Field(default_factory=list, max_length=9) @field_validator("covers", "depends_on") @classmethod def _require_unique_non_empty_values(cls, values: list[str]) -> list[str]: if any(not value.strip() for value in values) or len(set(values)) != len(values): raise ValueError("proposal lists must contain unique non-empty values") return values class ForemanDecompositionProposal(BaseModel): """A foreman split that requires a supervisor decision before queue mutation.""" id: str = Field(default_factory=lambda: uuid4().hex) created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc)) parent_task_id: str failure_fingerprint: str summary: str = Field(default="", max_length=2_000) subtasks: list[ForemanSubtaskProposal] = Field(min_length=2, max_length=10) status: ForemanProposalStatus = ForemanProposalStatus.PENDING supervisor_reason: str = Field(default="", max_length=2_000) decided_at: datetime | None = None @model_validator(mode="after") def _require_unique_subtask_ids(self) -> "ForemanDecompositionProposal": if len({task.id for task in self.subtasks}) != len(self.subtasks): raise ValueError("Foreman proposal subtask IDs must be unique") prior_ids: set[str] = set() for task in self.subtasks: invalid_dependencies = set(task.depends_on) - prior_ids if invalid_dependencies: raise ValueError( "Foreman proposal dependencies must reference earlier sibling IDs; " f"invalid={sorted(invalid_dependencies)}" ) prior_ids.add(task.id) return self class ParentCoherenceEvidence(BaseModel): """Deterministic checks run against the merged replacement set.""" checked_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc)) child_task_ids: list[str] = Field(default_factory=list) files_checked: list[str] = Field(default_factory=list) tests_passed: bool lint_passed: bool files_exist: bool diff_passed: bool required_artifacts_passed: bool passed: bool summary: str = Field(default="", max_length=2_000) class PlanPreflightEvidence(BaseModel): """Deterministic structural checks performed before a plan may execute.""" checked_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc)) passed: bool task_count: int maximum_task_count: int | None = None failures: list[str] = Field(default_factory=list, max_length=100) class TaskPlan(BaseModel): # Task IDs are unique only inside one plan. This durable identity scopes # Git branches/worktrees so a later plan with a similarly named task never # resumes or merges an unrelated retained branch. branch_namespace: str = Field(default_factory=lambda: uuid4().hex[:12], min_length=1, max_length=50) project_name: str goal: str intent: str tasks: list[TaskNode] recovery: RecoverySettings = Field(default_factory=RecoverySettings) decompositions_used: int = Field(default=0, ge=0) supervisor_amendments: list[SupervisorAmendment] = Field(default_factory=list, max_length=200) foreman_proposals: list[ForemanDecompositionProposal] = Field(default_factory=list, max_length=200) preflight_evidence: PlanPreflightEvidence | None = None audit_log_path: str = "" # Ledger shared across every plan of one campaign; empty falls back to project_name. ledger_name: str = Field(default="", max_length=200) # When set, a task without an executable contract is returned upward, never dispatched. require_executable_contracts: bool = False @property def effective_ledger_name(self) -> str: return self.ledger_name or self.project_name @field_validator("audit_log_path") @classmethod def _require_relative_audit_log_path(cls, value: str) -> str: if not value: return value path = Path(value) if path.is_absolute() or ".." in path.parts or path.suffix != ".jsonl": raise ValueError("audit_log_path must be a relative .jsonl path") return path.as_posix() @model_validator(mode="after") def _validate_evidence_gates(self) -> "TaskPlan": task_ids = {task.id for task in self.tasks} if len(task_ids) != len(self.tasks): raise ValueError("Task IDs must be unique") for task in self.tasks: unknown = set(task.evidence_gated_by) - task_ids if unknown: raise ValueError( f"Task {task.id} references unknown evidence-gate task IDs: {sorted(unknown)}" ) if not set(task.evidence_gated_by).issubset(task.dependencies): raise ValueError( f"Task {task.id} evidence_gated_by entries must also be dependencies" ) for proposal in self.foreman_proposals: if proposal.parent_task_id not in task_ids: raise ValueError( f"Foreman proposal {proposal.id} references unknown parent {proposal.parent_task_id}" ) return self def topological_sort(self) -> list[TaskNode]: visited = set() result: list[TaskNode] = [] task_map = {t.id: t for t in self.tasks} def visit(task_id: str): if task_id in visited: return visited.add(task_id) for dep_id in sorted( task_map[task_id].dependencies, key=lambda d: PRIORITY_ORDER.get(task_map.get(d, task_map[task_id]).priority, 99), ): if dep_id in task_map: visit(dep_id) result.append(task_map[task_id]) sorted_ids = sorted(self.tasks, key=lambda t: PRIORITY_ORDER.get(t.priority, 99)) for task in sorted_ids: visit(task.id) return result def get_ready_tasks(self) -> list[TaskNode]: completed = {t.id for t in self.tasks if t.status == TaskStatus.PASSED} task_map = {task.id: task for task in self.tasks} ready = [] for task in self.tasks: if task.status not in ( TaskStatus.PENDING, TaskStatus.FAILED, TaskStatus.RETRYING, TaskStatus.BLOCKED, ): continue if all( dependency_id in completed or ( task.accepts_not_applicable_dependencies and task_map.get(dependency_id) is not None and task_map[dependency_id].status is TaskStatus.NOT_APPLICABLE ) for dependency_id in task.dependencies ): ready.append(task) ready.sort(key=lambda t: PRIORITY_ORDER.get(t.priority, 99)) return ready def all_done(self) -> bool: return all( task.status in {TaskStatus.PASSED, TaskStatus.NOT_APPLICABLE} for task in self.tasks ) def has_escalated(self) -> bool: return any(t.status == TaskStatus.ESCALATED for t in self.tasks) def escalated_task_ids(self) -> list[str]: return [task.id for task in self.tasks if task.status == TaskStatus.ESCALATED] def state_fingerprint(self) -> tuple[tuple[Any, ...], ...]: return tuple( sorted( ( task.id, task.status.value, task.retry_count, task.blocked_reason, task.failure_kind.value if task.failure_kind else "", task.failure_detail, task.lifecycle_phase.value, task.validator_finding_fingerprint, task.recovery_action.value, tuple(task.semantic_repair_fingerprints), len(task.attempts), task.research_supplements_remaining, task.semantic_repairs_remaining, task.high_reasoning_repairs_remaining, ) for task in self.tasks ) )