"""Durable, bounded multi-batch orchestration for AFK Developer. A campaign is deliberately more constrained than a free-running agent. It may plan and execute one small batch at a time, reflect only after that batch has fully completed, and then either stop or queue one bounded follow-up batch. Escalated, incomplete, or repeated work never causes a new batch to be planned. """ from __future__ import annotations import hashlib from collections.abc import Callable from concurrent.futures import ThreadPoolExecutor from datetime import datetime, timezone from pathlib import Path from time import perf_counter from pydantic import ValidationError from afk_developer.backends.registry import BackendRegistry # Re-exported explicitly (not a star-import) so `afk_developer.campaign.X` # keeps resolving for every existing caller/test after the Task 3 split # (see docs/refactor-handoffs/01-file-splits.md). from afk_developer.campaign_models import ( AMENDMENT_BLOCKING_CAMPAIGN_STATUSES, # noqa: F401 (re-exported for the CLI) TERMINAL_CAMPAIGN_STATUSES, CampaignBatch, CampaignBatchStatistics, CampaignLimits, # noqa: F401 (re-exported for external callers/tests) CampaignModelUsage, CampaignReflection, CampaignRoleUsage, CampaignState, CampaignStatistics, CampaignStatus, ClosureMetric, PhaseAmendment, PhaseAmendmentError, PhaseReflection, PhaseRoadmapError, PhaseState, PhaseStatus, # noqa: F401 (re-exported for external callers/tests) QueueStepResult, StallDecision, apply_phase_amendments, # noqa: F401 (re-exported for external callers/tests) phase_roadmap_fingerprint, # noqa: F401 (re-exported for external callers/tests) ) from afk_developer.campaign_store import ( # noqa: F401 (CampaignBusyError re-exported for external callers/tests) CampaignBusyError, CampaignStore, ) from afk_developer.config import Config from afk_developer.ledger import CampaignLedger, entry_is_current from afk_developer.planner.task_model import ( AcceptanceProfile, AttemptUsage, TaskNode, TaskPlan, TaskStatus, ) from afk_developer.scheduler.recovery_coordinator import escalate_altitude from afk_developer.utils import extract_json def apply_campaign_policy(plan: TaskPlan, campaign: CampaignState) -> None: """Apply the campaign creator's fixed permissions to one newly planned batch. The model never chooses these values. Read-only tasks receive approved source roots for discovery. Mutating tasks receive the same enabled acceptance profile and roots, so a follow-up cannot silently lower the user's corpus-validation requirements. A campaign with profile ``none`` may carry roots only when its entire generated batch is explicitly read-only. """ profile = AcceptanceProfile(campaign.acceptance_profile) if profile is AcceptanceProfile.NONE and campaign.evidence_roots: mutable_tasks = [task.id for task in plan.tasks if not task.read_only] if mutable_tasks: raise ValueError( "Campaign profile 'none' may use evidence roots only when every generated " f"task is read-only; mutable task(s): {', '.join(mutable_tasks)}." ) for task in plan.tasks: task.evidence_roots = list(campaign.evidence_roots) task.terra_stall_retries_remaining = campaign.limits.terra_stall_retries task.max_tokens = campaign.limits.max_tokens_per_task task.max_seconds = campaign.limits.max_seconds_per_task if not task.read_only: task.acceptance_profile = profile task.max_changed_files = campaign.limits.max_changed_files_per_task task.max_changed_lines = campaign.limits.max_changed_lines_per_task task.discard_branch_on_failure = True task.require_raw_contract_artifacts = profile is AcceptanceProfile.CORPUS_RAW_OUTPUT # Every phase/batch plan of one campaign shares one ledger. plan.ledger_name = campaign.name plan.require_executable_contracts = campaign.limits.require_executable_contracts _USAGE_FIELDS = ( "prompt_tokens", "completion_tokens", "total_tokens", "cache_read_tokens", "cache_write_tokens", "reasoning_tokens", "api_calls", "agent_turns", "copilot_prompts_submitted", "copilot_nano_aiu", ) def _add_usage(target: AttemptUsage, source: AttemptUsage) -> None: for field_name in _USAGE_FIELDS: setattr(target, field_name, getattr(target, field_name) + getattr(source, field_name)) def _increment_status(statistics: CampaignBatchStatistics, status: TaskStatus) -> None: if status is TaskStatus.PASSED: statistics.passed_tasks += 1 elif status is TaskStatus.NOT_APPLICABLE: statistics.not_applicable_tasks += 1 elif status is TaskStatus.FAILED: statistics.failed_tasks += 1 elif status is TaskStatus.ESCALATED: statistics.escalated_tasks += 1 elif status is TaskStatus.BLOCKED: statistics.blocked_tasks += 1 elif status is TaskStatus.DECOMPOSED: statistics.decomposed_tasks += 1 def build_campaign_statistics( campaign: CampaignState, load_plan: Callable[[str], TaskPlan | tuple | None], *, now: datetime | None = None, ) -> CampaignStatistics: """Aggregate only durable campaign-owned plans and persisted attempt records. ``load_plan`` is injected so this module remains independent of CLI plan serialization. It may return the ordinary ``_load_plan`` tuple or its first ``TaskPlan`` element. Attempt IDs are deduplicated across all batch plans so repeated reporting and retry history cannot inflate usage. """ statistics = CampaignStatistics( campaign_status=campaign.status, stop_reason=campaign.stop_reason, batches_completed=sum(batch.completed for batch in campaign.batches), batches_planned_limit=campaign.limits.max_batches, active_seconds=campaign.active_seconds, ) reference_time = now or datetime.now(timezone.utc) statistics.elapsed_wall_seconds = max( (reference_time - campaign.created_at).total_seconds(), 0.0 ) seen_attempt_ids: set[str] = set() model_usage: dict[tuple[str, str], CampaignModelUsage] = {} role_usage: dict[str, CampaignRoleUsage] = {} def record_attempt( attempt_id: str, role: str, endpoint: str, model: str, usage: AttemptUsage ) -> bool: if not attempt_id or attempt_id in seen_attempt_ids: return False seen_attempt_ids.add(attempt_id) statistics.attempts += 1 statistics.role_attempts[role or "unknown"] = ( statistics.role_attempts.get(role or "unknown", 0) + 1 ) _add_usage(statistics.usage, usage) route = (endpoint, model) bucket = model_usage.setdefault( route, CampaignModelUsage(endpoint=endpoint, model=model), ) _add_usage(bucket, usage) role_bucket = role_usage.setdefault( role or "unknown", CampaignRoleUsage(role=role or "unknown") ) _add_usage(role_bucket, usage) return True for batch in campaign.batches: subtotal = CampaignBatchStatistics(ordinal=batch.ordinal, plan_name=batch.plan_name) loaded = load_plan(batch.plan_name) plan = loaded[0] if isinstance(loaded, tuple) else loaded if plan is None: subtotal.planned_tasks = batch.task_count statistics.batches.append(subtotal) statistics.tasks_planned += subtotal.planned_tasks continue subtotal.planned_tasks = len(plan.tasks) for task in plan.tasks: _increment_status(subtotal, task.status) for attempt in task.attempts: if record_attempt( attempt.id, attempt.role, attempt.endpoint, attempt.model, attempt.usage_delta, ): subtotal.attempts += 1 _add_usage(subtotal.usage, attempt.usage_delta) statistics.batches.append(subtotal) statistics.tasks_planned += subtotal.planned_tasks statistics.tasks_passed += subtotal.passed_tasks statistics.tasks_not_applicable += subtotal.not_applicable_tasks statistics.tasks_failed += subtotal.failed_tasks statistics.tasks_blocked += subtotal.blocked_tasks statistics.tasks_escalated += subtotal.escalated_tasks statistics.tasks_decomposed += subtotal.decomposed_tasks for reflection in campaign.reflections: record_attempt( f"reflection:{reflection.usage_event_id}", reflection.usage_role, reflection.usage_endpoint, reflection.usage_model, reflection.usage, ) # Phased-campaign reasoner work (roadmap planning, per-phase checkpoint # reflection, stall consultation) has no per-event durable record the way # the unphased CampaignReflection list above does -- it's a single running # total on the campaign itself. Fold it in as its own reasoner bucket so it # isn't silently absent from the grand total or the per-role breakdown. reasoner_usage = campaign.reasoner_usage if any(getattr(reasoner_usage, field_name) for field_name in _USAGE_FIELDS): _add_usage(statistics.usage, reasoner_usage) role_bucket = role_usage.setdefault("reasoner", CampaignRoleUsage(role="reasoner")) _add_usage(role_bucket, reasoner_usage) statistics.model_usage = sorted( model_usage.values(), key=lambda usage: (usage.endpoint, usage.model) ) statistics.role_usage = sorted(role_usage.values(), key=lambda usage: usage.role) return statistics def _goal_fingerprint(goal: str) -> str: normalized = " ".join(goal.casefold().split()) return hashlib.sha256(normalized.encode("utf-8")).hexdigest() def make_batch_goal(campaign: CampaignState, follow_up: str | None = None) -> str: """Build the bounded planner input without feeding broad historical context.""" if follow_up is None: focus = campaign.root_goal label = "initial batch" else: focus = follow_up label = f"follow-up batch {len(campaign.batches) + 1}" ceiling = campaign.limits.max_tasks_per_batch target_floor = max(1, ceiling // 2) return ( f"Campaign objective: {campaign.root_goal}\n\n" f"Current {label} focus: {focus}\n\n" f"Plan a thorough, independently reviewable batch of {target_floor}-{ceiling} tasks. " "Use the full ceiling unless the remaining objective is genuinely small enough to need " "fewer — do not artificially shrink scope to a handful of tasks when more of the " "objective is ready to plan now. Each mutating task must fit deterministic review: at " f"most {campaign.limits.max_changed_files_per_task} changed files and " f"{campaign.limits.max_changed_lines_per_task} changed lines. Split any contract that " "cannot fit those limits before proposing it. Preserve existing public contracts. Do not repeat " "completed work. Include a read-only architecture or verification task when needed. Do " "not create, alter, or approve acceptance profiles or external evidence roots; those " "remain human-only operations." ) def reflect_on_completed_batch( campaign: CampaignState, batch: CampaignBatch, *, config: Config, completed_task_summaries: list[str], ) -> CampaignReflection: """Ask the reasoner whether exactly one non-duplicating follow-up is useful. The reflection has no project-writing capability. It can only select ``complete``, ``continue``, or ``escalate``; the runner validates the result and creates any plan through the normal planner afterwards. """ task_text = "\n".join(f"- {item[:500]}" for item in completed_task_summaries[:30]) usage_before = AttemptUsage.from_stats(config.stats) response = ( BackendRegistry(config) .get_reasoner() .complete( system_prompt=( "You are a bounded campaign checkpoint reviewer. Based only on the completed " "batch, decide whether the user's original objective is complete, a small next " "engineering batch is justified, or a human must decide. Return ONLY JSON: " '{"decision":"complete|continue|escalate","summary":"...",' '"next_goal":"..."}. For continue, next_goal must be a concrete, narrow ' "engineering objective and must not repeat work. Never request credentials, " "network access, deployment, destructive data actions, or changes to acceptance " "profiles/evidence approvals." ), user_prompt=( f"ROOT OBJECTIVE:\n{campaign.root_goal}\n\n" f"COMPLETED BATCH {batch.ordinal}:\n{batch.goal}\n\n" f"COMPLETED TASKS:\n{task_text or '(no task summaries available)'}\n\n" f"PREVIOUS FOLLOW-UP FINGERPRINTS: {', '.join(sorted(campaign.seen_goal_fingerprints())) or '(none)'}" ), temperature=0.0, ) ) config.record_usage(response.usage, role="reasoner") route = config.route_for("reasoner") raw = extract_json(response.content) decision = str(raw.get("decision", "escalate")).strip().lower() summary = str(raw.get("summary", "")).strip() next_goal = str(raw.get("next_goal", "")).strip() if decision not in {"complete", "continue", "escalate"}: decision = "escalate" summary = "Checkpoint returned an unsupported decision." if decision == "continue": fingerprint = _goal_fingerprint(next_goal) if len(next_goal) < 20 or fingerprint in campaign.seen_goal_fingerprints(): decision = "escalate" summary = "Checkpoint proposed an empty or repeated follow-up goal." next_goal = "" fingerprint = "" else: next_goal = "" fingerprint = "" return CampaignReflection( batch_ordinal=batch.ordinal, decision=decision, summary=summary, next_goal=next_goal, goal_fingerprint=fingerprint, usage_endpoint=route.endpoint, usage_model=route.model, usage=usage_before.delta_to(AttemptUsage.from_stats(config.stats)), ) # --------------------------------------------------------------------------- # Phase roadmaps + plan-first approval # # A phased campaign adds one durable tier between "campaign" and "batch": a # human-approved roadmap of 3-10 phases, each with its own goal and # acceptance criteria. Only phase 1's task DAG is expanded up front; later # phases are expanded just-in-time at each phase boundary, since a task-level # plan for a far-future phase would reference files/functions that do not # exist yet. Nothing here executes code or touches acceptance/evidence # policy - these functions only produce auditable, human-reviewable state. # --------------------------------------------------------------------------- def make_phase_batch_goal(campaign: CampaignState, phase: PhaseState) -> str: """Build the bounded planner input for one phase's task DAG. The roadmap's ``task_sketch`` is deliberately NOT included. This planner runs against the real repository with every earlier phase already landed; showing it a guess made before any file was read converts that guess into an anchor, which is the failure this planner exists to avoid. """ ceiling = campaign.limits.max_tasks_per_phase target_floor = max(1, ceiling // 2) criteria = ( "\n".join(f"- {criterion}" for criterion in phase.acceptance_criteria) or "(none specified)" ) task_scope = ( f"Plan a thorough, independently reviewable task list of {target_floor}-{ceiling} " "tasks that fully achieves this phase's goal and acceptance criteria. Use the full " "ceiling unless the phase is genuinely small enough to need fewer -- do not " "artificially shrink scope. Dependencies may name only tasks in this current phase; " "earlier phases are already complete through campaign sequencing. " ) return ( f"Campaign objective: {campaign.root_goal}\n\n" f"Current phase {phase.ordinal} of {len(campaign.phases)}: {phase.name}\n" f"Phase goal: {phase.goal}\n\n" f"Phase acceptance criteria:\n{criteria}\n\n" f"{_closure_metric_planning_note(phase)}" f"{task_scope}Each mutating task must fit deterministic review: at most " f"{campaign.limits.max_changed_files_per_task} changed files and " f"{campaign.limits.max_changed_lines_per_task} changed lines. Split any contract that " "cannot fit those limits before proposing it. Preserve existing public contracts. Do not " "repeat work from a previous phase. " "Include a read-only architecture or verification task when needed. Do not create, " "alter, or approve acceptance profiles or external evidence roots; those remain " "human-only operations." ) def _closure_metric_planning_note(phase: PhaseState) -> str: metric = phase.closure_metric if metric is None: return "" current = ( f"It currently reads {metric.start_value}. " if metric.start_value is not None else "" ) return ( f"Phase closure metric: '{metric.name}' is measured by running `{metric.command}` from " f"the project root; the phase closes only when it reads {metric.describe_target()}. " f"{current}Every task passing is not enough: the task list as a whole must drive this " "measurement to its target, so the final task must own whatever residual the earlier " "tasks leave behind.\n\n" ) def plan_phase_roadmap( campaign: CampaignState, *, config: Config, feedback: str = "", ) -> list[PhaseState]: """Ask the reasoner for a bounded, human-auditable 3-10 phase roadmap. This call has no project-writing capability and creates no task DAG; the caller is responsible for expanding phase 1 into tasks (via the normal planner) and persisting both. Safe to call repeatedly with ``feedback`` to redraft before a human approves the roadmap. The roadmap's top-level ``closure_metric`` -- the campaign's own contract -- is written onto ``campaign.closure_metric``; the caller persists it with the phases. """ user_prompt = f"CAMPAIGN OBJECTIVE:\n{campaign.root_goal}\n" if feedback.strip(): user_prompt += f"\nHUMAN FEEDBACK ON THE PREVIOUS DRAFT:\n{feedback.strip()}\n" response = ( BackendRegistry(config) .get_reasoner() .complete( system_prompt=( "You are a bounded campaign roadmap planner. Break the campaign objective into " "3 to 10 sequential phases that together achieve it. Each phase must be a " "coherent, independently completable body of engineering work with its own " "concrete, verifiable acceptance criteria. Return ONLY JSON: " '{"closure_metric":{"name":"...","command":"...","target":0,"direction":"down"},' '"phases":[{"name":"...","goal":"...","task_sketch":["..."],' '"acceptance_criteria":["...", "..."],' '"closure_metric":{"name":"...","command":"...","target":0,"direction":"down"}}]}. ' "The top-level closure_metric is the campaign's own contract: what would still be " "measurably wrong if the whole objective were only half done. Each phase's " "closure_metric answers: what would still be measurably wrong if this phase were " "only half done? Its command runs from the project root and must print exactly one " "integer counting the remaining work against the real repository (for example: " "handlers still inline in a module, files missing from a required set, lint " "diagnostics remaining). It must not already satisfy the target before the phase " "starts, and must satisfy it only when every part of the phase is done. " "CRITICAL: the command must RUN CLEANLY against the repository as it is TODAY, " "before any work has happened, and print its integer then. It is a ratchet " "measured from the start, not an end-state assertion. A command that reads a " "file or imports a module that will only exist once the work is done crashes at " "baseline and is rejected. Count what REMAINS (files not yet moved, handlers " "still inline) rather than inspecting what will exist later, and treat a missing " "end-state path as the full remaining count, never as an error. Prefer " '{python} -c "..." (the placeholder resolves to the target interpreter) over ' "shell utilities so the command is portable. " "Keep the command SHORT -- well under 200 characters, one simple count. It is " "handed to a shell verbatim, so the outer double quotes must not reappear " "anywhere inside: use only single quotes within the program, and no nested or " "escaped double quotes. If your measurement will not fit that, the measurement " "is too clever -- choose a simpler one that still distinguishes done from " "half-done. A metric that counts one obvious thing and always runs beats an " "exhaustive one that fails to parse. " "Measure the OUTCOME the phase promises, never a structural side effect of " "doing the work. Counting files or modules CREATED is almost always the wrong " "metric: those reach their target the moment the scaffolding exists, while the " "work they were supposed to carry can still be undone. If the phase promises " "that every X ends up handled somewhere, count the Xs NOT YET handled, and let " "it reach zero only when none are left. Ask yourself what a half-finished " "version of this phase would look like that still creates every file it was " "meant to create -- your metric must read non-zero for that repository. " "Omit closure_metric only when no " "such measurement exists; the human must then explicitly accept an unmeasured phase. " "task_sketch is a NON-BINDING list of short kebab-case task IDs, one per task " "you expect that phase to contain (for example \"extract-alu-family\"). IDs, not " "sentences: it is compared against the IDs the phase planner later produces, so " "prose descriptions make that comparison meaningless. Estimate the real number " "of tasks -- if a phase names twelve units of work, sketch twelve IDs, not two " "summarising ones. You are writing this before any file has been read, so it " "will be wrong in places; each phase is planned in detail later against the real " "repository, and that planner is free to disagree with you. Do not treat the " "sketch as a commitment; spend your effort on the goal, the acceptance criteria, " "and the closure metric, which are the parts that bind. " "Order phases so later phases depend only on earlier ones. Do not create, alter, " "or approve acceptance profiles or external evidence roots; those remain " "human-only operations. Never request credentials, network access, deployment, " "or destructive data actions." ), user_prompt=user_prompt, temperature=0.0, ) ) config.record_usage(response.usage, role="reasoner") raw = extract_json(response.content) raw_phases = raw.get("phases", []) if not isinstance(raw_phases, list) or not (3 <= len(raw_phases) <= 10): count = len(raw_phases) if isinstance(raw_phases, list) else 0 raise PhaseRoadmapError(f"Roadmap must contain 3-10 phases; the reasoner returned {count}.") campaign.closure_metric = _parse_closure_metric(0, raw.get("closure_metric")) phases: list[PhaseState] = [] seen_task_ids: set[str] = set() for ordinal, item in enumerate(raw_phases, start=1): if not isinstance(item, dict): raise PhaseRoadmapError(f"Phase {ordinal} was not a JSON object.") name = str(item.get("name", "")).strip() goal = str(item.get("goal", "")).strip() if not name or not goal: raise PhaseRoadmapError(f"Phase {ordinal} is missing a name or goal.") raw_sketch = item.get("task_sketch", item.get("task_ids", [])) if not isinstance(raw_sketch, list): raise PhaseRoadmapError(f"Phase {ordinal} task_sketch was not a JSON array.") task_sketch = [ str(entry).strip() for entry in raw_sketch if str(entry).strip() and _is_task_id_shaped(str(entry).strip()) ] # Deduplicated, but never required: the sketch is advisory, so an empty # or repetitive one is a weak roadmap, not an unusable one. task_sketch = [ entry for index, entry in enumerate(task_sketch) if entry not in task_sketch[:index] and entry not in seen_task_ids ] seen_task_ids.update(task_sketch) criteria = [ str(criterion).strip() for criterion in item.get("acceptance_criteria", []) if str(criterion).strip() ] phases.append( PhaseState( ordinal=ordinal, name=name[:200], goal=goal[:4_000], task_sketch=task_sketch[:20], acceptance_criteria=criteria[:20], closure_metric=_parse_closure_metric(ordinal, item.get("closure_metric")), ) ) return phases def _parse_closure_metric(ordinal: int, raw: object) -> ClosureMetric | None: label = f"Phase {ordinal}" if ordinal else "Campaign" if raw is None or raw == {} or raw == "": return None if not isinstance(raw, dict): raise PhaseRoadmapError(f"{label} closure_metric was not a JSON object.") name = str(raw.get("name", "")).strip() command = str(raw.get("command", "")).strip() if not name or not command: raise PhaseRoadmapError(f"{label} closure_metric needs a name and a command.") target = raw.get("target", 0) if isinstance(target, bool) or not isinstance(target, int): raise PhaseRoadmapError(f"{label} closure_metric target must be an integer.") direction = str(raw.get("direction", "down")).strip().lower() or "down" if direction not in {"down", "up"}: raise PhaseRoadmapError(f"{label} closure_metric direction must be down or up.") return ClosureMetric( name=name[:120], command=command[:1_000], target=target, direction=direction ) def _describe_closure_metric(label: str, metric: ClosureMetric | None) -> str: """One line of measured ground truth, or an explicit statement that there is none.""" if metric is None: return f"{label}: (none defined - this phase has no machine-checkable half-done test)" start = "unmeasured" if metric.start_value is None else str(metric.start_value) last = "unmeasured" if metric.last_value is None else str(metric.last_value) return ( f"{label}: '{metric.name}' via `{metric.command}` targets {metric.describe_target()}; " f"started at {start}, now reads {last}." ) def _phase_checkpoint_evidence( campaign: CampaignState, phase: PhaseState, *, ledger: CampaignLedger | None, divergence_note: str, ) -> str: """Assemble the measured evidence a phase checkpoint judges against. The checkpoint's own task summaries are status strings; on their own they cannot distinguish "every task passed" from "the phase achieved its goal". These lines are the part that touched the repository. """ lines = [ _describe_closure_metric(f"PHASE {phase.ordinal} CLOSURE METRIC", phase.closure_metric), _describe_closure_metric("CAMPAIGN ROOT CLOSURE METRIC", campaign.closure_metric), ] if divergence_note: lines.append(f"PLAN DIVERGENCE: {divergence_note}") if ledger is not None: project_dir = Path(campaign.project_dir) current = [ entry for entry in (*ledger.findings, *ledger.scars) if entry_is_current(entry, project_dir) ] if current: lines.append("LEDGER (facts established since this campaign began):") lines.extend(f"- {entry.one_line()}" for entry in current[-20:]) else: lines.append("LEDGER: (no current entries)") return "\n".join(lines) def _is_task_id_shaped(entry: str) -> bool: """Whether a roadmap sketch entry can be compared against a real task ID. The sketch is advisory, so a reasoner that answers with prose instead of IDs must not be fatal -- but comparing a sentence against a task ID is meaningless, and silently doing it produces a divergence number that measures nothing. Entries that are not ID-shaped are dropped, which degrades the phase to "no sketch" and skips the comparison honestly. """ return ( 1 <= len(entry) <= 120 and " " not in entry and entry.replace("-", "").replace("_", "").replace(".", "").isalnum() ) def _parse_phase_amendments(raw: object) -> list[PhaseAmendment]: """Turn the checkpoint's JSON into typed amendments, or refuse the whole batch. Deliberately all-or-nothing: a checkpoint that half-understood the schema should escalate, not have its coherent half applied to the roadmap. """ if not isinstance(raw, list) or not raw: raise PhaseAmendmentError("reshape_future_phases carried no amendments.") if len(raw) > 10: raise PhaseAmendmentError(f"A checkpoint may propose at most 10 amendments; got {len(raw)}.") amendments: list[PhaseAmendment] = [] for index, item in enumerate(raw, start=1): if not isinstance(item, dict): raise PhaseAmendmentError(f"Amendment {index} was not a JSON object.") operation = str(item.get("operation", "")).strip().lower() if operation not in {"revise_goal", "add", "drop"}: raise PhaseAmendmentError(f"Amendment {index} has an unsupported operation.") try: target_ordinal = int(item.get("target_ordinal", 0)) except (TypeError, ValueError) as exc: raise PhaseAmendmentError(f"Amendment {index} has a non-integer ordinal.") from exc reason = str(item.get("reason", "")).strip() if len(reason) < 20: raise PhaseAmendmentError( f"Amendment {index} needs a reason of at least 20 characters naming its evidence." ) criteria = [ str(criterion).strip() for criterion in item.get("acceptance_criteria", []) if str(criterion).strip() ] try: amendments.append( PhaseAmendment( target_ordinal=target_ordinal, operation=operation, reason=reason[:1_000], name=str(item.get("name", "")).strip()[:200], goal=str(item.get("goal", "")).strip()[:4_000], acceptance_criteria=criteria[:20], closure_metric=_parse_closure_metric(target_ordinal, item.get("closure_metric")), ) ) except (PhaseRoadmapError, ValidationError) as exc: raise PhaseAmendmentError(f"Amendment {index} is malformed: {exc}") from exc return amendments def reflect_on_completed_phase( campaign: CampaignState, phase: PhaseState, *, config: Config, completed_task_summaries: list[str], ledger: CampaignLedger | None = None, divergence_note: str = "", ) -> PhaseReflection: """Ask the reasoner to close out one completed phase. Mirrors ``reflect_on_completed_batch``'s shape: no project-writing capability, only a narrowly typed decision the caller validates. Unlike the batch-reflect checkpoint, this never invents new work outside the roadmap - ``revise_future_phases`` may only adjust the immediate next phase's goal text; it cannot rewrite the roadmap, add phases, or touch a completed or in-progress phase. ``ledger`` and ``divergence_note`` are the grounded half of the decision. Task summaries are status strings and cannot distinguish "every task passed" from "the phase achieved its goal"; the closure metrics and the ledger are the parts that touched the repository. Both are optional so existing callers keep working, but a checkpoint deciding without them is deciding on text alone. """ task_text = "\n".join(f"- {item[:500]}" for item in completed_task_summaries[:30]) evidence = _phase_checkpoint_evidence( campaign, phase, ledger=ledger, divergence_note=divergence_note ) criteria = ( "\n".join(f"- {criterion}" for criterion in phase.acceptance_criteria) or "(none specified)" ) usage_before = AttemptUsage.from_stats(config.stats) response = ( BackendRegistry(config) .get_reasoner() .complete( system_prompt=( "You are a bounded campaign phase checkpoint reviewer. Decide whether the " "roadmap should proceed as planned, the immediate next phase's goal should be " "narrowly revised in light of what was learned, or a human must decide. " "Weigh the MEASURED EVIDENCE above the task summaries: every task can pass " "review while the phase's closure metric shows the goal is only partly met, " "and that gap is exactly what you exist to catch. A closure metric that " "barely moved is grounds to escalate even when every task passed. " "Return ONLY JSON: " '{"decision":"complete_phase|revise_future_phases|reshape_future_phases|escalate",' '"summary":"...","revised_next_phase_goal":"...",' '"amendments":[{"operation":"revise_goal|add|drop","target_ordinal":3,' '"reason":"...","name":"...","goal":"...","acceptance_criteria":["..."],' '"closure_metric":{"name":"...","command":"...","target":0,' '"direction":"down"}}]}. ' "revised_next_phase_goal is used only for revise_future_phases and must describe " "the same next phase, not a new one. " "Use reshape_future_phases when what this phase measured means the REMAINING " "roadmap has the wrong shape -- work exists that no planned phase owns, or a " "planned phase is now unnecessary. amendments may target only phases the " "campaign has not started; you may not revisit a completed phase or the " "campaign's own closure metric. An added phase MUST carry a closure_metric whose " "command prints one integer counting its remaining work against the real " "repository. Every amendment needs a reason of at least 20 characters naming the " "evidence that prompted it. Prefer escalate over a reshape you cannot ground in " "the measured evidence above. " "Never request credentials, network access, deployment, destructive data " "actions, or changes to acceptance profiles/evidence approvals." ), user_prompt=( f"ROOT OBJECTIVE:\n{campaign.root_goal}\n\n" f"COMPLETED PHASE {phase.ordinal} ({phase.name}):\n{phase.goal}\n\n" f"ACCEPTANCE CRITERIA:\n{criteria}\n\n" f"MEASURED EVIDENCE:\n{evidence}\n\n" f"COMPLETED TASKS:\n{task_text or '(no task summaries available)'}" ), temperature=0.0, ) ) config.record_usage(response.usage, role="reasoner") route = config.route_for("reasoner") raw = extract_json(response.content) decision = str(raw.get("decision", "escalate")).strip().lower() summary = str(raw.get("summary", "")).strip() revised_goal = str(raw.get("revised_next_phase_goal", "")).strip() amendments: list[PhaseAmendment] = [] if decision not in { "complete_phase", "revise_future_phases", "reshape_future_phases", "escalate", }: decision = "escalate" summary = summary or "Checkpoint returned an unsupported decision." if decision == "revise_future_phases" and len(revised_goal) < 20: decision = "escalate" summary = summary or "Checkpoint proposed an empty or too-short phase revision." revised_goal = "" if decision == "reshape_future_phases": try: amendments = _parse_phase_amendments(raw.get("amendments")) except PhaseAmendmentError as exc: decision = "escalate" # Always carried, never merely a fallback: a human reading this # escalation needs to know a reshape was refused and why, even # when the checkpoint also wrote a summary of its own. refusal = f"Checkpoint proposed an unusable roadmap amendment: {exc}" summary = f"{summary} {refusal}".strip() if summary else refusal amendments = [] if decision != "revise_future_phases": revised_goal = "" if decision != "reshape_future_phases": amendments = [] return PhaseReflection( phase_ordinal=phase.ordinal, decision=decision, summary=summary, revised_next_phase_goal=revised_goal, amendments=amendments, usage_endpoint=route.endpoint, usage_model=route.model, usage=usage_before.delta_to(AttemptUsage.from_stats(config.stats)), ) def run_campaign( campaign: CampaignState, *, store: CampaignStore, create_batch: Callable[[CampaignState, str], CampaignBatch], execute_batch: Callable[[CampaignState, CampaignBatch], tuple[bool, list[str], str]], reflect: Callable[[CampaignState, CampaignBatch, list[str]], CampaignReflection], ) -> CampaignState: """Run batches until completion or a durable safety boundary is reached.""" if campaign.status in {CampaignStatus.COMPLETED, CampaignStatus.EXHAUSTED}: return campaign campaign.status = CampaignStatus.RUNNING campaign.stop_reason = "" store.save(campaign) while True: if campaign.remaining_active_seconds() <= 0: campaign.status = CampaignStatus.EXHAUSTED campaign.stop_reason = "Active-time budget exhausted. Resume only after increasing the human-approved limit." break if len(campaign.batches) >= campaign.limits.max_batches: campaign.status = CampaignStatus.EXHAUSTED campaign.stop_reason = "Batch limit reached." break batch = ( campaign.batches[-1] if campaign.batches and not campaign.batches[-1].completed else None ) if batch is None: goal = ( make_batch_goal(campaign) if not campaign.batches else make_batch_goal(campaign, campaign.reflections[-1].next_goal) ) try: batch = create_batch(campaign, goal) except Exception as exc: campaign.status = CampaignStatus.ESCALATED campaign.stop_reason = f"Could not create a bounded follow-up plan: {exc}" break if batch.task_count < 1 or batch.task_count > campaign.limits.max_tasks_per_batch: campaign.status = CampaignStatus.ESCALATED campaign.stop_reason = ( f"Planned batch has {batch.task_count} tasks; limit is " f"{campaign.limits.max_tasks_per_batch}." ) break if campaign.total_tasks + batch.task_count > campaign.limits.max_total_tasks: campaign.status = CampaignStatus.EXHAUSTED campaign.stop_reason = "Total-task limit reached before another batch could start." break campaign.batches.append(batch) store.save(campaign) batch.started_at = batch.started_at or datetime.now(timezone.utc) started = perf_counter() completed, summaries, stop_reason = execute_batch(campaign, batch) campaign.active_seconds += perf_counter() - started if not completed: batch.stop_reason = stop_reason[:2_000] campaign.status = CampaignStatus.ESCALATED campaign.stop_reason = f"Batch {batch.ordinal} did not complete: {batch.stop_reason}" break batch.completed = True batch.completed_at = datetime.now(timezone.utc) batch.stop_reason = "" store.save(campaign) try: reflection = reflect(campaign, batch, summaries) except Exception as exc: campaign.status = CampaignStatus.ESCALATED campaign.stop_reason = f"Checkpoint reflection failed: {exc}" break if reflection.decision == "continue": fingerprint = reflection.goal_fingerprint or _goal_fingerprint(reflection.next_goal) if not reflection.next_goal.strip() or fingerprint in campaign.seen_goal_fingerprints(): campaign.status = CampaignStatus.ESCALATED campaign.stop_reason = "Checkpoint proposed an empty or repeated follow-up goal." break reflection.goal_fingerprint = fingerprint campaign.reflections.append(reflection) store.save(campaign) if reflection.decision == "complete": campaign.status = ( CampaignStatus.RELEASE_READY if campaign.require_release_witness else CampaignStatus.COMPLETED ) campaign.stop_reason = reflection.summary or ( "Awaiting required human release witness." if campaign.require_release_witness else "Checkpoint declared the objective complete." ) break if reflection.decision != "continue": campaign.status = CampaignStatus.ESCALATED campaign.stop_reason = reflection.summary or "Checkpoint requires human direction." break store.save(campaign) return campaign # --------------------------------------------------------------------------- # Durable single-queue campaign continuation # # Unlike ``run_campaign`` (which re-invokes the reasoner to plan and reflect # on every batch), this mode asks the reasoner to create ONE durable task # queue (``campaign.batches[0]``) and then advances it deterministically, one # leased task and one bounded execution sprint at a time, across as many # independent process runs as needed. The reasoner is consulted again only # when deterministic continuation genuinely cannot decide what to do next. # --------------------------------------------------------------------------- def reap_expired_leases(plan: TaskPlan, *, now: datetime | None = None) -> list[str]: """Return abandoned in-flight tasks to the ready pool. A task is only ever leased by stamping ``leased_at``/``lease_expires_at`` at the moment ``execute_plan`` marks it ``IN_PROGRESS`` (see ``queue.execute_plan``'s ``lease_seconds``/``lease_owner`` parameters). If the owning process crashes or is killed before that call returns, the task is stuck ``IN_PROGRESS`` with a lease that will eventually expire. Once expired, restore it to a workable status so ``TaskPlan.get_ready_tasks()`` can select it again; nothing else about the task (attempts, evidence, branch) is touched here. """ reference = now or datetime.now(timezone.utc) reaped: list[str] = [] for task in plan.tasks: if task.status is not TaskStatus.IN_PROGRESS: continue if task.lease_expires_at is None or task.lease_expires_at > reference: continue task.status = TaskStatus.RETRYING if task.retry_count else TaskStatus.PENDING task.leased_at = None task.lease_expires_at = None task.lease_owner = "" reaped.append(task.id) return reaped def _queue_cost_so_far(plan: TaskPlan) -> float: """Sum durable, deduplicated per-attempt cost telemetry for one queue plan.""" seen: set[str] = set() total = 0.0 for task in plan.tasks: for attempt in task.attempts: if not attempt.id or attempt.id in seen: continue seen.add(attempt.id) total += attempt.usage_delta.copilot_nano_aiu return total def continue_campaign_once( campaign: CampaignState, *, store: CampaignStore, ensure_queue: Callable[[CampaignState], TaskPlan], run_ready_task: Callable[[CampaignState, TaskPlan, TaskNode], None], persist_queue: Callable[[CampaignState, TaskPlan], None], now: datetime | None = None, max_workers: int = 1, ) -> QueueStepResult: """Advance a durable campaign queue by up to ``max_workers`` bounded sprints at once. This function never calls a reasoning model. It (1) enforces the campaign's time/step/cost budgets, (2) gets or creates the durable task queue via ``ensure_queue`` (the only place the reasoner plans work), (3) reaps expired leases (persisted immediately via ``persist_queue``), (4) selects up to ``max_workers`` highest-priority ready tasks, and (5) runs them via ``run_ready_task``, which is expected to lease its task, execute exactly one bounded sprint using the existing worker/review/acceptance pipeline, and persist the outcome itself. Every state transition is persisted before this function returns. ``max_workers`` defaults to 1, preserving the exact original single-task behavior and dispatch cost; when greater than 1 and more than one task is ready, the selected tasks run concurrently via a thread pool -- ``run_ready_task``'s own caller is responsible for isolating each task (e.g. one git worktree each) and for serializing any operation that touches shared primary-checkout state. """ if campaign.status in TERMINAL_CAMPAIGN_STATUSES: return QueueStepResult( queue_complete=campaign.status in {CampaignStatus.COMPLETED, CampaignStatus.RELEASE_READY} ) if campaign.remaining_active_seconds() <= 0: campaign.status = CampaignStatus.EXHAUSTED campaign.stop_reason = "Active-time budget exhausted." store.save(campaign) return QueueStepResult() if campaign.queue_steps_taken >= campaign.limits.max_queue_steps: campaign.status = CampaignStatus.EXHAUSTED campaign.stop_reason = "Queue step (attempt) budget exhausted." store.save(campaign) return QueueStepResult() campaign.status = CampaignStatus.RUNNING campaign.stop_reason = "" store.save(campaign) plan = ensure_queue(campaign) if ( campaign.limits.max_cost_nano_aiu is not None and _queue_cost_so_far(plan) >= campaign.limits.max_cost_nano_aiu ): campaign.status = CampaignStatus.EXHAUSTED campaign.stop_reason = "Cost budget exhausted." store.save(campaign) return QueueStepResult() reaped = reap_expired_leases(plan, now=now) if reaped: persist_queue(campaign, plan) if plan.all_done(): campaign.status = ( CampaignStatus.RELEASE_READY if campaign.require_release_witness else CampaignStatus.COMPLETED ) campaign.stop_reason = ( "Awaiting required human release witness." if campaign.require_release_witness else "All queued tasks passed or were not applicable." ) store.save(campaign) return QueueStepResult( reaped_lease_task_ids=reaped, queue_complete=campaign.status is CampaignStatus.COMPLETED, ) ready = plan.get_ready_tasks() if not ready: return QueueStepResult( reaped_lease_task_ids=reaped, stalled=True, note="No task is ready: remaining tasks are blocked, escalated, or exhausted their retries.", ) target = ready[0] started = perf_counter() remaining_steps = campaign.limits.max_queue_steps - campaign.queue_steps_taken target_count = max(1, min(max_workers, remaining_steps, len(ready))) targets = ready[:target_count] if len(targets) == 1: run_ready_task(campaign, plan, target) else: with ThreadPoolExecutor(max_workers=len(targets)) as executor: futures = [executor.submit(run_ready_task, campaign, plan, item) for item in targets] for future in futures: future.result() campaign.queue_steps_taken += len(targets) campaign.active_seconds += perf_counter() - started store.save(campaign) finished = [ next((item for item in plan.tasks if item.id == candidate.id), candidate) for candidate in targets ] return QueueStepResult( task_id=finished[0].id, task_status=finished[0].status.value, task_ids=[item.id for item in finished], task_statuses=[item.status.value for item in finished], reaped_lease_task_ids=reaped, ready_tasks_remaining=len(plan.get_ready_tasks()), queue_complete=plan.all_done(), ) def consult_terra_on_stall( campaign: CampaignState, plan: TaskPlan, *, config: Config, ) -> StallDecision: """Ask the reasoner to resolve a queue that deterministic continuation cannot. This is the only point where Terra is consulted after the initial queue is created. It may retry exactly one task that is already ``FAILED`` or ``ESCALATED`` and still has a stall-retry available, attaching a short clarifying note; every other outcome escalates for a human. It cannot create tasks, change dependencies, or touch acceptance/evidence policy. """ stuck = [ task for task in plan.tasks if task.status in {TaskStatus.FAILED, TaskStatus.ESCALATED, TaskStatus.BLOCKED} ] task_text = "\n".join( f"- {task.id} [{task.status.value}] retries_left={task.terra_stall_retries_remaining} " f"reason={(task.failure_detail or task.blocked_reason or '')[:300]}" for task in stuck[:30] ) usage_before = AttemptUsage.from_stats(config.stats) response = ( BackendRegistry(config) .get_reasoner() .complete( system_prompt=( "You are a bounded campaign stall reviewer. The deterministic queue runner " "found no runnable task. Decide only between 'retry_task' (name exactly one " "task that is FAILED or ESCALATED and give one short clarifying note for its " "next attempt) or 'escalate' (a human must decide). Return ONLY JSON: " '{"decision":"retry_task|escalate","task_id":"...","note":"...","summary":"..."}. ' "Never invent a task id, change dependencies, priorities, or acceptance/evidence " "policy, or request credentials, network access, or destructive actions." ), user_prompt=( f"CAMPAIGN OBJECTIVE:\n{campaign.root_goal}\n\n" f"STUCK TASKS:\n{task_text or '(none listed)'}" ), temperature=0.0, ) ) config.record_usage(response.usage, role="reasoner") route = config.route_for("reasoner") raw = extract_json(response.content) decision = str(raw.get("decision", "escalate")).strip().lower() task_id = str(raw.get("task_id", "")).strip() note = str(raw.get("note", "")).strip() summary = str(raw.get("summary", "")).strip() candidate = next((task for task in plan.tasks if task.id == task_id), None) if ( decision != "retry_task" or candidate is None or candidate.status not in {TaskStatus.FAILED, TaskStatus.ESCALATED} or candidate.terra_stall_retries_remaining <= 0 ): decision = "escalate" if not summary: summary = "Checkpoint could not identify a safe task to retry; human review required." task_id = "" note = "" return StallDecision( decision=decision, task_id=task_id, note=note, summary=summary, usage_endpoint=route.endpoint, usage_model=route.model, usage=usage_before.delta_to(AttemptUsage.from_stats(config.stats)), ) def apply_stall_decision(plan: TaskPlan, decision: StallDecision) -> bool: """Apply a bounded stall decision to the queue plan; return whether it unblocked work. The retried task runs one altitude up. If no altitude remains above the one that already failed, the decision cannot unblock work and the campaign escalates. """ if decision.decision != "retry_task" or not decision.task_id: return False task = next((item for item in plan.tasks if item.id == decision.task_id), None) if ( task is None or task.status not in {TaskStatus.FAILED, TaskStatus.ESCALATED} or task.terra_stall_retries_remaining <= 0 ): return False if escalate_altitude(task) is None: return False task.terra_stall_retries_remaining -= 1 task.status = TaskStatus.RETRYING if task.retry_count else TaskStatus.PENDING task.blocked_reason = "" task.failure_kind = None if decision.note: prefix = f"{task.failure_detail} " if task.failure_detail else "" task.failure_detail = f"{prefix}[Terra stall guidance] {decision.note}"[:2_000] return True def run_campaign_queue_until_terminal( campaign: CampaignState, *, store: CampaignStore, ensure_queue: Callable[[CampaignState], TaskPlan], run_ready_task: Callable[[CampaignState, TaskPlan, TaskNode], None], persist_queue: Callable[[CampaignState, TaskPlan], None], consult_stall: Callable[[CampaignState, TaskPlan], StallDecision], max_iterations: int = 10_000, max_workers: int = 1, ) -> CampaignState: """Repeatedly call ``continue_campaign_once`` until the campaign reaches a terminal state. ``max_iterations`` is a hard, deterministic safety cap independent of the campaign's own budgets, so this never loops indefinitely even if every other stop condition were somehow misconfigured. Terra is consulted at most once per distinct stalled queue fingerprint; a repeated identical stall after consultation escalates immediately rather than looping. ``max_workers`` (default 1) is forwarded to each ``continue_campaign_once`` call -- see its docstring for the concurrency contract. """ for _ in range(max_iterations): if campaign.status in TERMINAL_CAMPAIGN_STATUSES: break result = continue_campaign_once( campaign, store=store, ensure_queue=ensure_queue, run_ready_task=run_ready_task, persist_queue=persist_queue, max_workers=max_workers, ) if campaign.status in TERMINAL_CAMPAIGN_STATUSES: break if not result.stalled: continue plan = ensure_queue(campaign) fingerprint = hashlib.sha256(repr(plan.state_fingerprint()).encode("utf-8")).hexdigest() if fingerprint in campaign.consulted_stall_fingerprints: campaign.status = CampaignStatus.ESCALATED campaign.stop_reason = ( "Queue is stalled again in the same state after a prior Terra consultation." ) store.save(campaign) break try: decision = consult_stall(campaign, plan) except Exception as exc: campaign.status = CampaignStatus.ESCALATED campaign.stop_reason = f"Stall consultation failed: {exc}" store.save(campaign) break _add_usage(campaign.reasoner_usage, decision.usage) campaign.consulted_stall_fingerprints.append(fingerprint) unblocked = apply_stall_decision(plan, decision) if not unblocked: campaign.status = CampaignStatus.ESCALATED campaign.stop_reason = decision.summary or "Checkpoint requires human direction." store.save(campaign) break persist_queue(campaign, plan) store.save(campaign) else: if campaign.status not in TERMINAL_CAMPAIGN_STATUSES: campaign.status = CampaignStatus.EXHAUSTED campaign.stop_reason = "Reached the deterministic queue-step safety cap." store.save(campaign) return campaign