from pathlib import Path from rich.console import Console from rich.panel import Panel from rich.table import Table from afk_developer.campaign import CampaignStatistics from afk_developer.config import Config from afk_developer.planner.task_model import TaskPlan, TaskStatus from afk_developer.utils import console_safe console = Console() def _format_duration(seconds: float | None) -> str: if seconds is None: return "unavailable" total = max(int(seconds), 0) hours, remainder = divmod(total, 3600) minutes, seconds = divmod(remainder, 60) if hours: return f"{hours}h {minutes}m {seconds}s" if minutes: return f"{minutes}m {seconds}s" return f"{seconds}s" def report_campaign_statistics(statistics: CampaignStatistics) -> None: """Display the campaign's plan-backed durable aggregate and reconciliable subtotals.""" usage = statistics.usage credits = usage.copilot_nano_aiu / 1_000_000_000 metered_value = credits * 0.01 table = Table(title="Campaign Statistics") table.add_column("Metric", style="cyan") table.add_column("Value", style="green") table.add_row("Campaign Status", statistics.campaign_status.value) table.add_row("Stop / Checkpoint", statistics.stop_reason or "(none)") table.add_row( "Batches Completed / Planned Limit", f"{statistics.batches_completed}/{statistics.batches_planned_limit}", ) table.add_row("Tasks Planned", str(statistics.tasks_planned)) table.add_row("Tasks Passed", str(statistics.tasks_passed)) table.add_row("Tasks Not Applicable", str(statistics.tasks_not_applicable)) table.add_row("Tasks Failed", str(statistics.tasks_failed)) table.add_row("Tasks Blocked", str(statistics.tasks_blocked)) table.add_row("Tasks Escalated", str(statistics.tasks_escalated)) table.add_row("Tasks Decomposed", str(statistics.tasks_decomposed)) table.add_row("Task Attempts", str(statistics.attempts)) table.add_row("API Calls", str(usage.api_calls)) table.add_row("Agent Turns", str(usage.agent_turns)) table.add_row("Prompt Tokens", f"{usage.prompt_tokens:,}") table.add_row("Completion Tokens", f"{usage.completion_tokens:,}") table.add_row("Total Tokens", f"{usage.total_tokens:,}") table.add_row("Cache Read Tokens", f"{usage.cache_read_tokens:,}") table.add_row("Cache Write Tokens", f"{usage.cache_write_tokens:,}") table.add_row("Reasoning Tokens", f"{usage.reasoning_tokens:,}") table.add_row("Copilot Prompts", str(usage.copilot_prompts_submitted)) table.add_row("Copilot AI Credits", f"{credits:,.4f}") table.add_row( "Copilot Metered Value", f"${metered_value:,.4f} (not an invoice / not necessarily billed)", ) table.add_row("Active Campaign Time", _format_duration(statistics.active_seconds)) table.add_row("Elapsed Wall-Clock Time", _format_duration(statistics.elapsed_wall_seconds)) console.print() console.print(table) role_table = Table(title="Campaign Attempts by Role") role_table.add_column("Role", style="cyan") role_table.add_column("Attempts", justify="right") for role, count in sorted(statistics.role_attempts.items()): role_table.add_row(role, str(count)) if not statistics.role_attempts: role_table.add_row("(none)", "0") console.print(role_table) model_table = Table(title="Campaign Usage by Model") for column in ( "Endpoint", "Model", "Calls", "Turns", "Prompt", "Completion", "Total", "Cache Read", "Cache Write", "Reasoning", "Copilot Prompts", "AI Credits", "Metered Value", ): model_table.add_column(column, justify="right") for model in statistics.model_usage: model_credits = model.copilot_nano_aiu / 1_000_000_000 model_table.add_row( model.endpoint or "unknown", model.model or "unknown", str(model.api_calls), str(model.agent_turns), f"{model.prompt_tokens:,}", f"{model.completion_tokens:,}", f"{model.total_tokens:,}", f"{model.cache_read_tokens:,}", f"{model.cache_write_tokens:,}", f"{model.reasoning_tokens:,}", str(model.copilot_prompts_submitted), f"{model_credits:,.4f}", f"${model_credits * 0.01:,.4f}", ) if not statistics.model_usage: model_table.add_row( "(none)", "", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "$0.0000" ) console.print(model_table) role_usage_table = Table(title="Campaign Usage by Role") for column in ( "Role", "Calls", "Turns", "Prompt", "Completion", "Total", "Cache Read", "Cache Write", "Reasoning", "Copilot Prompts", "AI Credits", "Metered Value", ): role_usage_table.add_column(column, justify="right" if column != "Role" else "left") for role in statistics.role_usage: role_credits = role.copilot_nano_aiu / 1_000_000_000 role_usage_table.add_row( role.role or "unknown", str(role.api_calls), str(role.agent_turns), f"{role.prompt_tokens:,}", f"{role.completion_tokens:,}", f"{role.total_tokens:,}", f"{role.cache_read_tokens:,}", f"{role.cache_write_tokens:,}", f"{role.reasoning_tokens:,}", str(role.copilot_prompts_submitted), f"{role_credits:,.4f}", f"${role_credits * 0.01:,.4f}", ) if not statistics.role_usage: role_usage_table.add_row( "(none)", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "$0.0000" ) console.print(role_usage_table) batch_table = Table(title="Campaign Batch Subtotals") for column in ( "Batch", "Plan", "Planned", "Passed", "N/A", "Failed", "Blocked", "Escalated", "Attempts", "API Calls", "Total Tokens", ): batch_table.add_column(column, justify="right") for batch in statistics.batches: batch_table.add_row( str(batch.ordinal), batch.plan_name, str(batch.planned_tasks), str(batch.passed_tasks), str(batch.not_applicable_tasks), str(batch.failed_tasks), str(batch.blocked_tasks), str(batch.escalated_tasks), str(batch.attempts), str(batch.usage.api_calls), f"{batch.usage.total_tokens:,}", ) if not statistics.batches: batch_table.add_row("-", "(none)", "0", "0", "0", "0", "0", "0", "0", "0", "0") console.print(batch_table) console.print( "[dim]Campaign totals use only the persisted plans named by this campaign and their " "deduplicated attempt IDs. Metered value is not an invoice / not necessarily billed.[/dim]" ) def report_session_stats(config: Config): s = config.stats stats_table = Table(title="Session Statistics") stats_table.add_column("Metric", style="cyan") stats_table.add_column("Value", style="green") stats_table.add_row("API Calls", str(s.api_calls)) stats_table.add_row("Agent Turns", str(s.total_turns)) stats_table.add_row("Prompt Tokens", f"{s.prompt_tokens:,}") stats_table.add_row("Completion Tokens", f"{s.completion_tokens:,}") stats_table.add_row("Total Tokens", f"{s.total_tokens:,}") stats_table.add_row("Cache Read Tokens", f"{s.cache_read_tokens:,}") stats_table.add_row("Cache Write Tokens", f"{s.cache_write_tokens:,}") stats_table.add_row("Reasoning Tokens", f"{s.reasoning_tokens:,}") if s.copilot_prompts_submitted: stats_table.add_row("Copilot Prompts Submitted", str(s.copilot_prompts_submitted)) if s.copilot_usage_available: stats_table.add_row("Copilot AI Credits", f"{s.copilot_ai_credits:,.4f}") stats_table.add_row( "Copilot Metered Value", f"${s.copilot_metered_value_usd:,.4f} (not an invoice)", ) else: stats_table.add_row("Copilot Usage Telemetry", "Unavailable from the installed SDK") stats_table.add_row("Elapsed Time", s.elapsed_formatted) stats_table.add_row("Tasks Completed", str(s.tasks_completed)) stats_table.add_row("Tasks Failed", str(s.tasks_failed)) console.print() console.print(stats_table) if s.model_usage: model_table = Table(title="Model Usage") model_table.add_column("Endpoint", style="cyan") model_table.add_column("Model", style="cyan") model_table.add_column("Calls", justify="right") model_table.add_column("Input", justify="right") model_table.add_column("Output", justify="right") model_table.add_column("Cache Read", justify="right") model_table.add_column("Cache Write", justify="right") model_table.add_column("Reasoning", justify="right") model_table.add_column("AI Credits", justify="right") for usage in s.model_usage.values(): credits = (usage["copilot_nano_aiu"] or 0.0) / 1_000_000_000 model_table.add_row( usage["endpoint"] or "unknown", usage["model"], str(usage["api_calls"]), f"{usage['prompt_tokens']:,}", f"{usage['completion_tokens']:,}", f"{usage['cache_read_tokens']:,}", f"{usage['cache_write_tokens']:,}", f"{usage['reasoning_tokens']:,}", f"{credits:,.4f}" if usage["telemetry_available"] else "unavailable", ) console.print(model_table) if s.copilot_usage_available: console.print( "[dim]Copilot AI credits come from SDK usage events. GitHub values one AI credit at " "$0.01; the metered value is not the billed amount because included credits may apply.[/dim]" ) def report_results(plan: TaskPlan, project_dir: Path, config: Config): if plan.all_done(): console.print( Panel.fit( "[bold green]All tasks completed successfully![/bold green]", border_style="green" ) ) elif plan.has_escalated(): console.print( Panel.fit( "[bold yellow]Some tasks need manual attention.[/bold yellow]", border_style="yellow", ) ) else: console.print(Panel.fit("[bold red]Execution incomplete.[/bold red]", border_style="red")) table = Table(title=f"Results: {console_safe(plan.goal)}") table.add_column("Task", style="cyan") table.add_column("Status", style="white") table.add_column("Details") status_styles = { TaskStatus.PASSED: "[green]PASSED[/green]", TaskStatus.FAILED: "[red]FAILED[/red]", TaskStatus.ESCALATED: "[yellow]ESCALATED[/yellow]", TaskStatus.IN_PROGRESS: "[blue]IN PROGRESS[/blue]", TaskStatus.RETRYING: "[yellow]RETRYING[/yellow]", TaskStatus.BLOCKED: "[yellow]BLOCKED[/yellow]", TaskStatus.PENDING: "[dim]PENDING[/dim]", TaskStatus.CLAIMED: "[dim]CLAIMED[/dim]", TaskStatus.NOT_APPLICABLE: "[cyan]NOT APPLICABLE[/cyan]", TaskStatus.DECOMPOSED: "[cyan]DECOMPOSED[/cyan]", TaskStatus.CANCELLED: "[dim]CANCELLED[/dim]", } for task in plan.tasks: style = status_styles.get(task.status, str(task.status)) details = f"{task.estimated_effort}" if task.status == TaskStatus.PASSED: details = f"Done ({task.estimated_effort})" elif task.status == TaskStatus.NOT_APPLICABLE: details = ( task.not_applicable_reason or "No source-backed implementation contract applies" ) elif task.status == TaskStatus.FAILED: details = _failure_details(task, f"Failed after {task.retry_count} retries") elif task.status == TaskStatus.ESCALATED: details = _failure_details(task, f"Escalated after {task.retry_count} retries") elif task.status == TaskStatus.BLOCKED: details = task.blocked_reason or "Waiting for dependencies" details = _execution_details(task, details) table.add_row(console_safe(task.title), style, console_safe(details)) console.print(table) _report_task_attempts(plan) report_session_stats(config) def _failure_details(task, fallback: str) -> str: if task.failure_kind is None: return fallback detail = task.failure_detail.replace("\n", " ").strip() prefix = task.failure_kind.value.replace("_", " ") if task.failure_kind.value in { "verification_policy_rejected", "verification_tool_failed", "recovery_tool_failed", }: prefix = f"verification/recovery infrastructure ({prefix})" return f"{prefix}: {detail[:160]}" if detail else prefix def _execution_details(task, details: str) -> str: parts = [details] if task.evidence_packet_id: fingerprint = task.evidence_fingerprint[:12] if task.evidence_fingerprint else "unavailable" parts.append(f"evidence r{task.evidence_revision}: {fingerprint}") if task.validator_finding_ids: parts.append(f"validator findings: {', '.join(task.validator_finding_ids[:3])}") if task.recovery_action.value != "none": parts.append(f"scheduled: {task.recovery_action.value.replace('_', ' ')}") if task.semantic_repairs_used or task.research_supplements_used: parts.append( "recovery used " f"semantic={task.semantic_repairs_used}, research={task.research_supplements_used}; " "remaining " f"semantic={task.semantic_repairs_remaining}, research={task.research_supplements_remaining}" ) return " | ".join(parts) def _report_task_attempts(plan: TaskPlan) -> None: rows = _attempt_report_rows(plan) if not rows: return attempt_table = Table(title="Attempt Routes and Bounded Context") attempt_table.add_column("Task", style="cyan") attempt_table.add_column("Role") attempt_table.add_column("Route") attempt_table.add_column("Reason") attempt_table.add_column("Outcome") attempt_table.add_column("Context", justify="right") for row in rows: attempt_table.add_row(*row) console.print(attempt_table) def _attempt_report_rows(plan: TaskPlan) -> list[tuple[str, str, str, str, str, str]]: """Return normalized report rows independent of terminal width or Rich markup.""" rows: list[tuple[str, str, str, str, str, str]] = [] for task in plan.tasks: for attempt in task.attempts: route = f"{attempt.endpoint}/{attempt.model}" if attempt.reasoning_effort: route = f"{route} ({attempt.reasoning_effort})" outcome = attempt.outcome_status.value if attempt.outcome_status else "in progress" if attempt.failure_kind: outcome = f"{outcome}: {attempt.failure_kind.value}" rows.append( ( task.id, attempt.role, route, attempt.selection_reason, outcome, ( f"{len(attempt.context_source_ids)} sources, " f"~{attempt.context_token_estimate:,} tokens" ), ) ) return rows def report_analysis(plan: TaskPlan, config: Config): console.print(Panel.fit("[bold cyan]Analysis Complete[/bold cyan]", border_style="cyan")) for task in plan.tasks: if task.status == TaskStatus.PASSED: console.print(f"\n[bold]{task.title}[/bold]") console.print(task.description[:2000]) _report_task_attempts(plan) report_session_stats(config)