"""Campaign orchestration: durable batch/phase queue advancement. Extracted from ``cli.py`` to restore its stated module boundary (``cli.py`` = "orchestration; connects interview -> decompose -> execute -> report", not business logic -- see AGENTS.md). The Click commands that call these functions stay in ``cli.py``, which imports every name it needs from here at module level. A handful of general plan-persistence primitives (``_load_plan``/ ``_save_plan``/``_prepare_lint_baseline``/``_init_cortex``/``_run_plan``/ ``_get_plan_path``) are used by both campaign and non-campaign commands, so they intentionally stayed in ``cli.py`` rather than moving here too. Every function below that needs one imports it locally (inside the function body, not at module level) specifically to avoid a ``cli.py`` <-> ``campaign_runner.py`` circular import at module load time -- by the time any of these functions actually runs, both modules have already finished importing, so the deferred import resolves cleanly. """ import os import threading from datetime import datetime, timezone from pathlib import Path import click from afk_developer.campaign import ( CampaignBatch, CampaignState, CampaignStatus, CampaignStore, PhaseAmendmentError, PhaseReflection, PhaseState, PhaseStatus, StallDecision, _add_usage, apply_campaign_policy, apply_phase_amendments, consult_terra_on_stall, make_phase_batch_goal, reflect_on_completed_phase, ) from afk_developer.campaign_supervision import logical_task_count from afk_developer.closure_metric import ( ClosureMetricError, measure_closure_metric, record_measurement, ) from afk_developer.config import Config, LintMode from afk_developer.ledger import LedgerEntry, LedgerStore, file_keys from afk_developer.planner.task_model import TaskPlan, TaskStatus from afk_developer.recovery import RecoverySettings from afk_developer.scheduler.attempts import initialize_plan_recovery _PHASE_HISTORY_DEPTH = 3 def _campaign_create_batch(config: Config, campaign: CampaignState, goal: str) -> CampaignBatch: """Use the normal planner for one campaign batch, then persist its ordinary saved plan.""" from afk_developer.cli import _load_plan, _save_plan from afk_developer.grillme.interviewer import _detect_intent from afk_developer.grillme.questions import auto_discover_project from afk_developer.grillme.spec_model import TaskSpec from afk_developer.planner.decomposer import decompose_task from afk_developer.planner.plan_verifier import preflight_plan plan_name = campaign.next_plan_name() if _load_plan(config, plan_name) is not None: raise RuntimeError(f"Campaign batch plan already exists: {plan_name}") detected = auto_discover_project(campaign.project_dir) spec = TaskSpec( project_dir=campaign.project_dir, project_name=plan_name, goal=goal, intent=_detect_intent(goal), language=detected.language, framework=detected.framework, test_framework=detected.test_framework, linter=detected.linter, auto_detected=detected, approved=True, ) plan = decompose_task(spec, config) preflight = preflight_plan( plan, maximum_task_count=campaign.limits.max_tasks_per_batch, require_executable_contracts=campaign.limits.require_executable_contracts, ) if not preflight.passed: raise RuntimeError("Plan preflight failed: " + " ".join(preflight.failures)) if campaign.friction_audit_enabled: plan.audit_log_path = f"audits/{plan_name}.jsonl" if len(plan.tasks) > campaign.limits.max_tasks_per_batch: return CampaignBatch( ordinal=len(campaign.batches) + 1, plan_name=plan_name, goal=goal, task_count=len(plan.tasks), ) campaign_recovery = RecoverySettings( mode=campaign.limits.recovery_mode, semantic_repair_limit=campaign.limits.semantic_repair_limit, research_supplement_limit=campaign.limits.research_supplement_limit, high_reasoning_repair_limit=campaign.limits.high_reasoning_repair_limit, max_decompositions=campaign.limits.max_decompositions, max_subtasks_per_decomposition=campaign.limits.max_subtasks_per_decomposition, max_decomposition_depth=campaign.limits.max_decomposition_depth, require_supervisor_decomposition_approval=( campaign.limits.require_supervisor_decomposition_approval ), require_supervisor_parent_coherence=campaign.limits.require_supervisor_parent_coherence, ) initialize_plan_recovery(plan, campaign_recovery) apply_campaign_policy(plan, campaign) lint_mode = LintMode(campaign.lint_mode) _save_plan( config, plan, project_dir=campaign.project_dir, linter=detected.linter, test_framework=detected.test_framework, lint_mode=lint_mode, max_auto_resume_passes=campaign.limits.max_auto_resume_passes, ) return CampaignBatch( ordinal=len(campaign.batches) + 1, plan_name=plan_name, goal=goal, task_count=len(plan.tasks), ) def _campaign_execute_batch( config: Config, campaign: CampaignState, batch: CampaignBatch ) -> tuple[bool, list[str], str]: """Run one saved plan through its normal bounded queue and return auditable summaries.""" from afk_developer.cli import _init_cortex, _load_plan, _prepare_lint_baseline, _run_plan from afk_developer.scheduler.lint_baseline import LintBaselineError loaded = _load_plan(config, batch.plan_name) if loaded is None: return False, [], f"Saved batch plan is missing: {batch.plan_name}" plan, project_dir, linter, test_framework, lint_mode, _saved_max_passes = loaded target = Path(project_dir).resolve() if project_dir else campaign.project_dir try: baseline = _prepare_lint_baseline( config, batch.plan_name, target, linter, lint_mode, create_if_missing=True, ) except LintBaselineError as exc: return False, [], f"Cannot prepare lint baseline: {exc}" cortex = _init_cortex(config, batch.plan_name) _run_plan( plan, config, cortex, target, linter, test_framework, auto_resume=True, lint_mode=lint_mode, lint_baseline=baseline, max_auto_resume_passes=campaign.limits.max_auto_resume_passes, ) summaries = [ f"{task.id}: {task.status.value}; {task.failure_detail or task.not_applicable_reason}" for task in plan.tasks ] if plan.all_done(): return True, summaries, "" if plan.has_escalated(): return False, summaries, "Manual retry required: " + ", ".join(plan.escalated_task_ids()) return False, summaries, "Batch stopped before every task completed." def _campaign_ensure_queue(config: Config, store: CampaignStore, campaign: CampaignState): """Return the campaign's currently active durable task queue. Unphased campaigns keep today's exact behavior: the reasoner plans the whole queue exactly once (``campaign.batches[0]``), and every later call simply loads that same saved plan. Phased campaigns advance through one saved task DAG per roadmap phase instead - see ``_campaign_ensure_phased_queue``. """ from afk_developer.cli import _load_plan if campaign.phases: return _campaign_ensure_phased_queue(config, store, campaign) if campaign.batches: loaded = _load_plan(config, campaign.batches[0].plan_name) if loaded is None: raise click.ClickException( f"Durable queue plan is missing: {campaign.batches[0].plan_name}" ) return loaded[0] batch = _campaign_create_batch(config, campaign, campaign.root_goal) if batch.task_count < 1 or batch.task_count > campaign.limits.max_tasks_per_batch: raise click.ClickException( f"Planned queue has {batch.task_count} tasks; limit is " f"{campaign.limits.max_tasks_per_batch}." ) campaign.batches.append(batch) store.save(campaign) loaded = _load_plan(config, batch.plan_name) if loaded is None: raise click.ClickException(f"Could not load the newly saved queue plan: {batch.plan_name}") return loaded[0] def _campaign_queue_metadata(config: Config, campaign: CampaignState): """Return the saved (project_dir, linter, test_framework, lint_mode) for the queue plan.""" from afk_developer.cli import _load_plan from afk_developer.grillme.questions import auto_discover_project loaded = _load_plan(config, campaign.batches[-1].plan_name) if loaded is None: raise click.ClickException( f"Durable queue plan is missing: {campaign.batches[-1].plan_name}" ) _plan, project_dir, linter, test_framework, lint_mode, _max_passes = loaded target_dir = Path(project_dir).resolve() if project_dir else campaign.project_dir if not linter or not test_framework: detected = auto_discover_project(target_dir) linter = linter or detected.linter test_framework = test_framework or detected.test_framework return target_dir, linter, test_framework, lint_mode def _campaign_persist_queue(config: Config, campaign: CampaignState, plan) -> None: from afk_developer.cli import _save_plan target_dir, linter, test_framework, lint_mode = _campaign_queue_metadata(config, campaign) campaign.batches[-1].task_count = logical_task_count(plan) _save_plan( config, plan, project_dir=target_dir, linter=linter, test_framework=test_framework, lint_mode=lint_mode, max_auto_resume_passes=campaign.limits.max_auto_resume_passes, ) def _campaign_run_ready_task( config: Config, campaign: CampaignState, plan, task, *, git_lock: "threading.Lock | None" = None, best_of: int = 1, ) -> None: """Lease exactly one ready task and run one bounded sprint via the normal execution pipeline. ``git_lock``, when provided, is forwarded so several concurrent calls to this function (one per worker thread, each its own ``task``) can safely share the same primary Git checkout -- see ``execute_plan``'s ``git_lock`` docstring. ``best_of`` (> 1) instead runs ``execute_best_of_n``: N redundant ``coder_light`` attempts at this one task, keeping the first to pass review and discarding the rest. """ from afk_developer.cli import _init_cortex, _prepare_lint_baseline from afk_developer.events import audit_sink, governance_sink from afk_developer.execution import ExecutionBoundaryError, prepare_execution_boundary from afk_developer.scheduler.queue import execute_best_of_n, execute_plan target_dir, linter, test_framework, lint_mode = _campaign_queue_metadata(config, campaign) try: prepared = prepare_execution_boundary(plan, config, target_dir) except ExecutionBoundaryError as exc: raise click.ClickException(str(exc)) from exc baseline = _prepare_lint_baseline( config, campaign.batches[-1].plan_name, target_dir, linter, lint_mode, create_if_missing=True, ) cortex = _init_cortex(config, campaign.batches[-1].plan_name) audit_path = config.projects_dir / plan.audit_log_path if plan.audit_log_path else None with ( governance_sink(prepared.governance_store.path, prepared.governance_snapshot), audit_sink(audit_path), ): if best_of > 1: execute_best_of_n( task, plan, config, cortex, target_dir, linter, test_framework, n=best_of, lint_mode=lint_mode, lint_baseline=baseline, save_callback=lambda: _campaign_persist_queue(config, campaign, plan), lease_seconds=campaign.limits.lease_seconds, lease_owner=str(os.getpid()), git_lock=git_lock, ) else: execute_plan( plan, config, cortex, target_dir, linter, test_framework, save_callback=lambda: _campaign_persist_queue(config, campaign, plan), lint_mode=lint_mode, lint_baseline=baseline, only_task_id=task.id, lease_seconds=campaign.limits.lease_seconds, lease_owner=str(os.getpid()), isolation=config.git_isolation, git_lock=git_lock, ) finished = next((item for item in plan.tasks if item.id == task.id), task) if finished.status is not TaskStatus.IN_PROGRESS: finished.leased_at = None finished.lease_expires_at = None finished.lease_owner = "" _campaign_persist_queue(config, campaign, plan) def _campaign_consult_stall(config: Config, campaign: CampaignState, plan) -> StallDecision: return consult_terra_on_stall(campaign, plan, config=config) def _campaign_phase_plan_name(campaign: CampaignState, phase: PhaseState) -> str: return f"{campaign.name}-phase-{phase.ordinal:03d}" def _campaign_write_phase_context( config: Config, campaign: CampaignState, phase: PhaseState, plan_name: str ) -> None: """Seed a freshly expanded phase's cortex with its goal and prior phase-summary continuity.""" from afk_developer.cli import _init_cortex cortex = _init_cortex(config, plan_name) criteria = ( "\n".join(f"- {criterion}" for criterion in phase.acceptance_criteria) or "(none specified)" ) cortex.replace_permanent( "phase-goal", f"Phase {phase.ordinal} of {len(campaign.phases)}: {phase.name}\n{phase.goal}\n" f"Acceptance criteria:\n{criteria}", ) prior = [item for item in campaign.phases if item.ordinal < phase.ordinal and item.summary] history = "\n\n".join( f"Phase {item.ordinal} ({item.name}): {item.summary}" for item in prior[-_PHASE_HISTORY_DEPTH:] ) if history: cortex.replace_permanent("phase-history", history) def _drop_completed_phase_dependencies(plan: TaskPlan, completed_task_ids: set[str]) -> None: """Remove cross-phase edges already guaranteed by campaign sequencing.""" local_task_ids = {task.id for task in plan.tasks} for task in plan.tasks: task.dependencies = [ dependency for dependency in task.dependencies if dependency not in completed_task_ids or dependency in local_task_ids ] def _record_phase_divergence( config: Config, campaign: CampaignState, plan: TaskPlan, phase: PhaseState, ) -> None: """Compare the just-in-time plan against the roadmap sketch; budget the difference. A plan that disagrees with the t=0 sketch is the most valuable signal the campaign produces: it is the moment the repository contradicted the guess. Within budget it is written to the ledger as a finding, where the phase checkpoint can read it. Beyond budget it escalates, because a phase that needs far more work than the roadmap imagined may mean the roadmap itself is wrong, and that is a human's call. """ # TaskPlan already validates task-ID uniqueness at construction. actual = [task.id for task in plan.tasks] phase.task_ids = actual sketch = phase.task_sketch if not sketch: return delta = len(actual) - len(sketch) if not delta: # The two ID lists are generated independently, so the same unit of work # is routinely named add-ci-workflow in the sketch and # add-ci-quality-workflow in the plan. Set differences therefore report # renamings as divergence; only the count is a signal worth acting on, # and an unchanged count means the phase's scope is what was approved. return unplanned = sorted(set(actual) - set(sketch)) dropped = sorted(set(sketch) - set(actual)) note = ( f"Phase {phase.ordinal} ('{phase.name}') planned {len(actual)} tasks against a roadmap " f"sketch of {len(sketch)} ({delta:+d}). Planned but not sketched: " f"{', '.join(unplanned) or '(none)'}. Sketched but not planned: " f"{', '.join(dropped) or '(none)'}. Those two lists are matched by ID, " "so they include work that was merely renamed; the count is the measurement." ) budget = campaign.limits.phase_divergence_budget if abs(delta) > budget: raise click.ClickException( f"{note} That exceeds the phase divergence budget of {budget}. The repository " "disagrees with the approved roadmap by more than one phase's worth of work; " "redraft the roadmap or raise phase_divergence_budget, then resume." ) phase.divergence_note = note[:1_000] LedgerStore(config.projects_dir).add_finding( plan.effective_ledger_name, LedgerEntry( kind="finding", hypothesis=( f"The roadmap's t=0 sketch for phase {phase.ordinal} predicted its shape." )[:300], tried=f"Planned phase {phase.ordinal} against the real repository."[:300], observed=note[:300], depends_on=file_keys(Path(campaign.project_dir), []), author_role="planner", ), ) def _campaign_expand_phase(config: Config, campaign: CampaignState, phase: PhaseState) -> None: """Build and persist one phase's task DAG via the normal planner, just-in-time.""" from afk_developer.cli import _load_plan, _save_plan from afk_developer.grillme.interviewer import _detect_intent from afk_developer.grillme.questions import auto_discover_project from afk_developer.grillme.spec_model import TaskSpec from afk_developer.planner.decomposer import decompose_task from afk_developer.planner.plan_verifier import preflight_plan plan_name = _campaign_phase_plan_name(campaign, phase) if _load_plan(config, plan_name) is not None: raise click.ClickException(f"Phase plan already exists: {plan_name}") if phase.ordinal == 1: _measure_root_start(config, campaign) _measure_phase_start(config, campaign, phase) goal = make_phase_batch_goal(campaign, phase) detected = auto_discover_project(campaign.project_dir) spec = TaskSpec( project_dir=campaign.project_dir, project_name=plan_name, goal=goal, intent=_detect_intent(goal), language=detected.language, framework=detected.framework, test_framework=detected.test_framework, linter=detected.linter, auto_detected=detected, approved=True, ) plan = decompose_task(spec, config) completed_task_ids: set[str] = set() for prior_phase in campaign.phases: if ( prior_phase.ordinal >= phase.ordinal or prior_phase.status is not PhaseStatus.COMPLETED or not prior_phase.plan_name ): continue loaded_prior = _load_plan(config, prior_phase.plan_name) if loaded_prior is None: raise click.ClickException(f"Completed phase plan is missing: {prior_phase.plan_name}") completed_task_ids.update(task.id for task in loaded_prior[0].tasks) _drop_completed_phase_dependencies(plan, completed_task_ids) _record_phase_divergence(config, campaign, plan, phase) preflight = preflight_plan( plan, maximum_task_count=campaign.limits.max_tasks_per_phase, require_executable_contracts=campaign.limits.require_executable_contracts, ) if not preflight.passed: raise click.ClickException("Plan preflight failed: " + " ".join(preflight.failures)) if len(plan.tasks) < 1 or len(plan.tasks) > campaign.limits.max_tasks_per_phase: raise click.ClickException( f"Phase {phase.ordinal} plan has {len(plan.tasks)} tasks; limit is " f"{campaign.limits.max_tasks_per_phase}." ) if campaign.friction_audit_enabled: plan.audit_log_path = f"audits/{plan_name}.jsonl" campaign_recovery = RecoverySettings( mode=campaign.limits.recovery_mode, semantic_repair_limit=campaign.limits.semantic_repair_limit, research_supplement_limit=campaign.limits.research_supplement_limit, high_reasoning_repair_limit=campaign.limits.high_reasoning_repair_limit, max_decompositions=campaign.limits.max_decompositions, max_subtasks_per_decomposition=campaign.limits.max_subtasks_per_decomposition, max_decomposition_depth=campaign.limits.max_decomposition_depth, require_supervisor_decomposition_approval=( campaign.limits.require_supervisor_decomposition_approval ), require_supervisor_parent_coherence=campaign.limits.require_supervisor_parent_coherence, ) initialize_plan_recovery(plan, campaign_recovery) apply_campaign_policy(plan, campaign) lint_mode = LintMode(campaign.lint_mode) _save_plan( config, plan, project_dir=campaign.project_dir, linter=detected.linter, test_framework=detected.test_framework, lint_mode=lint_mode, max_auto_resume_passes=campaign.limits.max_auto_resume_passes, ) _campaign_write_phase_context(config, campaign, phase, plan_name) phase.plan_name = plan_name campaign.batches.append( CampaignBatch( ordinal=phase.ordinal, plan_name=plan_name, goal=goal, task_count=len(plan.tasks) ) ) def _measure_root_start(config: Config, campaign: CampaignState) -> None: """The campaign's own contract must be runnable and unsatisfied before phase 1 starts.""" metric = campaign.closure_metric if metric is None or metric.start_value is not None: return try: value = measure_closure_metric( metric, campaign.project_dir, target_python=config.target_python, timeout=config.max_shell_timeout, ) except ClosureMetricError as exc: raise click.ClickException(f"Campaign closure metric: {exc}") from exc record_measurement(metric, value, at_start=True) if metric.satisfied_by(value): raise click.ClickException( f"Campaign closure metric '{metric.name}' already reads {value} " f"({metric.describe_target()}) before any phase starts, so it cannot detect a " "half-done campaign. Redraft the metric or the objective." ) def _require_root_closure(config: Config, store: CampaignStore, campaign: CampaignState) -> None: """Refuse to close the final phase while the campaign's own contract is unmet.""" metric = campaign.closure_metric if metric is None: return try: value = measure_closure_metric( metric, campaign.project_dir, target_python=config.target_python, timeout=config.max_shell_timeout, ) except ClosureMetricError as exc: reason = f"Campaign closure metric failed: {exc}" else: record_measurement(metric, value) if metric.satisfied_by(value): return reason = ( f"Campaign is not done: closure metric '{metric.name}' reads {value}, target " f"{metric.describe_target()} (started at {metric.start_value}). Every phase closed, " "but the phases together did not cover the objective. Add a phase to close the " "residual, then resume." ) campaign.status = CampaignStatus.ESCALATED campaign.stop_reason = reason[:2_000] store.save(campaign) raise click.ClickException(campaign.stop_reason) def _measure_phase_start(config: Config, campaign: CampaignState, phase: PhaseState) -> None: """Touch the repository before any coder does: the metric must be runnable and unsatisfied. A metric that already reads its target before the phase starts cannot tell a half-done phase from a finished one, which is the exact blind spot this gate exists to close. """ metric = phase.closure_metric if metric is None: return try: value = measure_closure_metric( metric, campaign.project_dir, target_python=config.target_python, timeout=config.max_shell_timeout, ) except ClosureMetricError as exc: raise click.ClickException(f"Phase {phase.ordinal} ('{phase.name}'): {exc}") from exc record_measurement(metric, value, at_start=True) if metric.satisfied_by(value): raise click.ClickException( f"Phase {phase.ordinal} ('{phase.name}') closure metric '{metric.name}' already reads " f"{value} ({metric.describe_target()}) before the phase starts, so it cannot detect " "a half-done phase. Redraft the metric or the phase." ) def _require_phase_closure( config: Config, store: CampaignStore, campaign: CampaignState, phase: PhaseState ) -> None: """Refuse to close a phase whose closure metric has not reached its target. Every task passing its own review is necessary but not sufficient; this is where the residual nobody's task owned becomes visible instead of silently shipping as a completed phase. """ metric = phase.closure_metric if metric is None: return try: value = measure_closure_metric( metric, campaign.project_dir, target_python=config.target_python, timeout=config.max_shell_timeout, ) except ClosureMetricError as exc: reason = f"Phase {phase.ordinal} ('{phase.name}') closure metric failed: {exc}" else: record_measurement(metric, value) if metric.satisfied_by(value): return reason = ( f"Phase {phase.ordinal} ('{phase.name}') is not done: closure metric " f"'{metric.name}' reads {value}, target {metric.describe_target()} " f"(started at {metric.start_value}). Every task passed review, but the phase's " "tasks together did not cover the whole goal. Add work to close the residual, then " "resume." ) campaign.status = CampaignStatus.ESCALATED campaign.stop_reason = reason[:2_000] store.save(campaign) raise click.ClickException(campaign.stop_reason) def _campaign_discard_unapproved_phase_plans(config: Config, campaign: CampaignState) -> None: """Remove previously drafted (never-approved) phase plan files before redrafting.""" from afk_developer.cli import _get_plan_path for phase in campaign.phases: if phase.plan_name: _get_plan_path(config, phase.plan_name).unlink(missing_ok=True) campaign.batches = [] def _campaign_close_out_phase( config: Config, store: CampaignStore, campaign: CampaignState, phase: PhaseState, plan: TaskPlan, ) -> None: """Reflect on one completed phase, persist its summary, and apply the decision. Raises ``click.ClickException`` (after persisting an escalated campaign status) if the checkpoint requires a human; otherwise mutates ``phase`` and, when the reflection narrowly revises the immediate next phase's goal, that next ``PhaseState`` too. """ from afk_developer.cli import _init_cortex summaries = [ f"{task.id}: {task.status.value}; {task.failure_detail or task.not_applicable_reason}" for task in plan.tasks ] ledger = LedgerStore(config.projects_dir).load(plan.effective_ledger_name) reflection = reflect_on_completed_phase( campaign, phase, config=config, completed_task_summaries=summaries, ledger=ledger, divergence_note=phase.divergence_note, ) _add_usage(campaign.reasoner_usage, reflection.usage) phase.summary = reflection.summary phase.status = PhaseStatus.COMPLETED phase.completed_at = datetime.now(timezone.utc) cortex = _init_cortex(config, phase.plan_name) cortex.replace_permanent(f"phase-{phase.ordinal}-summary", reflection.summary or "(no summary)") if reflection.decision == "escalate": campaign.status = CampaignStatus.ESCALATED campaign.stop_reason = ( reflection.summary or f"Phase {phase.ordinal} checkpoint requires human direction." ) store.save(campaign) raise click.ClickException(campaign.stop_reason) next_phase = campaign.phase_after(phase.ordinal) if ( next_phase is not None and reflection.decision == "revise_future_phases" and reflection.revised_next_phase_goal ): next_phase.goal = reflection.revised_next_phase_goal[:4_000] if reflection.decision == "reshape_future_phases": _apply_phase_reshape(config, store, campaign, phase, reflection, plan) store.save(campaign) def _apply_phase_reshape( config: Config, store: CampaignStore, campaign: CampaignState, phase: PhaseState, reflection: PhaseReflection, plan: TaskPlan, ) -> None: """Reshape the remaining roadmap, or escalate if the amendment batch is refused. The campaign's root closure metric is untouched by construction, so the destination stays pinned while the path moves. A refused batch is a durable escalation rather than a silent no-op: a checkpoint that believed the roadmap was wrong and could not say so safely still needs a human. """ try: applied = apply_phase_amendments(campaign, reflection.amendments) except PhaseAmendmentError as exc: campaign.status = CampaignStatus.ESCALATED campaign.stop_reason = ( f"Phase {phase.ordinal} checkpoint proposed a roadmap reshape that was refused: " f"{exc} Checkpoint summary: {reflection.summary}" )[:2_000] store.save(campaign) raise click.ClickException(campaign.stop_reason) from exc LedgerStore(config.projects_dir).add_finding( plan.effective_ledger_name, LedgerEntry( kind="finding", hypothesis=f"The roadmap after phase {phase.ordinal} had the right shape."[:300], tried=f"Reviewed the roadmap at the phase {phase.ordinal} checkpoint."[:300], observed="; ".join(applied)[:300], depends_on=file_keys(Path(campaign.project_dir), []), author_role="reasoner", ), ) def _campaign_ensure_phased_queue(config: Config, store: CampaignStore, campaign: CampaignState): """Advance a phased campaign across phase boundaries; return the active phase's queue. Phase 1's task DAG is already created by ``campaign plan``. Later phases are expanded just-in-time, exactly once, the first time this is called after the previous phase's queue is fully done. """ from afk_developer.cli import _load_plan for _ in range(len(campaign.phases) + 1): phase = campaign.active_phase() if phase is None: if campaign.phases and campaign.all_phases_resolved(): last_phase = campaign.phases[-1] loaded = _load_plan(config, last_phase.plan_name) if loaded is None: raise click.ClickException( f"Last phase plan is missing: {last_phase.plan_name}" ) return loaded[0] raise click.ClickException(f"Campaign '{campaign.name}' has no remaining phase to run.") if not phase.plan_name: _campaign_expand_phase(config, campaign, phase) if campaign.approve_each_phase and phase.ordinal > 1: campaign.status = CampaignStatus.PAUSED campaign.plan_approved = False campaign.stop_reason = ( f"Phase {phase.ordinal} ('{phase.name}') is ready and awaiting " f"re-approval (--approve-each-phase). Run: afk campaign approve {campaign.name}" ) store.save(campaign) raise click.ClickException(campaign.stop_reason) store.save(campaign) loaded = _load_plan(config, phase.plan_name) if loaded is None: raise click.ClickException(f"Phase {phase.ordinal} plan is missing: {phase.plan_name}") plan = loaded[0] if not plan.all_done(): if phase.status is PhaseStatus.PLANNED: phase.status = PhaseStatus.ACTIVE phase.started_at = phase.started_at or datetime.now(timezone.utc) store.save(campaign) return plan if phase.status is not PhaseStatus.COMPLETED: _require_phase_closure(config, store, campaign, phase) if phase.ordinal == len(campaign.phases): _require_root_closure(config, store, campaign) _campaign_close_out_phase(config, store, campaign, phase, plan) # Loop again: the next iteration's active_phase() picks up where this # phase left off (the next phase, or None once every phase resolves). raise click.ClickException( f"Campaign '{campaign.name}' could not resolve its next phase within the roadmap bounds." )