"""Campaign Click command group. Extracted verbatim from the `campaign` Click group in `cli.py` (Session 1 of the refactor-handoffs plan, docs/refactor-handoffs/01-file-splits.md). Zero behavior change. Defines its own `click.group` (registered onto `main` from cli.py) rather than decorating `main` directly, per the plan's Task 2. Names resolved from cli.py's own module namespace (`console`, `_load_plan`, `_other_afk_processes_active`, `_validate_plan_name`) are accessed via `import afk_developer.cli as cli` (function-body-local, to avoid a circular import since cli.py imports this module at module level) so existing test monkeypatches on `afk_developer.cli.X` keep working unchanged. """ import hashlib import json import sys import threading from datetime import datetime, timezone from pathlib import Path import click from afk_developer.campaign import ( AMENDMENT_BLOCKING_CAMPAIGN_STATUSES, TERMINAL_CAMPAIGN_STATUSES, CampaignBatch, CampaignLimits, CampaignState, CampaignStatus, CampaignStore, PhaseRoadmapError, PhaseStatus, _add_usage, build_campaign_statistics, continue_campaign_once, phase_roadmap_fingerprint, plan_phase_roadmap, reflect_on_completed_batch, run_campaign, run_campaign_queue_until_terminal, ) from afk_developer.campaign_models import ( CheckpointAcknowledgement, PhaseState, ReleaseAttestation, ) from afk_developer.campaign_runner import ( _campaign_consult_stall, _campaign_create_batch, _campaign_discard_unapproved_phase_plans, _campaign_ensure_queue, _campaign_execute_batch, _campaign_expand_phase, _campaign_persist_queue, _campaign_run_ready_task, ) from afk_developer.campaign_supervision import ( SupervisorAmendmentError, approve_foreman_proposal, logical_task_count, mark_task_verified, reject_foreman_proposal, replace_task, replace_unstarted_phase_tasks, ) from afk_developer.config import Config, LintMode from afk_developer.core_campaign import ProcessorCoreGoalSpec, build_processor_core_goal from afk_developer.environment import _normalize_interpreter from afk_developer.evidence import EvidencePacketError, normalize_evidence_roots from afk_developer.planner.task_model import ( ENABLED_ACCEPTANCE_PROFILES, AcceptanceProfile, AttemptUsage, TaskNode, TaskPlan, TaskStatus, ) from afk_developer.reporter import report_campaign_statistics from afk_developer.scheduler.attempts import initialize_plan_recovery def _validate_plan_name_callback(ctx, param, value): import afk_developer.cli as cli return cli._validate_plan_name(ctx, param, value) def _repair_legacy_audit_path(state: CampaignState, plan_name: str, plan: TaskPlan) -> None: if state.friction_audit_enabled and not plan.audit_log_path: plan.audit_log_path = f"audits/{plan_name}.jsonl" @click.group("campaign") def campaign() -> None: """Manage a bounded, checkpointed sequence of AFK task batches.""" @campaign.command("create") @click.argument("campaign_name", callback=_validate_plan_name_callback) @click.option("--project-dir", "project_dir", "-d", type=click.Path(path_type=Path), required=True) @click.option("--goal", "goal", "-g", required=True, help="Human-approved campaign objective.") @click.option( "--max-hours", type=click.FloatRange(min=1 / 60, max=24), default=4.0, show_default=True ) @click.option("--max-batches", type=click.IntRange(min=1, max=24), default=4, show_default=True) @click.option( "--max-total-tasks", type=click.IntRange(min=1, max=200), default=24, show_default=True ) @click.option( "--max-tasks-per-batch", type=click.IntRange(min=1, max=30), default=8, show_default=True ) @click.option( "--max-auto-resume-passes", type=click.IntRange(min=1, max=100), default=12, show_default=True ) @click.option( "--auto-accept-parent-coherence", is_flag=True, default=False, help=( "Automatically pass a decomposed parent after all children and the deterministic " "merged-child review pass." ), ) @click.option( "--lint-mode", type=click.Choice([mode.value for mode in LintMode]), default=None, help="Review policy for every batch.", ) @click.option( "--profile", type=click.Choice([profile.value for profile in ENABLED_ACCEPTANCE_PROFILES]), default=AcceptanceProfile.NONE.value, show_default=True, help="Human-approved acceptance profile applied to every mutating task in each batch.", ) @click.option( "--evidence-root", "evidence_roots", type=click.Path(path_type=Path), multiple=True, help="External immutable roots approved for every generated batch.", ) @click.option( "--require-release-witness", is_flag=True, default=False, help="Pause at release_ready until a human records an observed release witness.", ) @click.option( "--friction-audit", is_flag=True, default=False, help="Write bounded attempt summaries to an opt-in JSONL audit log.", ) @click.pass_context def campaign_create( ctx: click.Context, campaign_name: str, project_dir: Path, goal: str, max_hours: float, max_batches: int, max_total_tasks: int, max_tasks_per_batch: int, max_auto_resume_passes: int, auto_accept_parent_coherence: bool, lint_mode: str | None, profile: str, evidence_roots: tuple[Path, ...], require_release_witness: bool, friction_audit: bool, ) -> None: """Save a campaign; planning and mutation begin only with ``campaign run``.""" import afk_developer.cli as cli config: Config = ctx.obj["config"] target = project_dir.resolve() if not target.is_dir(): raise click.UsageError(f"Project directory does not exist: {target}") store = CampaignStore(config.projects_dir) if store.load(campaign_name) is not None: raise click.UsageError(f"Campaign '{campaign_name}' already exists.") selected_profile = AcceptanceProfile(profile) try: normalized_roots = ( normalize_evidence_roots([str(root) for root in evidence_roots], project_dir=target) if evidence_roots else [] ) except EvidencePacketError as exc: raise click.UsageError(str(exc)) from exc if selected_profile is AcceptanceProfile.CORPUS_RAW_OUTPUT and not normalized_roots: raise click.UsageError("corpus_raw_output campaigns require at least one --evidence-root.") state = CampaignState( name=campaign_name, project_dir=target, root_goal=goal, lint_mode=(lint_mode or config.lint_mode.value), acceptance_profile=selected_profile.value, evidence_roots=normalized_roots, friction_audit_enabled=friction_audit, require_release_witness=require_release_witness, limits=CampaignLimits( max_batches=max_batches, max_total_tasks=max_total_tasks, max_tasks_per_batch=max_tasks_per_batch, max_active_seconds=round(max_hours * 3600), max_auto_resume_passes=max_auto_resume_passes, require_supervisor_parent_coherence=not auto_accept_parent_coherence, ), ) path = store.save(state) cli.console.print( "[green]Campaign saved.[/green] " f"{campaign_name}: up to {max_batches} batches, {max_total_tasks} tasks, and {max_hours:g} active hour(s).\n" f"State: {path}\n" f"Run explicitly with: afk campaign run {campaign_name} --yes\n" f"Or draft a phased roadmap with: afk campaign plan {campaign_name}" ) def _target_local_interpreter(config: Config, target: Path) -> Path: if config.target_python is not None: candidate = _normalize_interpreter(config.target_python) if candidate.is_file() and candidate.is_relative_to(_normalize_interpreter(target)): return candidate raise click.UsageError( "Configured target interpreter must exist inside the processor-core target: " f"{candidate}" ) relative = Path(".venv/Scripts/python.exe" if sys.platform == "win32" else ".venv/bin/python") candidate = _normalize_interpreter(target / relative) if not candidate.is_file(): raise click.UsageError( f"Processor-core target needs a local interpreter before campaign creation: {candidate}" ) return candidate def _full_hex_id(value: str, lengths: tuple[int, ...]) -> bool: return len(value) in lengths and all( character in "0123456789abcdefABCDEF" for character in value ) @campaign.command("create-core") @click.argument("campaign_name", callback=_validate_plan_name_callback) @click.option("--project-dir", "project_dir", "-d", type=click.Path(path_type=Path), required=True) @click.option("--architecture", required=True, help="Processor architecture and revision.") @click.option("--package-name", required=True, help="Flat Python import package name.") @click.option("--oracle-name", required=True, help="Human-readable primary oracle name.") @click.option("--oracle-repository", required=True, help="Primary oracle repository URL.") @click.option("--oracle-revision", required=True, help="Full immutable Git object ID.") @click.option("--oracle-scale", required=True, help="Verified corpus size and partition count.") @click.option("--oracle-sha256", default="", help="Optional primary artifact SHA-256.") @click.option( "--scope-file", type=click.Path(path_type=Path, exists=True, dir_okay=False), help="Optional architecture-specific scope supplement.", ) @click.option( "--max-hours", type=click.FloatRange(min=1 / 60, max=24), default=16.0, show_default=True ) @click.option("--max-batches", type=click.IntRange(min=1, max=24), default=8, show_default=True) @click.option( "--max-total-tasks", type=click.IntRange(min=1, max=200), default=120, show_default=True ) @click.option( "--max-tasks-per-batch", type=click.IntRange(min=1, max=30), default=20, show_default=True ) @click.option( "--max-auto-resume-passes", type=click.IntRange(min=1, max=100), default=24, show_default=True ) @click.pass_context def campaign_create_core( ctx: click.Context, campaign_name: str, project_dir: Path, architecture: str, package_name: str, oracle_name: str, oracle_repository: str, oracle_revision: str, oracle_scale: str, oracle_sha256: str, scope_file: Path | None, max_hours: float, max_batches: int, max_total_tasks: int, max_tasks_per_batch: int, max_auto_resume_passes: int, ) -> None: """Create an unapproved oracle-backed processor-core campaign.""" import afk_developer.cli as cli config: Config = ctx.obj["config"] target = project_dir.resolve() if not target.is_dir(): raise click.UsageError(f"Project directory does not exist: {target}") git_state = cli._git_worktree_state(target) if git_state != "clean worktree": raise click.UsageError( f"Processor-core target must be an isolated clean Git worktree; found {git_state}." ) interpreter = _target_local_interpreter(config, target) if not package_name.isidentifier(): raise click.UsageError("Package name must be one flat valid Python identifier.") oracle_revision = oracle_revision.strip() if not _full_hex_id(oracle_revision, (40, 64)): raise click.UsageError("Oracle revision must be a full 40- or 64-character Git object ID.") oracle_sha256 = oracle_sha256.strip() if oracle_sha256 and not _full_hex_id(oracle_sha256, (64,)): raise click.UsageError("Oracle SHA-256 must contain exactly 64 hexadecimal characters.") scope = scope_file.read_text(encoding="utf-8").strip() if scope_file else "" if scope_file and not scope: raise click.UsageError("Scope file must not be empty.") store = CampaignStore(config.projects_dir) if store.load(campaign_name) is not None: raise click.UsageError(f"Campaign '{campaign_name}' already exists.") goal = build_processor_core_goal( ProcessorCoreGoalSpec( campaign_name=campaign_name, architecture=architecture.strip(), package_name=package_name, target=target, interpreter=interpreter, oracle_name=oracle_name.strip(), oracle_repository=oracle_repository.strip(), oracle_revision=oracle_revision.lower(), oracle_scale=oracle_scale.strip(), oracle_sha256=oracle_sha256.lower(), scope=scope, ) ) state = CampaignState( name=campaign_name, project_dir=target, root_goal=goal, lint_mode=LintMode.STRICT.value, friction_audit_enabled=True, limits=CampaignLimits( max_batches=max_batches, max_total_tasks=max_total_tasks, max_tasks_per_batch=max_tasks_per_batch, max_active_seconds=round(max_hours * 3600), max_auto_resume_passes=max_auto_resume_passes, require_supervisor_parent_coherence=False, ), ) path = store.save(state) cli.console.print( "[green]Processor-core campaign saved; no planning or execution occurred.[/green]\n" f"State: {path}\n" f"1. Draft the roadmap: afk campaign plan {campaign_name}\n" f"2. Observe all work: afk status --watch\n" f"3. Review, then approve explicitly: afk campaign approve {campaign_name}\n" f"4. Start bounded work: afk campaign work {campaign_name} --yes --workers 1 --best-of 1" ) @campaign.command("plan") @click.argument("campaign_name") @click.option( "--feedback", default="", help="Feedback for the reasoner to revise the previous roadmap draft.", ) @click.option( "--approve-each-phase", is_flag=True, default=False, help="Pause for human re-approval before each new phase after phase 1.", ) @click.pass_context def campaign_plan( ctx: click.Context, campaign_name: str, feedback: str, approve_each_phase: bool ) -> None: """Draft (or redraft) a phase roadmap and phase 1's task DAG; nothing executes yet. Re-runnable with ``--feedback`` until ``campaign approve`` locks it in. A human may hand-edit the saved campaign JSON before approving. """ import afk_developer.cli as cli config: Config = ctx.obj["config"] store = CampaignStore(config.projects_dir) state = store.load(campaign_name) if state is None: raise click.UsageError(f"No saved campaign found for '{campaign_name}'.") if state.status in TERMINAL_CAMPAIGN_STATUSES: raise click.UsageError(f"Campaign '{campaign_name}' is already {state.status.value}.") if state.ever_approved: raise click.UsageError( f"Campaign '{campaign_name}' has already been approved and may have started " "executing a phase; cancel and recreate to draft a new roadmap." ) if state.batches and not state.phases: raise click.UsageError( f"Campaign '{campaign_name}' already has an unphased durable queue; phased " "planning is only for a campaign that has not yet been stepped/worked." ) try: lock_path = store.acquire_run_lock(campaign_name) except Exception as exc: raise click.UsageError(str(exc)) from exc try: try: usage_before = AttemptUsage.from_stats(config.stats) phases = plan_phase_roadmap(state, config=config, feedback=feedback) _add_usage( state.reasoner_usage, usage_before.delta_to(AttemptUsage.from_stats(config.stats)) ) except PhaseRoadmapError as exc: raise click.ClickException(str(exc)) from exc if len(phases) > state.limits.max_phases: raise click.ClickException( f"Roadmap has {len(phases)} phases; limit is {state.limits.max_phases}." ) _campaign_discard_unapproved_phase_plans(config, state) state.phases = phases state.approve_each_phase = approve_each_phase or state.approve_each_phase state.roadmap_fingerprint = "" store.save(state) _campaign_expand_phase(config, state, state.phases[0]) store.save(state) finally: store.release_run_lock(lock_path) phase_one_name = cli._safe(phases[0].name) cli.console.print( f"[green]Roadmap drafted for '{campaign_name}':[/green] {len(phases)} phase(s).\n" f"Phase 1 ('{phase_one_name}') planned with {state.batches[-1].task_count} task(s).\n" f"Review the saved campaign JSON, then run: afk campaign approve {campaign_name}" ) for phase in phases: cli.console.print( f" {phase.ordinal}. {cli._safe(phase.name)} - {cli._safe(phase.goal[:100])}" ) cli.console.print(f" closure metric: {_describe_closure_metric(phase.closure_metric)}") cli.console.print(f" Campaign closure metric: {_describe_closure_metric(state.closure_metric)}") def _describe_closure_metric(metric) -> str: from rich.markup import escape if metric is None: return "[yellow](none -- nothing measurable fails if this is half done)[/yellow]" reading = "" if metric.last_value is None else f" now {metric.last_value}," return escape(f"{metric.name}:{reading} target {metric.describe_target()} via `{metric.command}`") def _reject_already_satisfied_phase_metrics(config: Config, state) -> None: """Refuse a roadmap carrying a phase metric that is already at its target. Only the root metric is measured before phase 1, so a phase whose metric can never read non-zero would otherwise sail through approval and be discovered as a useless gate hours into the run -- or never, because a metric that starts satisfied closes its phase no matter what happened. A metric that cannot RUN yet is left alone: later phases legitimately measure paths that earlier phases create, and those are validated at their own phase start. Only a metric that runs and is already satisfied is a provable defect here. """ from afk_developer.closure_metric import ClosureMetricError, measure_closure_metric broken: list[str] = [] for phase in state.phases: metric = phase.closure_metric if metric is None or phase.status not in (PhaseStatus.PLANNED, PhaseStatus.ACTIVE): continue try: value = measure_closure_metric( metric, state.project_dir, target_python=config.target_python, timeout=config.max_shell_timeout, ) except ClosureMetricError: continue if metric.satisfied_by(value): broken.append( f"{phase.ordinal} ('{phase.name}'): '{metric.name}' already reads {value} " f"({metric.describe_target()})" ) if broken: listing = "; ".join(broken) raise click.UsageError( f"Phase closure metric(s) already satisfied before any work starts: {listing}. " "Such a metric cannot tell a half-done phase from a finished one, so the phase " "would close on it regardless of the outcome. Redraft with: " "afk campaign plan --feedback" ) @campaign.command("approve") @click.argument("campaign_name") @click.option( "--allow-unmeasured-phases", is_flag=True, default=False, help="Approve even though some phases declare no closure metric (no half-done oracle).", ) @click.pass_context def campaign_approve(ctx: click.Context, campaign_name: str, allow_unmeasured_phases: bool) -> None: """Lock in the saved phase roadmap so ``campaign step``/``work`` may run it.""" import afk_developer.cli as cli config: Config = ctx.obj["config"] store = CampaignStore(config.projects_dir) state = store.load(campaign_name) if state is None: raise click.UsageError(f"No saved campaign found for '{campaign_name}'.") if state.status in TERMINAL_CAMPAIGN_STATUSES: raise click.UsageError(f"Campaign '{campaign_name}' is already {state.status.value}.") if not state.phases: raise click.UsageError( f"Campaign '{campaign_name}' has no drafted roadmap. Run: " f"afk campaign plan {campaign_name}" ) unmeasured = [ phase for phase in state.phases if phase.closure_metric is None and phase.status in (PhaseStatus.PLANNED, PhaseStatus.ACTIVE) ] if state.closure_metric is None and not allow_unmeasured_phases: raise click.UsageError( "The campaign itself declares no closure metric, so nothing would fail if the " "objective were only half done. Add a top-level closure_metric to the saved campaign " "JSON (or redraft with: afk campaign plan --feedback), or accept the risk explicitly " "with --allow-unmeasured-phases." ) if unmeasured and not allow_unmeasured_phases: listing = ", ".join(f"{phase.ordinal} ('{phase.name}')" for phase in unmeasured) raise click.UsageError( f"Phase(s) {listing} declare no closure metric, so nothing would fail if they were " "only half done. Add a closure_metric to each in the saved campaign JSON (or redraft " "with: afk campaign plan --feedback), or accept the risk explicitly with " "--allow-unmeasured-phases." ) _reject_already_satisfied_phase_metrics(config, state) for phase in state.phases: cli.console.print( f" {phase.ordinal}. {cli._safe(phase.name)} - closure metric: " f"{_describe_closure_metric(phase.closure_metric)}" ) cli.console.print(f" Campaign closure metric: {_describe_closure_metric(state.closure_metric)}") state.roadmap_fingerprint = phase_roadmap_fingerprint(state.phases) state.plan_approved = True state.ever_approved = True if state.status is CampaignStatus.PAUSED: state.status = CampaignStatus.READY state.stop_reason = "" store.save(state) cli.console.print( f"[green]Campaign '{campaign_name}' approved.[/green] {len(state.phases)} phase(s) " f"locked in (fingerprint {state.roadmap_fingerprint[:12]}). " f"Run with: afk campaign work {campaign_name} --yes" ) @campaign.command("extend") @click.argument("campaign_name") @click.option( "--additional-hours", type=click.FloatRange(min=1 / 60, max=24), required=True, help="Additional human-approved active-time budget, up to 24 hours total.", ) @click.pass_context def campaign_extend(ctx: click.Context, campaign_name: str, additional_hours: float) -> None: """Explicitly extend an exhausted campaign's active-time budget. This is a supervisor action, not an automatic recovery path: it preserves the approved roadmap and durable task graph, records no hidden reset of consumed time, and only reopens campaigns stopped by the active-time governor. """ import afk_developer.cli as cli config: Config = ctx.obj["config"] store = CampaignStore(config.projects_dir) state = store.load(campaign_name) if state is None: raise click.UsageError(f"No saved campaign found for '{campaign_name}'.") if ( state.status is not CampaignStatus.EXHAUSTED or state.stop_reason != "Active-time budget exhausted." ): raise click.UsageError( "Only a campaign exhausted by its active-time budget can be extended. " f"Current status: {state.status.value}." ) additional_seconds = round(additional_hours * 3600) new_limit = state.limits.max_active_seconds + additional_seconds max_seconds = 24 * 3600 if new_limit > max_seconds: remaining_hours = max((max_seconds - state.limits.max_active_seconds) / 3600, 0.0) raise click.UsageError( "The extension would exceed the 24-hour active-time ceiling; " f"at most {remaining_hours:g} additional hour(s) are available." ) state.limits.max_active_seconds = new_limit state.status = CampaignStatus.READY state.stop_reason = "" store.save(state) cli.console.print( f"[green]Campaign '{campaign_name}' extended.[/green] " f"Active-time limit is now {new_limit / 3600:g} hour(s); " f"{state.remaining_active_seconds() / 3600:g} hour(s) remain. " f"Resume with: afk campaign work {campaign_name} --yes" ) _REPLACEMENT_RUNTIME_FIELDS = { "status", "retry_count", "files_created", "blocked_reason", "not_applicable_reason", "failure_kind", "failure_detail", "attempts", "leased_at", "lease_expires_at", "lease_owner", "lifecycle_phase", "recovery_action", "parent_task_id", "subtask_ids", "decomposition_fingerprints", "decomposition_depth", } @campaign.command("replace-task") @click.argument("campaign_name") @click.argument("task_id") @click.option( "--spec", "spec_path", type=click.Path(exists=True, dir_okay=False, path_type=Path), required=True, ) @click.option("--reason", required=True) @click.option("--dry-run", is_flag=True, default=False) @click.pass_context def campaign_replace_task( ctx: click.Context, campaign_name: str, task_id: str, spec_path: Path, reason: str, dry_run: bool, ) -> None: """Retire one bad task and splice in a narrow, audited replacement DAG.""" import afk_developer.cli as cli config: Config = ctx.obj["config"] store = CampaignStore(config.projects_dir) try: raw_spec = json.loads(spec_path.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError) as exc: raise click.UsageError(f"Could not read replacement spec: {exc}") from exc entries = raw_spec.get("tasks") if isinstance(raw_spec, dict) else raw_spec if not isinstance(entries, list): raise click.UsageError( "Replacement spec must be a JSON list or an object with a 'tasks' list." ) if any( not isinstance(entry, dict) or _REPLACEMENT_RUNTIME_FIELDS & set(entry) for entry in entries ): raise click.UsageError("Replacement specs may not supply runtime state fields.") try: replacements = [TaskNode.model_validate(entry) for entry in entries] except Exception as exc: raise click.UsageError(f"Invalid replacement task specification: {exc}") from exc try: lock_path = store.acquire_run_lock(campaign_name) except Exception as exc: raise click.UsageError(str(exc)) from exc try: state = store.load(campaign_name) if state is None: raise click.UsageError(f"No saved campaign found for '{campaign_name}'.") if state.status in AMENDMENT_BLOCKING_CAMPAIGN_STATUSES: raise click.UsageError(f"Campaign '{campaign_name}' is already {state.status.value}.") if not state.batches: raise click.UsageError("Campaign has no durable task plan to amend.") plan_name = state.batches[-1].plan_name loaded = cli._load_plan(config, plan_name) if loaded is None: raise click.UsageError(f"Campaign plan '{plan_name}' is missing.") _repair_legacy_audit_path(state, plan_name, loaded[0]) amended = replace_task(loaded[0], task_id, replacements, reason) initialize_plan_recovery(amended, amended.recovery) amendment = amended.supervisor_amendments[-1] if dry_run: cli.console.print( f"[yellow]Dry run:[/yellow] {task_id} -> {', '.join(amendment.replacement_task_ids)}; " f"rewires: {', '.join(amendment.affected_downstream_ids) or '(none)'}" ) return cli._save_loaded_plan(config, amended, loaded) batch = next(batch for batch in state.batches if batch.plan_name == plan_name) batch.task_count = logical_task_count(amended) store.save(state) except SupervisorAmendmentError as exc: raise click.UsageError(str(exc)) from exc finally: store.release_run_lock(lock_path) cli.console.print( f"[green]Supervisor amendment recorded.[/green] Retired {task_id}; inserted " f"{', '.join(amendment.replacement_task_ids)}." ) @campaign.command("replace-unstarted-phase") @click.argument("campaign_name") @click.option( "--spec", "spec_path", type=click.Path(exists=True, dir_okay=False, path_type=Path), required=True, ) @click.option("--reason", required=True) @click.pass_context def campaign_replace_unstarted_phase( ctx: click.Context, campaign_name: str, spec_path: Path, reason: str ) -> None: """Replace an unapproved, unstarted phase queue with a narrow audited DAG.""" import afk_developer.cli as cli config: Config = ctx.obj["config"] try: raw_spec = json.loads(spec_path.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError) as exc: raise click.UsageError(f"Could not read replacement spec: {exc}") from exc entries = raw_spec.get("tasks") if isinstance(raw_spec, dict) else raw_spec if not isinstance(entries, list): raise click.UsageError( "Replacement spec must be a JSON list or an object with a 'tasks' list." ) if any( not isinstance(entry, dict) or _REPLACEMENT_RUNTIME_FIELDS & set(entry) for entry in entries ): raise click.UsageError("Replacement specs may not supply runtime state fields.") try: replacements = [TaskNode.model_validate(entry) for entry in entries] except Exception as exc: raise click.UsageError(f"Invalid replacement task specification: {exc}") from exc store = CampaignStore(config.projects_dir) try: lock_path = store.acquire_run_lock(campaign_name) except Exception as exc: raise click.UsageError(str(exc)) from exc try: state = store.load(campaign_name) if state is None: raise click.UsageError(f"No saved campaign found for '{campaign_name}'.") if state.status is not CampaignStatus.PAUSED or state.plan_approved: raise click.UsageError("Only an unapproved paused campaign phase may be replaced.") phase = state.active_phase() if phase is None or not phase.plan_name: raise click.UsageError("Campaign has no unstarted active phase plan to replace.") loaded = cli._load_plan(config, phase.plan_name) if loaded is None: raise click.UsageError(f"Campaign plan '{phase.plan_name}' is missing.") _repair_legacy_audit_path(state, phase.plan_name, loaded[0]) amended = replace_unstarted_phase_tasks(loaded[0], replacements, reason) initialize_plan_recovery(amended, amended.recovery) cli._save_loaded_plan(config, amended, loaded) batch = next(batch for batch in state.batches if batch.plan_name == phase.plan_name) batch.task_count = logical_task_count(amended) store.save(state) except SupervisorAmendmentError as exc: raise click.UsageError(str(exc)) from exc finally: store.release_run_lock(lock_path) cli.console.print( "[green]Unstarted phase queue replaced.[/green] " f"Retired the padded queue; inserted {', '.join(task.id for task in replacements)}." ) @campaign.command("verify-task") @click.argument("campaign_name") @click.argument("task_id") @click.option("--reason", required=True) @click.pass_context def campaign_verify_task(ctx: click.Context, campaign_name: str, task_id: str, reason: str) -> None: """Record direct supervisor verification of one escalated task.""" import afk_developer.cli as cli config: Config = ctx.obj["config"] store = CampaignStore(config.projects_dir) try: lock_path = store.acquire_run_lock(campaign_name) except Exception as exc: raise click.UsageError(str(exc)) from exc try: state = store.load(campaign_name) if state is None: raise click.UsageError(f"No saved campaign found for '{campaign_name}'.") if state.status not in {CampaignStatus.READY, CampaignStatus.ESCALATED}: raise click.UsageError( "Direct verification requires a ready or escalated campaign. " f"Current status: {state.status.value}." ) if not state.batches: raise click.UsageError("Campaign has no durable task plan to amend.") plan_name = state.batches[-1].plan_name loaded = cli._load_plan(config, plan_name) if loaded is None: raise click.UsageError(f"Campaign plan '{plan_name}' is missing.") _repair_legacy_audit_path(state, plan_name, loaded[0]) amended = mark_task_verified(loaded[0], task_id, reason) cli._save_loaded_plan(config, amended, loaded) state.status = CampaignStatus.READY state.stop_reason = "" store.save(state) except SupervisorAmendmentError as exc: raise click.UsageError(str(exc)) from exc finally: store.release_run_lock(lock_path) cli.console.print( f"[green]Supervisor verification recorded.[/green] {task_id} passed; " "campaign is ready to continue." ) def _decide_foreman_proposal( ctx: click.Context, campaign_name: str, proposal_id: str, reason: str, *, approve: bool, ) -> tuple[str, list[str]]: import afk_developer.cli as cli config: Config = ctx.obj["config"] store = CampaignStore(config.projects_dir) try: lock_path = store.acquire_run_lock(campaign_name) except Exception as exc: raise click.UsageError(str(exc)) from exc try: state = store.load(campaign_name) if state is None: raise click.UsageError(f"No saved campaign found for '{campaign_name}'.") if state.status not in {CampaignStatus.READY, CampaignStatus.ESCALATED}: raise click.UsageError( "Foreman proposal decisions require a ready or escalated campaign. " f"Current status: {state.status.value}." ) if not state.batches: raise click.UsageError("Campaign has no durable task plan to amend.") plan_name = state.batches[-1].plan_name loaded = cli._load_plan(config, plan_name) if loaded is None: raise click.UsageError(f"Campaign plan '{plan_name}' is missing.") _repair_legacy_audit_path(state, plan_name, loaded[0]) amended = ( approve_foreman_proposal(loaded[0], proposal_id, reason) if approve else reject_foreman_proposal(loaded[0], proposal_id, reason) ) proposal = next(item for item in amended.foreman_proposals if item.id == proposal_id) cli._save_loaded_plan(config, amended, loaded) batch = next(batch for batch in state.batches if batch.plan_name == plan_name) batch.task_count = logical_task_count(amended) state.status = CampaignStatus.READY state.stop_reason = "" store.save(state) return proposal.parent_task_id, [child.id for child in proposal.subtasks] except SupervisorAmendmentError as exc: raise click.UsageError(str(exc)) from exc finally: store.release_run_lock(lock_path) @campaign.command("approve-decomposition") @click.argument("campaign_name") @click.argument("proposal_id") @click.option("--reason", required=True) @click.pass_context def campaign_approve_decomposition( ctx: click.Context, campaign_name: str, proposal_id: str, reason: str ) -> None: """Apply one foreman proposal after supervisor contract and coverage review.""" import afk_developer.cli as cli parent_id, child_ids = _decide_foreman_proposal( ctx, campaign_name, proposal_id, reason, approve=True ) cli.console.print( f"[green]Foreman proposal approved.[/green] {parent_id} delegated to: " f"{', '.join(child_ids)}." ) @campaign.command("reject-decomposition") @click.argument("campaign_name") @click.argument("proposal_id") @click.option("--reason", required=True) @click.pass_context def campaign_reject_decomposition( ctx: click.Context, campaign_name: str, proposal_id: str, reason: str ) -> None: """Record that a foreman proposal was rejected without changing the queue.""" import afk_developer.cli as cli parent_id, _ = _decide_foreman_proposal(ctx, campaign_name, proposal_id, reason, approve=False) cli.console.print( f"[yellow]Foreman proposal rejected.[/yellow] Parent remains escalated: {parent_id}." ) @campaign.command("acknowledge-checkpoint") @click.argument("campaign_name") @click.option("--reason", required=True) @click.pass_context def campaign_acknowledge_checkpoint(ctx: click.Context, campaign_name: str, reason: str) -> None: """Resume after a supervisor accepts evidence over an escalated completed checkpoint.""" import afk_developer.cli as cli if not reason.strip(): raise click.UsageError("A non-empty supervisor reason is required.") config: Config = ctx.obj["config"] store = CampaignStore(config.projects_dir) try: lock_path = store.acquire_run_lock(campaign_name) except Exception as exc: raise click.UsageError(str(exc)) from exc try: state = store.load(campaign_name) if state is None: raise click.UsageError(f"No saved campaign found for '{campaign_name}'.") if state.status is not CampaignStatus.ESCALATED: raise click.UsageError("Checkpoint acknowledgement requires an escalated campaign.") active = state.active_phase() if active is None: raise click.UsageError("No subsequent planned phase is available to resume.") completed = [phase for phase in state.phases if phase.ordinal < active.ordinal] if not completed or completed[-1].status is not PhaseStatus.COMPLETED: raise click.UsageError( "Only a completed preceding phase checkpoint may be acknowledged." ) state.checkpoint_acknowledgements.append( CheckpointAcknowledgement(phase_ordinal=completed[-1].ordinal, reason=reason.strip()) ) state.status = CampaignStatus.READY state.stop_reason = "" store.save(state) finally: store.release_run_lock(lock_path) cli.console.print( f"[green]Checkpoint acknowledgement recorded.[/green] Resuming phase {active.ordinal}." ) @campaign.command("attest-release") @click.argument("campaign_name") @click.option("--kind", required=True) @click.option("--summary", required=True) @click.option("--artifact", type=click.Path(path_type=Path), default=None) @click.pass_context def campaign_attest_release( ctx: click.Context, campaign_name: str, kind: str, summary: str, artifact: Path | None ) -> None: """Record a human release observation and complete an opted-in campaign.""" import afk_developer.cli as cli if not summary.strip(): raise click.UsageError("Release witness summary must be non-empty.") config: Config = ctx.obj["config"] store = CampaignStore(config.projects_dir) state = store.load(campaign_name) if state is None: raise click.UsageError(f"No saved campaign found for '{campaign_name}'.") if not state.require_release_witness or state.status is not CampaignStatus.RELEASE_READY: raise click.UsageError("Campaign is not awaiting an opt-in release witness.") artifact_path = "" artifact_hash = "" if artifact is not None: root = state.project_dir.resolve() candidate = artifact.resolve() if artifact.is_absolute() else (root / artifact).resolve() try: artifact_path = candidate.relative_to(root).as_posix() except ValueError as exc: raise click.UsageError("Release artifact must be inside the campaign project.") from exc if not candidate.is_file(): raise click.UsageError("Release artifact must be an existing regular file.") artifact_hash = hashlib.sha256(candidate.read_bytes()).hexdigest() state.release_attestation = ReleaseAttestation( kind=kind, summary=summary.strip(), artifact_path=artifact_path, artifact_sha256=artifact_hash, ) state.status = CampaignStatus.COMPLETED state.stop_reason = "Human release witness recorded." store.save(state) cli.console.print("[green]Human release witness recorded; campaign completed.[/green]") @campaign.command("run") @click.argument("campaign_name") @click.option( "--yes", "yes", is_flag=True, default=False, help="Approve this bounded autonomous run." ) @click.pass_context def campaign_run(ctx: click.Context, campaign_name: str, yes: bool) -> None: """Plan, execute, checkpoint, and optionally queue bounded follow-up batches.""" import afk_developer.cli as cli config: Config = ctx.obj["config"] if cli._other_afk_processes_active(include_campaign_runs=False): raise click.UsageError( "Another AFK execution appears active; campaign runs require exclusive access." ) store = CampaignStore(config.projects_dir) state = store.load(campaign_name) if state is None: raise click.UsageError(f"No saved campaign found for '{campaign_name}'.") if state.phases: raise click.UsageError( f"Campaign '{campaign_name}' is a phased campaign; use 'afk campaign step/work' " "instead of 'campaign run'." ) if state.status in {CampaignStatus.COMPLETED, CampaignStatus.EXHAUSTED}: cli.console.print( f"[yellow]Campaign is already {state.status.value}:[/yellow] {state.stop_reason}" ) report_campaign_statistics( build_campaign_statistics(state, lambda name: cli._load_plan(config, name)) ) return if not yes and not click.confirm( f"Run campaign '{campaign_name}' for up to {state.remaining_active_seconds() / 3600:.2f} active hour(s)?", default=False, ): return def create_batch(current: CampaignState, goal: str) -> CampaignBatch: return _campaign_create_batch(config, current, goal) def execute_batch(current: CampaignState, batch: CampaignBatch) -> tuple[bool, list[str], str]: return _campaign_execute_batch(config, current, batch) def reflect(current: CampaignState, batch: CampaignBatch, summaries: list[str]): return reflect_on_completed_batch( current, batch, config=config, completed_task_summaries=summaries ) try: lock_path = store.acquire_run_lock(campaign_name) except Exception as exc: raise click.UsageError(str(exc)) from exc try: try: result = run_campaign( state, store=store, create_batch=create_batch, execute_batch=execute_batch, reflect=reflect, ) except KeyboardInterrupt: state.status = CampaignStatus.PAUSED state.stop_reason = "Campaign run interrupted; resume explicitly when ready." store.save(state) result = state cli.console.print("[yellow]Campaign paused after interruption.[/yellow]") finally: store.release_run_lock(lock_path) style = "green" if result.status is CampaignStatus.COMPLETED else "yellow" cli.console.print( f"[{style}]Campaign {result.status.value}.[/{style}] " f"Batches: {len(result.batches)}; tasks planned: {result.total_tasks}; " f"active time: {result.active_seconds / 3600:.2f}h. {result.stop_reason}" ) report_campaign_statistics( build_campaign_statistics(result, lambda name: cli._load_plan(config, name)) ) @campaign.command("status") @click.argument("campaign_name") @click.option( "--watch", is_flag=True, default=False, help="Continuously poll and re-render (read-only)." ) @click.option( "--interval", type=click.FloatRange(min=0.2), default=2.0, show_default=True, help="Polling interval in seconds for --watch.", ) @click.option( "--attempts", "attempt_task_id", default=None, help="Show friction attempt summaries for one task (requires --friction-audit).", ) @click.pass_context def campaign_status( ctx: click.Context, campaign_name: str, watch: bool, interval: float, attempt_task_id: str | None, ) -> None: """Show durable campaign limits, progress, and the latest checkpoint decision.""" from rich.markup import escape import afk_developer.cli as cli config: Config = ctx.obj["config"] store = CampaignStore(config.projects_dir) state = store.load(campaign_name) if state is None: raise click.UsageError(f"No saved campaign found for '{campaign_name}'.") if attempt_task_id is not None: from afk_developer.events import load_attempt_summaries if not state.batches: raise click.UsageError("Campaign has no durable queue plan yet.") loaded = cli._load_plan(config, state.batches[-1].plan_name) if loaded is None or not loaded[0].audit_log_path: raise click.UsageError("No friction audit is enabled for the active campaign plan.") summaries = load_attempt_summaries( config.projects_dir / loaded[0].audit_log_path, attempt_task_id ) if not summaries: cli.console.print(f"No attempt summaries recorded for {attempt_task_id}.") return for summary in summaries: cli.console.print( f"{summary.get('attempt_id', '?')}: {summary.get('outcome', '?')}; " f"turns={summary.get('total_turns', 0)} tokens={summary.get('total_tokens', 0)} " f"api_calls={summary.get('api_calls', 0)} files={len(summary.get('files_changed', []))}" ) return if watch: from afk_developer.watch import SnapshotLoadError, build_status_view, watch_loop from afk_developer.watch import load_json_snapshot as _load_snapshot campaign_path = store.path_for(campaign_name) plan_name = state.batches[-1].plan_name if state.batches else None plan_path = cli._get_plan_path(config, plan_name) if plan_name else None try: campaign_snapshot = _load_snapshot(campaign_path) plan_snapshot = _load_snapshot(plan_path) if plan_path is not None else None except SnapshotLoadError as exc: raise click.ClickException(str(exc)) from exc def render(): nonlocal campaign_snapshot, plan_snapshot campaign_snapshot = _load_snapshot(campaign_path, previous=campaign_snapshot) if plan_path is not None: plan_snapshot = _load_snapshot(plan_path, previous=plan_snapshot) return build_status_view( plan_snapshot.payload if plan_snapshot is not None else None, campaign_snapshot.payload, now=datetime.now(timezone.utc), stale=campaign_snapshot.stale or (plan_snapshot.stale if plan_snapshot is not None else False), plan_mtime=plan_snapshot.mtime if plan_snapshot is not None else None, ) watch_loop(cli.console, interval, render) cli.console.print("\n[dim]Stopped watching.[/dim]") return cli.console.print( f"[bold]{state.name}[/bold] — {state.status.value}\n" f"Batches: {len(state.batches)}/{state.limits.max_batches}; tasks: {state.total_tasks}/{state.limits.max_total_tasks}; " f"active time: {state.active_seconds / 3600:.2f}/{state.limits.max_active_seconds / 3600:.2f}h\n" f"Stop/checkpoint: {state.stop_reason or '(none)'}" ) if state.phases: marker = { PhaseStatus.PLANNED: escape("[ ]"), PhaseStatus.ACTIVE: escape("[>]"), PhaseStatus.COMPLETED: escape("[x]"), PhaseStatus.SKIPPED: escape("[skip]"), } resolved = sum( phase.status in (PhaseStatus.COMPLETED, PhaseStatus.SKIPPED) for phase in state.phases ) cli.console.print( f"Phases: {resolved}/{len(state.phases)} resolved; approved={state.plan_approved}" ) for phase in state.phases: cli.console.print(f" {marker[phase.status]} {phase.ordinal}. {escape(phase.name)}") if phase.closure_metric is not None: cli.console.print(f" closure metric: {_describe_closure_metric(phase.closure_metric)}") if phase.divergence_note: cli.console.print(f" [yellow]diverged:[/yellow] {escape(phase.divergence_note)}") # An adaptive roadmap that changes silently is not auditable. if state.phase_amendments: cli.console.print( f"Roadmap amendments: {len(state.phase_amendments)}/" f"{state.limits.max_phase_amendments} used" ) for amendment in state.phase_amendments: cli.console.print(f" - {escape(amendment.describe())}") if state.status is CampaignStatus.RELEASE_READY: cli.console.print( "[yellow]Release witness required:[/yellow] awaiting a human observation." ) if state.release_attestation is not None: cli.console.print( "[cyan]Human release witness:[/cyan] " f"{escape(state.release_attestation.kind)} — " f"{escape(state.release_attestation.summary)}" ) report_campaign_statistics( build_campaign_statistics(state, lambda name: cli._load_plan(ctx.obj["config"], name)) ) @campaign.command("step") @click.argument("campaign_name") @click.pass_context def campaign_step(ctx: click.Context, campaign_name: str) -> None: """Advance a durable campaign queue by exactly one leased task and one bounded sprint. Safe to run from an entirely new process: all state (the queue plan and campaign progress) is durable, so this can be invoked repeatedly across many independent short-lived runs and will resume without duplicating completed work. """ import afk_developer.cli as cli config: Config = ctx.obj["config"] store = CampaignStore(config.projects_dir) state = store.load(campaign_name) if state is None: raise click.UsageError(f"No saved campaign found for '{campaign_name}'.") if state.status in TERMINAL_CAMPAIGN_STATUSES: cli.console.print( f"[yellow]Campaign is already {state.status.value}:[/yellow] {state.stop_reason}" ) return if state.phases and not state.plan_approved: raise click.UsageError( f"Campaign '{campaign_name}' has a drafted but unapproved phase roadmap. Run: " f"afk campaign approve {campaign_name}" ) if cli._other_afk_processes_active(include_campaign_runs=False): raise click.UsageError( "Another AFK execution appears active; campaign runs require exclusive access." ) try: lock_path = store.acquire_run_lock(campaign_name) except Exception as exc: raise click.UsageError(str(exc)) from exc try: result = continue_campaign_once( state, store=store, ensure_queue=lambda current: _campaign_ensure_queue(config, store, current), run_ready_task=lambda current, plan, task: _campaign_run_ready_task( config, current, plan, task ), persist_queue=lambda current, plan: _campaign_persist_queue(config, current, plan), ) finally: store.release_run_lock(lock_path) if result.task_id: cli.console.print( f"[bold]{campaign_name}[/bold]: ran task [cyan]{result.task_id}[/cyan] -> " f"{result.task_status}. {result.ready_tasks_remaining} ready task(s) remain." ) elif result.stalled: cli.console.print(f"[yellow]{campaign_name}[/yellow]: no runnable task. {result.note}") elif result.queue_complete: cli.console.print(f"[green]{campaign_name}[/green]: queue complete.") else: cli.console.print(f"[dim]{campaign_name}[/dim]: campaign status is {state.status.value}.") cli.console.print(f"Campaign status: {state.status.value}. {state.stop_reason}") @campaign.command("work") @click.argument("campaign_name") @click.option( "--yes", "yes", is_flag=True, default=False, help="Approve this bounded autonomous run." ) @click.option( "--workers", "workers", type=click.IntRange(1, 8), default=1, help="Run up to this many ready tasks concurrently, each in its own git worktree.", ) @click.option( "--best-of", "best_of", type=click.IntRange(1, 5), default=1, help=( "Run this many redundant coder_light attempts per task and keep the first to pass " "review, discarding the rest." ), ) @click.pass_context def campaign_work( ctx: click.Context, campaign_name: str, yes: bool, workers: int, best_of: int ) -> None: """Repeatedly continue a durable campaign queue, one bounded sprint at a time, until terminal. Deterministically dispatches ready tasks one at a time by default; Terra (the reasoner) is consulted only when the queue truly cannot make progress on its own. Stops at the campaign's configured attempt/time/cost budgets, on completion, or when escalated for a human. ``--workers N`` (N > 1) dispatches up to N independent ready tasks concurrently instead, each isolated in its own git worktree -- this is new and unverified under real parallel load; start small (2) before raising it. ``--best-of N`` (N > 1, opt-in) instead runs N redundant, cheaper ``coder_light`` attempts at *each* task and keeps only the first to pass review; it never applies to acceptance-profiled tasks. The two options may be combined. """ import afk_developer.cli as cli config: Config = ctx.obj["config"] store = CampaignStore(config.projects_dir) state = store.load(campaign_name) if state is None: raise click.UsageError(f"No saved campaign found for '{campaign_name}'.") if state.status in TERMINAL_CAMPAIGN_STATUSES: cli.console.print( f"[yellow]Campaign is already {state.status.value}:[/yellow] {state.stop_reason}" ) report_campaign_statistics( build_campaign_statistics(state, lambda name: cli._load_plan(config, name)) ) return if state.phases and not state.plan_approved: raise click.UsageError( f"Campaign '{campaign_name}' has a drafted but unapproved phase roadmap. Run: " f"afk campaign approve {campaign_name}" ) if workers > 1 and config.git_isolation != "worktree": raise click.UsageError( "--workers > 1 requires worktree git isolation. Set execution.isolation: worktree " "in config.yml (or AFK_GIT_ISOLATION=worktree) first." ) if cli._other_afk_processes_active(include_campaign_runs=False): raise click.UsageError( "Another AFK execution appears active; campaign runs require exclusive access." ) if not yes and not click.confirm( f"Work campaign '{campaign_name}' for up to {state.remaining_active_seconds() / 3600:.2f} " f"active hour(s){f' with {workers} parallel workers' if workers > 1 else ''}" f"{f', best-of-{best_of} per task' if best_of > 1 else ''}?", default=False, ): return git_lock = threading.Lock() if workers > 1 or best_of > 1 else None try: lock_path = store.acquire_run_lock(campaign_name) except Exception as exc: raise click.UsageError(str(exc)) from exc try: try: result = run_campaign_queue_until_terminal( state, store=store, ensure_queue=lambda current: _campaign_ensure_queue(config, store, current), run_ready_task=lambda current, plan, task: _campaign_run_ready_task( config, current, plan, task, git_lock=git_lock, best_of=best_of ), persist_queue=lambda current, plan: _campaign_persist_queue(config, current, plan), consult_stall=lambda current, plan: _campaign_consult_stall(config, current, plan), max_workers=workers, ) except KeyboardInterrupt: state.status = CampaignStatus.PAUSED state.stop_reason = "Campaign run interrupted; resume explicitly when ready." store.save(state) result = state cli.console.print("[yellow]Campaign paused after interruption.[/yellow]") finally: store.release_run_lock(lock_path) style = "green" if result.status is CampaignStatus.COMPLETED else "yellow" cli.console.print( f"[{style}]Campaign {result.status.value}.[/{style}] " f"Queue steps: {result.queue_steps_taken}/{result.limits.max_queue_steps}; " f"active time: {result.active_seconds / 3600:.2f}h. {result.stop_reason}" ) report_campaign_statistics( build_campaign_statistics(result, lambda name: cli._load_plan(config, name)) ) @campaign.command("cancel") @click.argument("campaign_name") @click.pass_context def campaign_cancel(ctx: click.Context, campaign_name: str) -> None: """Cancel a durable campaign; remaining unstarted/blocked/failed tasks stop permanently.""" import afk_developer.cli as cli config: Config = ctx.obj["config"] store = CampaignStore(config.projects_dir) state = store.load(campaign_name) if state is None: raise click.UsageError(f"No saved campaign found for '{campaign_name}'.") if state.status in TERMINAL_CAMPAIGN_STATUSES: cli.console.print(f"[yellow]Campaign is already {state.status.value}.[/yellow]") return lock_path = store.acquire_run_lock(campaign_name) try: state.status = CampaignStatus.CANCELLED state.stop_reason = "Cancelled by operator." if state.batches: loaded = cli._load_plan(config, state.batches[0].plan_name) if loaded is not None: plan = loaded[0] for task in plan.tasks: if task.status in { TaskStatus.PENDING, TaskStatus.RETRYING, TaskStatus.BLOCKED, TaskStatus.FAILED, }: task.status = TaskStatus.CANCELLED _campaign_persist_queue(config, state, plan) store.save(state) finally: store.release_run_lock(lock_path) cli.console.print(f"[yellow]Campaign '{campaign_name}' cancelled.[/yellow]")