"""Pure campaign data models: enums, pydantic models, and dependency-free helpers used across the campaign orchestration layer. Extracted from campaign.py (Session 1 of the refactor-handoffs plan, docs/refactor-handoffs/01-file-splits.md, Task 3). Nothing here calls BackendRegistry or does queue/IO orchestration -- see campaign.py for that. """ from __future__ import annotations import hashlib from datetime import datetime, timezone from enum import Enum from pathlib import Path from typing import Literal from uuid import uuid4 from pydantic import BaseModel, Field, field_validator from afk_developer.planner.task_model import AcceptanceProfile, AttemptUsage class CampaignStatus(str, Enum): READY = "ready" RUNNING = "running" PAUSED = "paused" RELEASE_READY = "release_ready" COMPLETED = "completed" ESCALATED = "escalated" EXHAUSTED = "exhausted" CANCELLED = "cancelled" TERMINAL_CAMPAIGN_STATUSES = frozenset( { CampaignStatus.COMPLETED, CampaignStatus.RELEASE_READY, CampaignStatus.EXHAUSTED, CampaignStatus.ESCALATED, CampaignStatus.CANCELLED, } ) # Escalation means "a human must decide", so the supervisor's own amendment # commands must still work there -- refusing them locks the deciding tools in # exactly the state that exists to summon a decider, leaving retrying the # unchanged failing task as the only offered move. Genuinely finished # campaigns stay closed to amendment. AMENDMENT_BLOCKING_CAMPAIGN_STATUSES = TERMINAL_CAMPAIGN_STATUSES - {CampaignStatus.ESCALATED} class CampaignLimits(BaseModel): """Human-approved ceilings for an autonomous campaign.""" max_batches: int = Field(default=4, ge=1, le=24) max_total_tasks: int = Field(default=60, ge=1, le=200) max_tasks_per_batch: int = Field(default=25, ge=1, le=30) max_active_seconds: int = Field(default=28_800, ge=60, le=86_400) max_auto_resume_passes: int = Field(default=12, ge=1, le=100) max_changed_files_per_task: int = Field(default=6, ge=1, le=30) max_changed_lines_per_task: int = Field(default=400, ge=1, le=5_000) lease_seconds: int = Field(default=1_200, ge=60, le=14_400) max_queue_steps: int = Field(default=600, ge=1, le=5_000) max_cost_nano_aiu: float | None = Field(default=None, ge=0.0) terra_stall_retries: int = Field(default=2, ge=0, le=10) recovery_mode: str = Field(default="bounded") semantic_repair_limit: int = Field(default=2, ge=0, le=10) research_supplement_limit: int = Field(default=2, ge=0, le=10) high_reasoning_repair_limit: int = Field(default=2, ge=0, le=10) max_phases: int = Field(default=8, ge=1, le=20) max_tasks_per_phase: int = Field(default=20, ge=1, le=40) # How far a just-in-time phase plan may differ in task count from the # roadmap's t=0 sketch before a human is asked. Divergence within the # budget is recorded as a ledger finding, not raised as an error. phase_divergence_budget: int = Field(default=5, ge=0, le=40) # How many times one campaign may reshape its own remaining roadmap. max_phase_amendments: int = Field(default=3, ge=0, le=20) max_decompositions: int = Field(default=6, ge=0, le=50) max_subtasks_per_decomposition: int = Field(default=5, ge=2, le=10) max_decomposition_depth: int = Field(default=1, ge=0, le=3) require_supervisor_decomposition_approval: bool = True require_supervisor_parent_coherence: bool = True # A task is dispatchable only with an executable acceptance test attached. require_executable_contracts: bool = True # Hard per-contract caps across all attempts; 0 disables the cap. max_tokens_per_task: int = Field(default=0, ge=0) max_seconds_per_task: int = Field(default=0, ge=0) @field_validator("recovery_mode") @classmethod def _validate_recovery_mode(cls, value: str) -> str: if value not in {"off", "bounded"}: raise ValueError("recovery_mode must be 'off' or 'bounded'") return value class PhaseStatus(str, Enum): PLANNED = "planned" ACTIVE = "active" COMPLETED = "completed" SKIPPED = "skipped" class ClosureMetric(BaseModel): """The machine-checkable answer to "what would fail if this phase were only half done?" ``command`` runs from the target project root and must print one integer. The phase may not close until that integer satisfies ``target``. This is a ratchet rather than a test: intermediate tasks are allowed to leave the value partially reduced, so it never blocks a task's own green suite the way a plain "the chain is empty" assertion would. """ name: str = Field(min_length=1, max_length=120) command: str = Field(min_length=1, max_length=1_000) target: int = 0 direction: Literal["down", "up"] = "down" start_value: int | None = None last_value: int | None = None last_measured_at: datetime | None = None def satisfied_by(self, value: int) -> bool: return value <= self.target if self.direction == "down" else value >= self.target def describe_target(self) -> str: operator = "<=" if self.direction == "down" else ">=" return f"{operator} {self.target}" class PhaseState(BaseModel): """One human-auditable roadmap phase within a phased campaign.""" ordinal: int = Field(ge=1) name: str = Field(min_length=1, max_length=200) goal: str = Field(min_length=1, max_length=4_000) # The roadmap's non-binding guess at this phase's shape, made before any # file was read. Advisory only: it is never shown to the phase planner and # never graded against. It exists so a human reviewing the roadmap can see # rough scope, and so plan divergence has a baseline to measure against. task_sketch: list[str] = Field(default_factory=list, max_length=20) # The task IDs this phase actually owns, written at just-in-time expansion. task_ids: list[str] = Field(default_factory=list, max_length=40) acceptance_criteria: list[str] = Field(default_factory=list, max_length=20) closure_metric: ClosureMetric | None = None status: PhaseStatus = PhaseStatus.PLANNED plan_name: str = "" summary: str = Field(default="", max_length=2_000) # What the just-in-time planner did that the t=0 roadmap sketch did not predict. divergence_note: str = Field(default="", max_length=1_000) started_at: datetime | None = None completed_at: datetime | None = None class PhaseAmendmentError(ValueError): """Raised before a phase amendment can be persisted.""" class PhaseAmendment(BaseModel): """One bounded, reasoned change to a not-yet-started roadmap phase. Amendments may only touch phases the campaign has not begun. A completed or active phase has a persisted task plan keyed to its ordinal, and its result is already part of the campaign's history; rewriting either is how an adaptive planner would talk itself into declaring an unfinished job done. The campaign's root closure metric is likewise out of reach: the destination stays pinned so the path is free to move. """ target_ordinal: int = Field(ge=1) operation: Literal["revise_goal", "add", "drop"] reason: str = Field(min_length=20, max_length=1_000) name: str = Field(default="", max_length=200) goal: str = Field(default="", max_length=4_000) acceptance_criteria: list[str] = Field(default_factory=list, max_length=20) closure_metric: ClosureMetric | None = None phase_ordinal: int = Field(default=0, ge=0) created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc)) def describe(self) -> str: return f"{self.operation} phase {self.target_ordinal}: {self.reason}" class CampaignBatch(BaseModel): ordinal: int = Field(ge=1) plan_name: str goal: str task_count: int = Field(default=0, ge=0) completed: bool = False started_at: datetime | None = None completed_at: datetime | None = None stop_reason: str = "" class CampaignReflection(BaseModel): batch_ordinal: int = Field(ge=1) decision: str summary: str = Field(default="", max_length=2_000) next_goal: str = Field(default="", max_length=2_000) goal_fingerprint: str = "" created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc)) usage_event_id: str = Field(default_factory=lambda: uuid4().hex) usage_role: str = "reasoner" usage_endpoint: str = "" usage_model: str = "" usage: AttemptUsage = Field(default_factory=AttemptUsage) class CampaignModelUsage(AttemptUsage): """Durable aggregate usage for one route in a campaign report.""" endpoint: str = "" model: str = "" class CampaignRoleUsage(AttemptUsage): """Durable aggregate usage for one AFK role in a campaign report.""" role: str = "" class CampaignBatchStatistics(BaseModel): """One batch's plan-backed subtotal for campaign reconciliation.""" ordinal: int plan_name: str planned_tasks: int = 0 passed_tasks: int = 0 not_applicable_tasks: int = 0 failed_tasks: int = 0 blocked_tasks: int = 0 escalated_tasks: int = 0 decomposed_tasks: int = 0 attempts: int = 0 usage: AttemptUsage = Field(default_factory=AttemptUsage) class CampaignStatistics(BaseModel): """Computed view over campaign-owned plans and safe persisted usage metadata.""" campaign_status: CampaignStatus stop_reason: str = "" batches_completed: int = 0 batches_planned_limit: int = 0 tasks_planned: int = 0 tasks_passed: int = 0 tasks_not_applicable: int = 0 tasks_failed: int = 0 tasks_blocked: int = 0 tasks_escalated: int = 0 tasks_decomposed: int = 0 attempts: int = 0 role_attempts: dict[str, int] = Field(default_factory=dict) usage: AttemptUsage = Field(default_factory=AttemptUsage) model_usage: list[CampaignModelUsage] = Field(default_factory=list) role_usage: list[CampaignRoleUsage] = Field(default_factory=list) active_seconds: float = 0.0 elapsed_wall_seconds: float | None = None batches: list[CampaignBatchStatistics] = Field(default_factory=list) class CampaignState(BaseModel): name: str project_dir: Path root_goal: str = Field(min_length=1, max_length=10_000) linter: str = "" test_framework: str = "" lint_mode: str = "strict" acceptance_profile: str = AcceptanceProfile.NONE.value evidence_roots: list[str] = Field(default_factory=list) limits: CampaignLimits = Field(default_factory=CampaignLimits) status: CampaignStatus = CampaignStatus.READY batches: list[CampaignBatch] = Field(default_factory=list) reflections: list[CampaignReflection] = Field(default_factory=list) active_seconds: float = Field(default=0.0, ge=0.0) stop_reason: str = Field(default="", max_length=2_000) queue_steps_taken: int = Field(default=0, ge=0) consulted_stall_fingerprints: list[str] = Field(default_factory=list) phases: list[PhaseState] = Field(default_factory=list) phase_amendments: list[PhaseAmendment] = Field(default_factory=list) # The root of the plan tree is itself a contract: measured before phase 1 and at the end. closure_metric: ClosureMetric | None = None plan_approved: bool = False ever_approved: bool = False roadmap_fingerprint: str = "" approve_each_phase: bool = False friction_audit_enabled: bool = False require_release_witness: bool = False release_attestation: "ReleaseAttestation | None" = None checkpoint_acknowledgements: list["CheckpointAcknowledgement"] = Field(default_factory=list) reasoner_usage: AttemptUsage = Field(default_factory=AttemptUsage) created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc)) updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc)) @field_validator("name") @classmethod def _validate_name(cls, value: str) -> str: if not value or any( char not in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-" for char in value ): raise ValueError( "campaign name must contain only letters, numbers, dots, underscores, and hyphens" ) return value @property def total_tasks(self) -> int: return sum(batch.task_count for batch in self.batches) def next_plan_name(self) -> str: return f"{self.name}-batch-{len(self.batches) + 1:03d}" def seen_goal_fingerprints(self) -> set[str]: return { reflection.goal_fingerprint for reflection in self.reflections if reflection.goal_fingerprint } def remaining_active_seconds(self) -> float: return max(self.limits.max_active_seconds - self.active_seconds, 0.0) def active_phase(self) -> PhaseState | None: """Return the earliest phase still in progress, in roadmap order.""" for phase in self.phases: if phase.status in (PhaseStatus.PLANNED, PhaseStatus.ACTIVE): return phase return None def phase_after(self, ordinal: int) -> PhaseState | None: return next((phase for phase in self.phases if phase.ordinal == ordinal + 1), None) def all_phases_resolved(self) -> bool: return bool(self.phases) and all( phase.status in (PhaseStatus.COMPLETED, PhaseStatus.SKIPPED) for phase in self.phases ) class ReleaseAttestation(BaseModel): """Explicit human observation, never presented as automated validation.""" kind: str = Field(min_length=1, max_length=100) summary: str = Field(min_length=1, max_length=4_000) operator: str = Field(default="human", min_length=1, max_length=200) created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc)) artifact_path: str = "" artifact_sha256: str = "" class CheckpointAcknowledgement(BaseModel): """A durable supervisor decision to continue after a completed checkpoint escalates.""" phase_ordinal: int = Field(ge=1) reason: str = Field(min_length=1, max_length=4_000) created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc)) def started_phase_frontier(campaign: CampaignState) -> int: """The highest ordinal the campaign has already begun; nothing at or below it may move.""" started = [ phase.ordinal for phase in campaign.phases if phase.status is not PhaseStatus.PLANNED ] return max(started, default=0) def apply_phase_amendments( campaign: CampaignState, amendments: list[PhaseAmendment] ) -> list[str]: """Reshape the not-yet-started tail of a roadmap. Returns one line per applied change. Fail-closed and all-or-nothing: every amendment is validated against the live campaign before any is applied, so a rejected batch leaves the roadmap exactly as it was. Only phases after ``started_phase_frontier`` may be touched, because those are precisely the phases with no persisted task plan keyed to their ordinal -- which is what makes renumbering the tail safe. """ if not amendments: return [] budget = campaign.limits.max_phase_amendments already = len(campaign.phase_amendments) if already + len(amendments) > budget: raise PhaseAmendmentError( f"Campaign has used {already} of {budget} phase amendments; " f"{len(amendments)} more would exceed the budget." ) targets = [amendment.target_ordinal for amendment in amendments] if len(targets) != len(set(targets)): raise PhaseAmendmentError( "Each phase may be amended at most once per checkpoint; " f"got repeated targets in {targets}." ) frontier = started_phase_frontier(campaign) by_ordinal = {phase.ordinal: phase for phase in campaign.phases} for amendment in amendments: target = by_ordinal.get(amendment.target_ordinal) if target is None: raise PhaseAmendmentError(f"Unknown phase ordinal: {amendment.target_ordinal}.") if amendment.target_ordinal <= frontier or target.status is not PhaseStatus.PLANNED: raise PhaseAmendmentError( f"Phase {amendment.target_ordinal} is {target.status.value}; only phases the " "campaign has not started may be amended." ) if amendment.operation == "add": if not amendment.name.strip() or not amendment.goal.strip(): raise PhaseAmendmentError("An added phase needs both a name and a goal.") if amendment.closure_metric is None: raise PhaseAmendmentError( f"Added phase '{amendment.name}' has no closure metric. A phase with no " "machine-checkable half-done test cannot be created." ) if amendment.operation == "revise_goal" and not amendment.goal.strip(): raise PhaseAmendmentError( f"Revising phase {amendment.target_ordinal} needs a replacement goal." ) working = list(campaign.phases) applied: list[str] = [] for amendment in amendments: target = next( phase for phase in working if phase.ordinal == amendment.target_ordinal ) if amendment.operation == "revise_goal": target.goal = amendment.goal.strip()[:4_000] if amendment.name.strip(): target.name = amendment.name.strip()[:200] if amendment.acceptance_criteria: target.acceptance_criteria = amendment.acceptance_criteria[:20] if amendment.closure_metric is not None: target.closure_metric = amendment.closure_metric elif amendment.operation == "drop": target.status = PhaseStatus.SKIPPED target.summary = f"Skipped by phase amendment: {amendment.reason}"[:2_000] else: working.insert( working.index(target) + 1, PhaseState( ordinal=amendment.target_ordinal, # rewritten by the renumber below name=amendment.name.strip()[:200], goal=amendment.goal.strip()[:4_000], acceptance_criteria=amendment.acceptance_criteria[:20], closure_metric=amendment.closure_metric, ), ) applied.append(amendment.describe()) live = [phase for phase in working if phase.status is not PhaseStatus.SKIPPED] if len(live) > campaign.limits.max_phases: raise PhaseAmendmentError( f"The amended roadmap would hold {len(live)} live phases, over the " f"max_phases limit of {campaign.limits.max_phases}." ) for position, phase in enumerate(working, start=1): if position > frontier: phase.ordinal = position campaign.phases = working for amendment in amendments: amendment.phase_ordinal = amendment.target_ordinal campaign.phase_amendments.extend(amendments) return applied class PhaseRoadmapError(RuntimeError): """Raised when the reasoner cannot produce a usable phase roadmap.""" def phase_roadmap_fingerprint(phases: list[PhaseState]) -> str: normalized = "\u241f".join( f"{phase.ordinal}|{phase.name.casefold()}|{phase.goal.casefold()}|" + ",".join(task_id.casefold() for task_id in phase.task_sketch) + "|" + ",".join(criterion.casefold() for criterion in phase.acceptance_criteria) + _closure_metric_fingerprint_segment(phase.closure_metric) for phase in phases ) return hashlib.sha256(normalized.encode("utf-8")).hexdigest() def _closure_metric_fingerprint_segment(metric: ClosureMetric | None) -> str: # Absent metrics contribute nothing so fingerprints approved before this field existed still match. if metric is None: return "" return f"|{metric.name.casefold()}|{metric.command}|{metric.target}|{metric.direction}" class PhaseReflection(BaseModel): """A bounded reasoner decision closing out one completed campaign phase.""" phase_ordinal: int = Field(ge=1) decision: str = "escalate" summary: str = Field(default="", max_length=2_000) revised_next_phase_goal: str = Field(default="", max_length=4_000) amendments: list[PhaseAmendment] = Field(default_factory=list, max_length=10) created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc)) usage_event_id: str = Field(default_factory=lambda: uuid4().hex) usage_role: str = "reasoner" usage_endpoint: str = "" usage_model: str = "" usage: AttemptUsage = Field(default_factory=AttemptUsage) class QueueStepResult(BaseModel): """The outcome of exactly one ``continue_campaign_once`` call.""" task_id: str = "" task_status: str = "" task_ids: list[str] = Field(default_factory=list) task_statuses: list[str] = Field(default_factory=list) reaped_lease_task_ids: list[str] = Field(default_factory=list) ready_tasks_remaining: int = 0 queue_complete: bool = False stalled: bool = False note: str = "" class StallDecision(BaseModel): """A bounded reasoner decision for a queue that cannot make deterministic progress.""" decision: str = "escalate" task_id: str = "" note: str = Field(default="", max_length=1_000) summary: str = Field(default="", max_length=2_000) usage_endpoint: str = "" usage_model: str = "" usage: AttemptUsage = Field(default_factory=AttemptUsage)