import hashlib import json import os import re import sqlite3 import subprocess import threading from datetime import datetime, timezone from pathlib import Path import click from rich.console import Console from rich.panel import Panel from afk_developer import __version__ from afk_developer import fsutil from afk_developer.config import Config, DEFAULT_COPILOT_MODEL, LintMode, save_user_config from afk_developer.cortex.db import CortexDB from afk_developer.grillme.spec_model import TaskIntent from afk_developer.planner.task_model import ( TaskPlan, TaskStatus, ) from afk_developer.reporter import report_session_stats from afk_developer.scheduler.lint_baseline import ( LintBaseline, LintBaselineError, capture_ruff_baseline, load_baseline, run_ruff_json, save_baseline, validate_ruff_baseline, ) from afk_developer.scheduler.attempts import ( initialize_plan_recovery, ) from afk_developer.scheduler.manual_retry import run_manual_retry from afk_developer.campaign_cli import campaign from afk_developer.acceptance_cli import acceptance_profile, _configure_acceptance_profile # noqa: F401 (_configure_acceptance_profile re-exported for tests/test_evidence_packets.py) # Re-exported (unused in this module) because tests/test_cli.py imports it # directly from afk_developer.cli; the campaign group itself now gets its own # copy from campaign_runner.py via campaign_cli.py. from afk_developer.campaign_runner import _campaign_ensure_queue # noqa: F401 console = Console() def _safe(text: str) -> str: return text.encode("ascii", "replace").decode("ascii") ARCHIVE_DIR = Path.home() / ".afk-developer" / "prompts" _PLAN_NAME_PATTERN = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]*\Z") # Guards first-write creation of a per-project lint baseline against a # concurrent duplicate capture when multiple `--workers` threads race to be # the first task that needs one. _LINT_BASELINE_LOCK = threading.Lock() def _archive_prompt(project_name: str, goal: str) -> None: ARCHIVE_DIR.mkdir(parents=True, exist_ok=True) ts = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S") filename = f"{project_name}-{ts}.md" path = ARCHIVE_DIR / filename path.write_text(f"# {project_name}\n\n{goal}\n", encoding="utf-8") def _validate_plan_name(_: click.Context, __: click.Parameter, value: str | None) -> str | None: """Accept a filesystem-safe state name distinct from the target repository name.""" if value is None: return None if not _PLAN_NAME_PATTERN.fullmatch(value): raise click.BadParameter( "must contain only letters, numbers, dots, underscores, and hyphens " "and must not begin with punctuation" ) return value def _lint_baseline_path(config: Config, project_name: str) -> Path: return config.resolve_project_dir(project_name) / "lint-baseline.json" def _prepare_lint_baseline( config: Config, project_name: str, project_dir: Path, linter: str, lint_mode: LintMode, create_if_missing: bool, ) -> LintBaseline | None: if lint_mode is LintMode.STRICT: return None if linter.lower() != "ruff": raise LintBaselineError( f"Baseline lint mode is only supported for Ruff, not {linter or 'an unspecified linter'}." ) path = _lint_baseline_path(config, project_name) if path.exists(): baseline = load_baseline(path) current_lint = run_ruff_json(project_dir, python_executable=config.target_python) validate_ruff_baseline(baseline, project_dir, project_name, current_lint.version) return baseline if not create_if_missing: raise LintBaselineError( f"Baseline lint mode requires {path}. Run 'afk lint-baseline {project_name} -d {project_dir}' first." ) with _LINT_BASELINE_LOCK: # Re-check now that we hold the lock: another worker thread may have # already captured the baseline while we were waiting for it. if path.exists(): baseline = load_baseline(path) current_lint = run_ruff_json(project_dir, python_executable=config.target_python) validate_ruff_baseline(baseline, project_dir, project_name, current_lint.version) return baseline baseline = capture_ruff_baseline( project_dir, project_name, python_executable=config.target_python ) save_baseline(path, baseline) console.print( f"[cyan]Captured Ruff baseline:[/cyan] {baseline.diagnostic_count} diagnostics at {path}" ) return baseline def _resolve_lint_mode(config: Config, lint_mode: str | None) -> LintMode: return LintMode(lint_mode) if lint_mode else config.lint_mode def _resolve_max_auto_resume_passes(config: Config, override: int | None) -> int: return override if override is not None else config.max_auto_resume_passes def _other_afk_processes_active(*, include_campaign_runs: bool = True) -> bool: current_pid = os.getpid() campaign_runs = 0 if os.name == "nt": command = [ "powershell", "-NoProfile", "-Command", "Get-CimInstance Win32_Process -Filter \"Name = 'python.exe'\" | " 'ForEach-Object { "$($_.ProcessId)`t$($_.CommandLine)" }', ] else: command = ["ps", "-eo", "pid=,args="] try: result = subprocess.run( command, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=10, ) except (OSError, subprocess.TimeoutExpired): return True if result.returncode != 0: return True for line in (result.stdout or "").splitlines(): fields = line.strip().split(maxsplit=1) if len(fields) != 2: continue try: pid = int(fields[0]) except ValueError: continue command_line = fields[1] is_mutating_run = any( f"afk_developer.cli {command}" in command_line for command in ("grillme", "resume", "retry") ) is_campaign_run = "afk_developer.cli campaign run" in command_line if is_campaign_run: # Some Windows process listings expose the launch-wrapper PID rather # than the Python child's PID. Count campaign commands instead of # rejecting the sole current invocation as a concurrent process. campaign_runs += 1 continue if pid != current_pid and is_mutating_run: return True return include_campaign_runs and campaign_runs > 1 def _git_worktree_state(project_dir: Path) -> str: try: result = subprocess.run( ["git", "status", "--short"], cwd=str(project_dir), capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=30, ) except (OSError, subprocess.TimeoutExpired): return "Git state unavailable" if result.returncode != 0: return "not a Git worktree" return "dirty worktree" if (result.stdout or "").strip() else "clean worktree" ESTIMATE_BLENDED_RATE = 0.50 # USD per million tokens (legacy DeepSeek blended estimate) def _gather_all_sessions() -> list[dict]: import sqlite3 base = Path.home() / ".afk-developer" / "projects" if not base.exists(): return [] all_sessions: list[dict] = [] for proj_dir in base.iterdir(): if not proj_dir.is_dir(): continue db_path = proj_dir / "cortex.db" if not db_path.exists(): continue try: conn = sqlite3.connect(str(db_path)) conn.row_factory = sqlite3.Row rows = conn.execute( "SELECT * FROM session_stats ORDER BY saved_at DESC LIMIT 10" ).fetchall() conn.close() all_sessions.extend(dict(r) for r in rows) except Exception: pass return all_sessions[:50] def _estimate_cost(cortex: CortexDB, task_count: int) -> str: sessions = cortex.list_sessions(limit=20) if not sessions: sessions = cortex.list_all_sessions(limit=20) if not sessions: sessions = _gather_all_sessions() if not sessions: return None total_tokens = sum(s.get("total_tokens", 0) for s in sessions) total_tasks = sum(s.get("tasks_completed", 0) for s in sessions) if total_tasks == 0: return None total_copilot_value = sum(s.get("copilot_metered_value_usd", 0) for s in sessions) if total_copilot_value: estimated_value = (total_copilot_value / total_tasks) * task_count return ( f"Estimated Copilot AI-credit meter value: ~${estimated_value:.2f} " "(included credits may cover it; not an invoice)" ) if total_tokens == 0: return None tokens_per_task = total_tokens / total_tasks est_tokens = int(tokens_per_task * task_count) est_cost = (est_tokens / 1_000_000) * ESTIMATE_BLENDED_RATE rate_display = f"~${est_cost:.2f}" if est_cost >= 0.01 else "< $0.01" return f"Estimated: ~{est_tokens:,} tokens ({rate_display} at DeepSeek rates)" def _save_retry_session(cortex: CortexDB, config: Config, task) -> None: """Persist and display statistics for one terminal retry attempt.""" if task.status is TaskStatus.PASSED: config.stats.tasks_completed += 1 else: config.stats.tasks_failed += 1 cortex.save_session(config.stats.to_dict()) report_session_stats(config) @click.group() @click.version_option(version=__version__) @click.pass_context def main(ctx: click.Context): """AFK Developer — Autonomous background-coding engine with configurable AI endpoints.""" ctx.ensure_object(dict) config = Config.from_env() if not config.is_configured: console.print( Panel.fit( "[bold red]DEEPSEEK_API_KEY not set.[/bold red]\n\n" "Set your API key with:\n" " [bold]export DEEPSEEK_API_KEY=sk-...[/bold] (Linux/macOS)\n" " [bold]$env:DEEPSEEK_API_KEY='sk-...'[/bold] (PowerShell)\n" " [bold]set DEEPSEEK_API_KEY=sk-...[/bold] (CMD)", title="Configuration Error", border_style="red", ) ) raise click.Abort() ctx.obj["config"] = config @main.command() @click.option("--config-path", type=click.Path(path_type=Path), default=None) def setup(config_path: Path | None): """Configure endpoint profiles and role-specific models.""" from getpass import getpass console.print( Panel.fit( "[bold]AFK Developer setup[/bold]\n" "Credentials are stored in the OS credential vault; configuration stores references only.", border_style="blue", ) ) endpoint_type = click.prompt( "Default endpoint type", type=click.Choice(["copilot", "openai_compatible"], case_sensitive=False), default="copilot", ).lower() endpoint_name = "copilot" if endpoint_type == "copilot" else "deepseek" endpoint: dict[str, str] = {"type": endpoint_type} if endpoint_type == "openai_compatible": endpoint["base_url"] = click.prompt( "Endpoint base URL", default="https://api.deepseek.com" ).strip() secret_name = click.prompt( "Credential vault name", default=f"{endpoint_name}-api-key" ).strip() value = getpass(f"API key for '{secret_name}' (leave blank to keep unset): ").strip() if value: from afk_developer.secrets import store_secret store_secret(secret_name, value) console.print(f"[green]Stored credential '{secret_name}' in the OS vault.[/green]") endpoint["api_key_ref"] = f"${{secret:{secret_name}}}" reasoner_model = click.prompt("Reasoner model", default=DEFAULT_COPILOT_MODEL).strip() same_coder_model = click.confirm("Use the same model for coding?", default=True) coder_endpoint = endpoint_name coder_model = ( reasoner_model if same_coder_model else click.prompt("Coder model", default=reasoner_model).strip() ) raw = { "endpoints": {endpoint_name: endpoint}, "roles": { "reasoner": {"endpoint": endpoint_name, "model": reasoner_model, "timeout": 300}, "coder": {"endpoint": coder_endpoint, "model": coder_model, "timeout": 900}, }, } target = save_user_config(raw, config_path) console.print(f"[green]Configuration saved:[/green] {target}") console.print( f"[dim]Reasoner: {endpoint_name}/{reasoner_model}; " f"Coder: {coder_endpoint}/{coder_model}[/dim]" ) def _summarize_understanding(spec, config: Config) -> str: """Ask the LLM to summarize what it understands the task to be.""" from afk_developer.backends.registry import BackendRegistry content = ( f"GOAL: {spec.goal}\n" f"LANGUAGE: {spec.language or 'unknown'}\n" f"FRAMEWORK: {spec.framework or 'none'}\n" f"TEST FRAMEWORK: {spec.test_framework or 'none'}\n" f"CONSTRAINTS: {', '.join(spec.constraints) if spec.constraints else 'none'}\n" f"ADDITIONAL CONTEXT: {spec.additional_context or 'none'}\n" ) response = ( BackendRegistry(config) .get_reasoner() .complete( system_prompt=( "You are an expert software engineer reviewing a task specification. " "Summarize what you understand the user wants in 3-4 clear sentences. " "Be specific about the technologies, features, and constraints. " "Return ONLY plain text — no JSON, no markdown formatting." ), user_prompt=content, temperature=0.3, ) ) config.record_usage(response.usage, role="reasoner") return response.content.strip() def _refinement_loop(spec, config: Config): """Interactive refinement loop: clarify, summarize, add/clarify/execute/quit.""" from afk_developer.planner.clarify import ask_clarifying_questions console.print() round_num = 0 while True: round_num += 1 if round_num == 1: if not click.confirm("Would you like me to ask clarifying questions?", default=True): break # Step 1: Ask clarifying questions try: console.print("\n[dim]Thinking of clarifying questions...[/dim]") questions = ask_clarifying_questions(spec, config) for q in questions: default = q.get("default", "") console.print(f"\n[bold cyan]Q:[/bold cyan] {q['question']}") if default: console.print(f"[dim]Default: {default}[/dim]") answer = click.prompt(" >", type=str, default=default, show_default=False).strip() if answer: spec.additional_context += f"\nQ: {q['question']}\nA: {answer}" if not questions: console.print("[dim]No clarifying questions needed — spec is clear.[/dim]") except Exception as e: console.print(f"[yellow]Could not generate clarifying questions: {e}[/yellow]") # Step 2: Summarize understanding try: console.print("\n[dim]Summarizing my understanding...[/dim]") summary = _summarize_understanding(spec, config) console.print(Panel.fit(summary, title="What I Understand", border_style="cyan")) except Exception as e: console.print(f"[yellow]Could not summarize: {e}[/yellow]") break # Step 3: User chooses next action console.print("\n[bold]What next?[/bold]") console.print( " [bold][A][/bold]dd more context " "[bold][C][/bold]larify more " "[bold][E][/bold]xecute " "[bold][Q][/bold]uit & save" ) choice = click.getchar().lower() console.print() if choice == "a": additional = click.prompt( "Additional context", type=str, default="", show_default=False ).strip() if additional: spec.additional_context += f"\n[User notes, round {round_num}]: {additional}" round_num = 0 # reset so it asks "would you like clarifying questions?" again elif choice == "c": console.print("[dim]Asking more clarifying questions...[/dim]") continue elif choice == "e": console.print("[dim]Proceeding to execution.[/dim]") break elif choice == "q": console.print("[yellow]Quitting — plan not executed.[/yellow]") spec.approved = False break else: console.print("[dim]Proceeding to execution.[/dim]") break return spec @main.command() @click.option("--project-dir", "-d", default=".", help="Project directory to work in") @click.option( "--plan-name", callback=_validate_plan_name, help="Separate saved-plan state name; defaults to the target directory name.", ) @click.option( "--goal", "-g", default=None, help="Direct task description (skips interactive interview)" ) @click.option( "--hitl", is_flag=True, default=False, help="Human-in-the-loop mode: approve each destructive action", ) @click.option( "--yes", "-y", is_flag=True, default=False, help="Auto-approve all prompts (non-interactive)" ) @click.option( "--auto-resume", is_flag=True, default=False, help="Keep resuming until all tasks complete" ) @click.option( "--plan-only", is_flag=True, default=False, help="Generate and save the task plan without executing it", ) @click.option( "--lint-mode", type=click.Choice([mode.value for mode in LintMode]), default=None, help="Review policy override: strict or baseline.", ) @click.option( "--max-auto-resume-passes", type=click.IntRange(min=1), default=None, help="Maximum queue passes for --auto-resume.", ) @click.pass_context def grillme( ctx: click.Context, project_dir: str, plan_name: str | None, goal: str, hitl: bool, yes: bool, auto_resume: bool, plan_only: bool, lint_mode: str | None, max_auto_resume_passes: int | None, ): """Start a structured interview to define and plan a coding task.""" from afk_developer.grillme.interviewer import run_interview from afk_developer.planner.decomposer import decompose_task from afk_developer.planner.plan_verifier import preflight_plan auto = goal is not None or yes spec = run_interview(project_dir, goal, yes=yes) if plan_name: spec.project_name = plan_name _archive_prompt(spec.project_name, spec.goal) if not spec.approved: console.print("[yellow]Cancelled.[/yellow]") return if not auto: spec = _refinement_loop(spec, ctx.obj["config"]) config: Config = ctx.obj["config"] effective_lint_mode = _resolve_lint_mode(config, lint_mode) effective_max_passes = _resolve_max_auto_resume_passes(config, max_auto_resume_passes) cortex = _init_cortex(config, spec.project_name) console.print("\n[bold]Decomposing into tasks...[/bold]") try: plan = decompose_task(spec, config) except Exception as e: console.print(f"[red]Failed to decompose task: {e}[/red]") return preflight = preflight_plan(plan) if not preflight.passed: console.print("[red]Plan preflight failed:[/red]") for failure in preflight.failures: console.print(f" [red]- {_safe(failure)}[/red]") return initialize_plan_recovery(plan, config.recovery) console.print(f"\n[bold]Task Plan: {len(plan.tasks)} tasks[/bold]") priority_colors = { "critical_bug": "red", "infrastructure": "yellow", "tracer_bullet": "magenta", "feature": "white", "polish": "green", "refactor": "dim", } for task in plan.topological_sort(): dep_str = f" depends on: {', '.join(task.dependencies)}" if task.dependencies else "" color = "cyan" if task.read_only else priority_colors.get(task.priority.value, "white") p_label = task.priority.value.replace("_", " ") console.print( f" [{color}]{_safe(task.id)}[/{color}]: {_safe(task.title)} [{task.estimated_effort}] [{p_label}]{dep_str}" ) _save_plan( config, plan, project_dir=spec.project_dir, linter=spec.linter, test_framework=spec.test_framework, lint_mode=effective_lint_mode, max_auto_resume_passes=effective_max_passes, ) if plan.intent == TaskIntent.ANALYZE.value: console.print( f"\n[cyan]Analysis plan: {len(plan.tasks)} tasks to explore the codebase.[/cyan]" ) else: console.print( f"\n[bold]Implementation plan: {len(plan.tasks)} tasks.[/bold] " f"Language: {spec.language}, Tests: {spec.test_framework}, Lint: {spec.linter}" ) if hitl: console.print( "\n[bold yellow]HITL mode active[/bold yellow] — you will be prompted before each file write, edit, and command execution." ) cost_est = _estimate_cost(cortex, len(plan.tasks)) if cost_est: console.print(f"\n[dim]{cost_est}[/dim]") if plan_only: console.print("[green]Plan saved without execution.[/green] Use 'afk resume' to start it.") return if not auto and not click.confirm("\nExecute this plan?", default=True): console.print("[dim]Plan saved. Use 'afk resume' to run later.[/dim]") return try: lint_baseline = _prepare_lint_baseline( config, spec.project_name, Path(spec.project_dir), spec.linter, effective_lint_mode, create_if_missing=True, ) except LintBaselineError as exc: console.print(f"[red]Cannot start plan: {exc}[/red]") return _run_plan( plan, config, cortex, spec.project_dir, spec.linter, spec.test_framework, hitl_mode=hitl, auto_resume=auto_resume, lint_mode=effective_lint_mode, lint_baseline=lint_baseline, max_auto_resume_passes=effective_max_passes, ) _save_plan( config, plan, project_dir=spec.project_dir, linter=spec.linter, test_framework=spec.test_framework, lint_mode=effective_lint_mode, max_auto_resume_passes=effective_max_passes, ) main.add_command(campaign) main.add_command(acceptance_profile) @main.command() @click.argument("project_name") @click.option( "--hitl", is_flag=True, default=False, help="Human-in-the-loop mode: approve each destructive action", ) @click.option( "--yes", "-y", is_flag=True, default=False, help="Auto-approve all prompts (non-interactive)" ) @click.option( "--auto-resume", is_flag=True, default=False, help="Keep resuming until all tasks complete" ) @click.option( "--lint-mode", type=click.Choice([mode.value for mode in LintMode]), default=None, help="Review policy override; defaults to the saved plan policy.", ) @click.option( "--max-auto-resume-passes", type=click.IntRange(min=1), default=None, help="Maximum queue passes for --auto-resume.", ) @click.pass_context def resume( ctx: click.Context, project_name: str, hitl: bool, yes: bool, auto_resume: bool, lint_mode: str | None, max_auto_resume_passes: int | None, ): """Resume a previously started task plan.""" config: Config = ctx.obj["config"] loaded = _load_plan(config, project_name) if loaded is None: console.print(f"[red]No saved plan found for '{project_name}'.[/red]") return ( plan, saved_project_dir, saved_linter, saved_test_framework, saved_lint_mode, saved_max_auto_resume_passes, ) = loaded # Recovery policy is snapshotted onto the plan at creation time (see the # `grillme` command). Refresh it from the live config on every resume, so a # config.yml change (e.g. turning bounded recovery on) actually takes effect # for plans created before the change, instead of silently staying frozen at # whatever `recovery:` said when the plan was first generated. Safe to call # again: it only (re)initializes budget counters for tasks that haven't # started yet, never resetting an in-progress or completed task's budget. initialize_plan_recovery(plan, config.recovery) project_dir = Path(saved_project_dir) if saved_project_dir else Path.cwd() linter = saved_linter or "" test_framework = saved_test_framework or "" effective_lint_mode = LintMode(lint_mode or saved_lint_mode.value) effective_max_passes = ( max_auto_resume_passes if max_auto_resume_passes is not None else saved_max_auto_resume_passes ) cortex = _init_cortex(config, project_name) console.print(f"[bold]Resuming:[/bold] [cyan]{plan.goal}[/cyan] ({len(plan.tasks)} tasks)") if plan.all_done(): console.print("[green]All tasks already complete.[/green]") return if plan.has_escalated(): task_ids = ", ".join(plan.escalated_task_ids()) console.print( f"[yellow]Manual retry required for {task_ids}. " "Use 'afk retry ' before resuming dependents.[/yellow]" ) return remaining = [t for t in plan.tasks if t.status != "passed"] console.print(f"[dim]{len(remaining)} tasks remaining.[/dim]") if hitl: console.print("[bold yellow]HITL mode active[/bold yellow]") if not yes and not click.confirm("Continue?", default=True): return try: lint_baseline = _prepare_lint_baseline( config, project_name, project_dir, linter, effective_lint_mode, create_if_missing=False, ) except LintBaselineError as exc: console.print(f"[red]Cannot resume plan: {exc}[/red]") return _run_plan( plan, config, cortex, project_dir, linter, test_framework, hitl_mode=hitl, auto_resume=auto_resume, lint_mode=effective_lint_mode, lint_baseline=lint_baseline, max_auto_resume_passes=effective_max_passes, ) @main.command() @click.argument("project_name") @click.argument("task_id") @click.option("--hitl", is_flag=True, default=False, help="Human-in-the-loop mode") @click.option( "--lint-mode", type=click.Choice([mode.value for mode in LintMode]), default=None, help="Review policy override; saved with the retried plan.", ) @click.option( "--force-recovery", is_flag=True, default=False, help="Explicitly override an exhausted bounded semantic or evidence-research budget.", ) @click.option( "--validate-existing", is_flag=True, default=False, help="Run review and acceptance against retained task-branch changes without starting a coder.", ) @click.pass_context def retry( ctx: click.Context, project_name: str, task_id: str, hitl: bool, lint_mode: str | None, force_recovery: bool = False, validate_existing: bool = False, ): """Retry a single failed task without touching the others.""" run_manual_retry( ctx, project_name, task_id, hitl, lint_mode, force_recovery=force_recovery, validate_existing=validate_existing, ) @main.command("approve-decomposition") @click.argument("project_name") @click.argument("proposal_id") @click.option("--reason", required=True) @click.pass_context def approve_decomposition( ctx: click.Context, project_name: str, proposal_id: str, reason: str ) -> None: """Apply one reviewed foreman decomposition proposal to a saved plan.""" from afk_developer.campaign_supervision import ( SupervisorAmendmentError, approve_foreman_proposal, ) config: Config = ctx.obj["config"] loaded = _load_plan(config, project_name) if loaded is None: raise click.UsageError(f"No saved plan found for '{project_name}'.") plan, *_ = loaded try: amended = approve_foreman_proposal(plan, proposal_id, reason) except SupervisorAmendmentError as exc: raise click.UsageError(str(exc)) from exc _save_loaded_plan(config, amended, loaded) proposal = next(item for item in amended.foreman_proposals if item.id == proposal_id) console.print( f"[green]Foreman proposal approved.[/green] {proposal.parent_task_id} delegated to: " f"{', '.join(child.id for child in proposal.subtasks)}." ) @main.command("reject-decomposition") @click.argument("project_name") @click.argument("proposal_id") @click.option("--reason", required=True) @click.pass_context def reject_decomposition( ctx: click.Context, project_name: str, proposal_id: str, reason: str ) -> None: """Record rejection of one foreman decomposition proposal without queue mutation.""" from afk_developer.campaign_supervision import ( SupervisorAmendmentError, reject_foreman_proposal, ) config: Config = ctx.obj["config"] loaded = _load_plan(config, project_name) if loaded is None: raise click.UsageError(f"No saved plan found for '{project_name}'.") plan, *_ = loaded try: amended = reject_foreman_proposal(plan, proposal_id, reason) except SupervisorAmendmentError as exc: raise click.UsageError(str(exc)) from exc _save_loaded_plan(config, amended, loaded) proposal = next(item for item in amended.foreman_proposals if item.id == proposal_id) console.print( f"[yellow]Foreman proposal rejected.[/yellow] {proposal.parent_task_id} remains escalated." ) @main.command("status") @click.argument("project_name", required=False) @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.pass_context def status_command(ctx: click.Context, project_name: str | None, watch: bool, interval: float): """Show all durable work, or a detailed snapshot for PROJECT_NAME. Reads durable JSON directly (never a campaign run lock, never a write), so it is safe to run alongside live AFK work. """ from afk_developer.watch import ( SnapshotLoadError, build_fleet_status_view, build_status_view, load_fleet_status_entries, load_json_snapshot, watch_loop, ) config: Config = ctx.obj["config"] if project_name is None: def render_fleet(): now = datetime.now(timezone.utc) return build_fleet_status_view( load_fleet_status_entries(config.projects_dir, now=now), now=now ) if not watch: console.print(render_fleet()) return watch_loop(console, interval, render_fleet) console.print("\n[dim]Stopped watching.[/dim]") return path = _get_plan_path(config, project_name) governance_path = config.resolve_project_dir(project_name) / "governance-projection.json" try: snapshot = load_json_snapshot(path) except SnapshotLoadError as exc: raise click.ClickException(str(exc)) from exc governance_snapshot = None if governance_path.is_file(): try: governance_snapshot = load_json_snapshot(governance_path) except SnapshotLoadError: governance_snapshot = None if not watch: console.print( build_status_view( snapshot.payload, governance_state=(governance_snapshot.payload if governance_snapshot else None), now=datetime.now(timezone.utc), stale=snapshot.stale or (governance_snapshot.stale if governance_snapshot else False), plan_mtime=snapshot.mtime, ) ) return def render(): nonlocal snapshot, governance_snapshot snapshot = load_json_snapshot(path, previous=snapshot) if governance_snapshot is not None or governance_path.is_file(): governance_snapshot = load_json_snapshot(governance_path, previous=governance_snapshot) return build_status_view( snapshot.payload, governance_state=(governance_snapshot.payload if governance_snapshot else None), now=datetime.now(timezone.utc), stale=snapshot.stale or (governance_snapshot.stale if governance_snapshot else False), plan_mtime=snapshot.mtime, ) watch_loop(console, interval, render) console.print("\n[dim]Stopped watching.[/dim]") @main.command("lint-baseline") @click.argument("project_name") @click.option( "--project-dir", "-d", default=None, help="Project directory, if no saved plan exists." ) @click.option("--refresh", is_flag=True, default=False, help="Replace an existing baseline.") @click.pass_context def lint_baseline_command( ctx: click.Context, project_name: str, project_dir: str | None, refresh: bool ): """Create or explicitly refresh a Ruff baseline for a brownfield project.""" config: Config = ctx.obj["config"] if _other_afk_processes_active(): console.print( "[red]Cannot capture a lint baseline while another AFK process is active.[/red]" ) return if project_dir: target_dir = Path(project_dir) else: loaded = _load_plan(config, project_name) if loaded is None or not loaded[1]: console.print("[red]Provide --project-dir or create a saved plan first.[/red]") return target_dir = Path(loaded[1]) target_dir = target_dir.resolve() if not target_dir.is_dir(): console.print(f"[red]Project directory does not exist: {target_dir}[/red]") return path = _lint_baseline_path(config, project_name) if path.exists() and not refresh: console.print( f"[yellow]Baseline already exists: {path}. Use --refresh to replace it explicitly.[/yellow]" ) return worktree_state = _git_worktree_state(target_dir) try: baseline = capture_ruff_baseline(target_dir, project_name) save_baseline(path, baseline) except LintBaselineError as exc: console.print(f"[red]Could not capture Ruff baseline: {exc}[/red]") return git_head = baseline.git_head or "no Git HEAD" console.print( f"[green]Ruff baseline saved:[/green] {baseline.diagnostic_count} diagnostics, " f"{git_head}, {worktree_state}, {path}" ) @main.command("maintain-state") @click.argument("project_name") @click.option( "--keep-session-stats", type=click.IntRange(min=1), default=100, show_default=True, help="Number of newest session-stat rows to retain.", ) @click.pass_context def maintain_state(ctx: click.Context, project_name: str, keep_session_stats: int): """Prune duplicate runner state and compact an inactive project's Cortex database.""" if _other_afk_processes_active(): console.print("[red]Cannot compact state while another AFK process is active.[/red]") return config: Config = ctx.obj["config"] cortex = _init_cortex(config, project_name) try: result = cortex.compact_state(keep_session_stats) except (OSError, sqlite3.Error, ValueError) as exc: console.print(f"[red]State maintenance failed: {exc}[/red]") return console.print( "[green]State maintenance complete:[/green] " f"removed {result['duplicate_last_plan_rows']} duplicate plan rows and " f"{result['old_session_rows']} old session rows; " f"reclaimed {result['reclaimed_bytes']:,} bytes." ) @main.command() @click.argument("project_name") @click.pass_context def prd(ctx: click.Context, project_name: str): """Generate a structured PRD document from a saved plan.""" config: Config = ctx.obj["config"] loaded = _load_plan(config, project_name) if loaded is None: console.print(f"[red]No saved plan found for '{project_name}'.[/red]") return plan, saved_project_dir, _, _, _, _ = loaded project_dir = Path(saved_project_dir) if saved_project_dir else Path.cwd() console.print(f"[bold]Generating PRD for:[/bold] [cyan]{plan.goal[:80]}...[/cyan]") console.print(f"[dim]Project: {project_dir}[/dim]") task_summaries = "\n".join( f"- [{t.priority.value}] {t.id}: {t.title} ({t.estimated_effort})" for t in plan.tasks ) prompt = ( f"GOAL: {plan.goal}\n\n" f"INTENT: {plan.intent}\n\n" f"PLANNED TASKS ({len(plan.tasks)}):\n{task_summaries}" ) from afk_developer.backends.registry import BackendRegistry console.print("[dim]Synthesizing PRD from LLM...[/dim]") try: response = ( BackendRegistry(config) .get_reasoner() .complete( system_prompt=( "You are a senior product manager. Synthesize a Product Requirements Document from " "the task plan and goal below. Use this EXACT template:\n\n" "## Problem Statement\n\n[what problem does this solve, from user's perspective]\n\n" "## Solution\n\n[how it solves the problem, from user's perspective]\n\n" "## User Stories\n\n[numbered list of user stories in format: As a , I want , so that ]\n\n" "## Implementation Decisions\n\n[list of architectural/technical decisions made: modules, interfaces, schema, contracts]\n\n" "## Out of Scope\n\n[what is explicitly NOT included]\n\n" "## Further Notes\n\n[any additional context]\n\n" "Do NOT include file paths or code snippets. Do NOT repeat the task list verbatim. " "Write in clear, concise English." ), user_prompt=prompt, temperature=0.3, ) ) config.record_usage(response.usage, role="reasoner") except Exception as e: console.print(f"[red]Failed to generate PRD: {e}[/red]") return prd_content = response.content.strip() prd_dir = project_dir / "prd" prd_dir.mkdir(parents=True, exist_ok=True) prd_path = prd_dir / f"{project_name}.md" prd_path.write_text(prd_content, encoding="utf-8") console.print(f"\n[green]PRD saved to:[/green] {prd_path}") console.print( Panel.fit( _safe(prd_content[:600] + ("..." if len(prd_content) > 600 else "")), title="PRD Preview", border_style="cyan", ) ) def _run_plan( plan, config, cortex, project_dir, linter, test_framework, hitl_mode=False, auto_resume=False, lint_mode: LintMode = LintMode.STRICT, lint_baseline: LintBaseline | None = None, max_auto_resume_passes: int = 10, ): 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_plan from afk_developer.reporter import report_analysis, report_results try: prepared = prepare_execution_boundary(plan, config, project_dir) except ExecutionBoundaryError as exc: raise click.ClickException(str(exc)) from exc cortex.replace_permanent( "last-plan", json.dumps({"goal": plan.goal, "intent": plan.intent, "task_count": len(plan.tasks)}), ) queue_passes = 0 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): while True: queue_passes += 1 before_state = plan.state_fingerprint() execute_plan( plan, config, cortex, project_dir, linter, test_framework, hitl_mode=hitl_mode, save_callback=lambda: _save_plan( config, plan, project_dir=project_dir, linter=linter, test_framework=test_framework, lint_mode=lint_mode, max_auto_resume_passes=max_auto_resume_passes, ), lint_mode=lint_mode, lint_baseline=lint_baseline, isolation=config.git_isolation, ) if plan.intent == TaskIntent.ANALYZE.value: report_analysis(plan, config) else: report_results(plan, project_dir, config) _save_plan( config, plan, project_dir=project_dir, linter=linter, test_framework=test_framework, lint_mode=lint_mode, max_auto_resume_passes=max_auto_resume_passes, ) cortex.save_session(config.stats.to_dict()) if plan.all_done() or not auto_resume: break if plan.has_escalated(): task_ids = ", ".join(plan.escalated_task_ids()) console.print( f"[yellow]Auto-resume halted: manual retry required for {task_ids}. " "Use 'afk retry '.[/yellow]" ) break ready_tasks = plan.get_ready_tasks() if not ready_tasks: console.print( "[yellow]Auto-resume halted: no runnable tasks remain. " "Review blocked dependencies before resuming.[/yellow]" ) break if plan.state_fingerprint() == before_state: console.print( "[yellow]Auto-resume halted: the queue pass made no state progress. " "Review the saved plan before retrying.[/yellow]" ) break if queue_passes >= max_auto_resume_passes: console.print( f"[yellow]Auto-resume halted after {queue_passes} queue passes. " "Resume explicitly after reviewing the plan.[/yellow]" ) break console.print( f"\n[dim]Auto-resuming: {len(ready_tasks)} runnable tasks remaining...[/dim]" ) @main.command("approve-environment-repair") @click.argument("project_name") @click.option("--reason", required=True, help="Why the verified target environment changed.") @click.pass_context def approve_environment_repair(ctx: click.Context, project_name: str, reason: str) -> None: """Approve a verified interpreter/dependency fingerprint change for one saved plan.""" from afk_developer.environment import resolve_environment_contract from afk_developer.event_store import DurableEventStore, EventProjector if not reason.strip(): raise click.UsageError("An environment repair reason is required.") config: Config = ctx.obj["config"] loaded = _load_plan(config, project_name) if loaded is None: raise click.UsageError(f"No saved plan found for '{project_name}'.") _, project_dir, _, _, _, _ = loaded if not project_dir: raise click.UsageError("Saved plan has no target project directory.") environment = resolve_environment_contract(project_dir, target_python=config.target_python) if not environment.passed: raise click.UsageError( f"Environment repair cannot approve ({environment.code}): {environment.detail}" ) state_dir = config.resolve_project_dir(project_name) store = DurableEventStore(state_dir / "governance-events.jsonl") snapshot_path = state_dir / "governance-projection.json" store.append( "environment_repair_approved", { "fingerprint": environment.contract.target.fingerprint, "contract": environment.contract.to_record(), "reason": reason.strip(), }, ) projector = EventProjector() projector.save_snapshot(snapshot_path, projector.rebuild(store, snapshot_path)) console.print( "[green]Environment repair approved.[/green] " f"Accepted target fingerprint {environment.contract.target.fingerprint[:16]}." ) @main.command("attest-product-validation") @click.argument("project_name") @click.argument("task_id") @click.option( "--observation", required=True, help="Human observation of the requested product behavior." ) @click.pass_context def attest_product_validation( ctx: click.Context, project_name: str, task_id: str, observation: str ) -> None: """Record a human-only product validation after deterministic task checks passed.""" from afk_developer.event_store import DurableEventStore, EventProjector from afk_developer.planner.task_model import ( ProductValidationStatus, TaskLifecyclePhase, TaskStatus, ) if not observation.strip(): raise click.UsageError("A non-empty product validation observation is required.") config: Config = ctx.obj["config"] loaded = _load_plan(config, project_name) if loaded is None: raise click.UsageError(f"No saved plan found for '{project_name}'.") plan, project_dir, linter, test_framework, lint_mode, max_passes = loaded task = next((item for item in plan.tasks if item.id == task_id), None) if task is None or task.product_validation is None: raise click.UsageError("Task has no configured product validation checkpoint.") checkpoint = task.product_validation if checkpoint.status is not ProductValidationStatus.AWAITING_HUMAN: raise click.UsageError("Task is not awaiting human product validation.") root = Path(project_dir).resolve() hashes: dict[str, str] = {} for raw_path in checkpoint.artifact_paths: candidate = (root / raw_path).resolve() if not candidate.is_relative_to(root) or not candidate.is_file(): raise click.UsageError(f"Required product-validation artifact is missing: {raw_path}") hashes[raw_path] = hashlib.sha256(candidate.read_bytes()).hexdigest() checkpoint.status = ProductValidationStatus.ATTESTED checkpoint.attested_at = datetime.now(timezone.utc) checkpoint.observation = observation.strip() checkpoint.artifact_sha256 = hashes task.status = TaskStatus.PASSED task.lifecycle_phase = TaskLifecyclePhase.PASSED task.blocked_reason = "" _save_plan( config, plan, project_dir=Path(project_dir), linter=linter, test_framework=test_framework, lint_mode=lint_mode, max_auto_resume_passes=max_passes, ) state_dir = config.resolve_project_dir(project_name) store = DurableEventStore(state_dir / "governance-events.jsonl") snapshot_path = state_dir / "governance-projection.json" store.append( "product_validation_attested", { "task_id": task.id, "validation_kind": checkpoint.kind, "observation": checkpoint.observation, "artifact_sha256": hashes, }, ) projector = EventProjector() projector.save_snapshot(snapshot_path, projector.rebuild(store, snapshot_path)) console.print(f"[green]Product validation attested.[/green] {task.id} is passed.") @main.command("observe-product-artifacts") @click.argument("project_name") @click.argument("task_id") @click.pass_context def observe_product_artifacts(ctx: click.Context, project_name: str, task_id: str) -> None: """Record factual metadata for a task's declared product-validation artifacts.""" from afk_developer.event_store import DurableEventStore, EventProjector from afk_developer.vision import ObservationError, observe_artifacts config: Config = ctx.obj["config"] loaded = _load_plan(config, project_name) if loaded is None: raise click.UsageError(f"No saved plan found for '{project_name}'.") plan, project_dir, _, _, _, _ = loaded task = next((item for item in plan.tasks if item.id == task_id), None) if task is None or task.product_validation is None: raise click.UsageError("Task has no declared product-validation artifact manifest.") try: observations = observe_artifacts(project_dir, task.product_validation.artifact_paths) except ObservationError as exc: raise click.UsageError(str(exc)) from exc state_dir = config.resolve_project_dir(project_name) store = DurableEventStore(state_dir / "governance-events.jsonl") snapshot_path = state_dir / "governance-projection.json" store.append( "vision_observed", {"task_id": task.id, "observations": [item.to_record() for item in observations]}, ) projector = EventProjector() projector.save_snapshot(snapshot_path, projector.rebuild(store, snapshot_path)) console.print( f"[cyan]Factual artifact observation recorded.[/cyan] {len(observations)} artifact(s); " "no product validation was granted." ) @main.command("friction-report") @click.argument("project_name") @click.pass_context def friction_report(ctx: click.Context, project_name: str) -> None: """Summarize where one run required recovery, escalation, or human attention.""" from afk_developer.event_store import DurableEventStore from afk_developer.friction_report import build_friction_report config: Config = ctx.obj["config"] path = config.resolve_project_dir(project_name) / "governance-events.jsonl" if not path.is_file(): raise click.UsageError(f"No governance event log found for '{project_name}'.") report = build_friction_report(DurableEventStore(path)) lines = [f"Governance events: {report.event_count}", "Operational counters:"] lines.extend(f" {name}: {value}" for name, value in report.counters.items()) if report.pending_effects: lines.append("Pending effects:") lines.extend( f" {effect_id}: {operation}" for effect_id, operation in report.pending_effects.items() ) if report.environment_rejection: lines.append( "Environment rejection: " f"{report.environment_rejection.get('code', '?')} — " f"{report.environment_rejection.get('detail', '')}" ) if report.awaiting_product_validation: lines.append( "Awaiting product validation: " + ", ".join(report.awaiting_product_validation) ) console.print("\n".join(lines)) def _init_cortex(config: Config, project_name: str) -> CortexDB: db_path = config.resolve_project_dir(project_name) / "cortex.db" return CortexDB(db_path, project_name) def _get_plan_path(config: Config, project_name: str) -> Path: return config.resolve_project_dir(project_name) / "plan.json" def _existing_project_files(project_dir: Path, declared_files: list[str]) -> list[str]: """Keep only existing project-relative declarations when Git is unavailable.""" root = project_dir.resolve() files: list[str] = [] for raw_path in declared_files: candidate = (root / raw_path).resolve() if candidate.is_relative_to(root) and candidate.is_file(): files.append(candidate.relative_to(root).as_posix()) return sorted(set(files)) def _save_plan( config: Config, plan, project_dir=None, linter="", test_framework="", lint_mode: LintMode = LintMode.STRICT, max_auto_resume_passes: int = 10, ) -> bool: path = _get_plan_path(config, plan.project_name) data = { "branch_namespace": plan.branch_namespace, "project_name": plan.project_name, "goal": plan.goal, "intent": plan.intent, "project_dir": str(project_dir) if project_dir else "", "linter": linter or "", "test_framework": test_framework or "", "lint_mode": lint_mode.value, "max_auto_resume_passes": max_auto_resume_passes, "recovery": plan.recovery.to_dict(), "decompositions_used": plan.decompositions_used, "supervisor_amendments": [item.model_dump() for item in plan.supervisor_amendments], "foreman_proposals": [item.model_dump() for item in plan.foreman_proposals], "preflight_evidence": ( plan.preflight_evidence.model_dump() if plan.preflight_evidence is not None else None ), "audit_log_path": plan.audit_log_path, "tasks": [t.model_dump() for t in plan.tasks], } fsutil.atomic_write_text(path, json.dumps(data, indent=2, default=str)) return True def _load_plan(config: Config, project_name: str): from afk_developer.planner.task_model import TaskNode from afk_developer.recovery import RecoverySettings path = _get_plan_path(config, project_name) if not path.exists(): return None data = json.loads(path.read_text(encoding="utf-8")) tasks = [TaskNode(**t) for t in data["tasks"]] plan_data = { "project_name": data["project_name"], "goal": data["goal"], "intent": data["intent"], "tasks": tasks, "recovery": RecoverySettings.from_mapping(data.get("recovery")), "decompositions_used": data.get("decompositions_used", 0), "supervisor_amendments": data.get("supervisor_amendments", []), "foreman_proposals": data.get("foreman_proposals", []), "preflight_evidence": data.get("preflight_evidence"), "audit_log_path": data.get("audit_log_path", ""), } if data.get("branch_namespace"): plan_data["branch_namespace"] = data["branch_namespace"] plan = TaskPlan(**plan_data) try: lint_mode = LintMode(data.get("lint_mode", config.lint_mode.value)) except ValueError as exc: raise ValueError(f"Saved plan has an invalid lint mode: {data.get('lint_mode')}") from exc max_auto_resume_passes = int(data.get("max_auto_resume_passes", config.max_auto_resume_passes)) if max_auto_resume_passes < 1: raise ValueError("Saved plan has an invalid auto-resume pass limit.") return ( plan, data.get("project_dir", ""), data.get("linter", ""), data.get("test_framework", ""), lint_mode, max_auto_resume_passes, ) def _save_loaded_plan(config: Config, plan: TaskPlan, loaded: tuple) -> bool: """Save an amended plan without resetting its execution metadata.""" return _save_plan( config, plan, project_dir=loaded[1], linter=loaded[2], test_framework=loaded[3], lint_mode=loaded[4], max_auto_resume_passes=loaded[5], ) if __name__ == "__main__": main()