"""Read-only rendering for ``afk status [--watch]`` / ``afk campaign status --watch``. Session 3 of the refactor-handoffs plan (docs/refactor-handoffs/03-tui-watch.md Part 2). Everything here is strictly read-only: it never writes a state file and never acquires the campaign run lock (``CampaignStore.acquire_run_lock``) -- it only observes plan.json/campaign JSON files a different live process (or a finished run) owns. ``build_status_view`` is a pure function (no filesystem, no ``rich.live`` loop) so it is directly unit-testable; ``load_json_snapshot``/``watch_loop`` handle the actual polling and tolerate a poll landing mid atomic-replace. """ from __future__ import annotations import json import time from dataclasses import dataclass from datetime import datetime, timezone from pathlib import Path from typing import Any, Callable from rich import box from rich.console import Console, Group, RenderableType from rich.markup import escape from rich.panel import Panel from rich.table import Table _STATUS_STYLES = { "passed": "green", "not_applicable": "cyan", "failed": "red", "escalated": "red", "cancelled": "red", "in_progress": "yellow", "retrying": "yellow", "claimed": "yellow", "decomposed": "cyan", "pending": "dim", "blocked": "dim", } # Rich markup treats a bare `[name]` as an (unclosed) style tag and silently # swallows it if `name` looks like a plausible tag identifier -- true of `[x]` # and `[skip]` (but not `[ ]`/`[>]`, whose first character never matches Rich's # tag grammar). Escaped here so these ASCII markers always render literally # regardless of which marker they are. _PHASE_MARKERS = { "planned": escape("[ ]"), "active": escape("[>]"), "completed": escape("[x]"), "skipped": escape("[skip]"), } _PENDING_LIKE_STATUSES = {"pending", "claimed", "in_progress", "retrying"} def _safe(text: str) -> str: """Encode arbitrary (possibly LLM-generated) text for a legacy Windows console. Mirrors ``cli.py``'s own ``_safe()`` -- duplicated here (rather than imported) since it is two lines and importing from ``cli.py`` at module level would create a circular import (``cli.py`` imports this module). """ return text.encode("ascii", "replace").decode("ascii") @dataclass class JsonSnapshot: """One successfully (or previously) loaded JSON state file.""" payload: dict[str, Any] mtime: datetime | None stale: bool = False @dataclass(frozen=True) class FleetStatusEntry: """One campaign or standalone plan summarized for the fleet index.""" name: str target: str state: str milestone: str passed: int pending: int escalated: int active_task: str updated_at: datetime | None action: str class SnapshotLoadError(RuntimeError): """Raised only when there is no prior good snapshot to fall back to.""" def load_json_snapshot(path: Path, previous: JsonSnapshot | None = None) -> JsonSnapshot: """Load one JSON state file, tolerating a poll landing mid atomic-replace. On ``OSError`` (missing file, permission hiccup, ...) or malformed JSON, the previous good snapshot is returned again with ``stale=True`` instead of raising -- a watch loop must never crash or blank the screen just because it polled at the wrong instant. Raises ``SnapshotLoadError`` only when there is no previous snapshot to fall back to (the very first load). """ try: text = path.read_text(encoding="utf-8") payload = json.loads(text) mtime = datetime.fromtimestamp(path.stat().st_mtime, tz=timezone.utc) except (OSError, json.JSONDecodeError) as exc: if previous is not None: return JsonSnapshot(payload=previous.payload, mtime=previous.mtime, stale=True) raise SnapshotLoadError(f"Could not load state from {path}: {exc}") from exc return JsonSnapshot(payload=payload, mtime=mtime, stale=False) def _parse_timestamp(value: Any) -> datetime | None: if not value: return None if isinstance(value, datetime): return value try: return datetime.fromisoformat(str(value)) except ValueError: return None def _lease_label(task: dict[str, Any], *, now: datetime) -> str: """The "what is running right now" signal for one task's lease fields.""" expires_at = _parse_timestamp(task.get("lease_expires_at")) if expires_at is None or expires_at <= now: return "" owner = task.get("lease_owner") or "?" return escape(f"[>] RUNNING (pid {owner})") def _task_counts(tasks: list[dict[str, Any]]) -> dict[str, int]: counts: dict[str, int] = {} for task in tasks: status = str(task.get("status", "pending")) counts[status] = counts.get(status, 0) + 1 return counts def _format_timestamp(value: datetime | None) -> str: if value is None: return "unknown" return value.strftime("%Y-%m-%d %H:%M:%S UTC") def _active_task(tasks: list[dict[str, Any]], *, now: datetime) -> str: for task in tasks: expires_at = _parse_timestamp(task.get("lease_expires_at")) if expires_at is not None and expires_at > now: return str(task.get("id", "?")) return "" def _campaign_milestone(campaign: dict[str, Any]) -> str: phases = campaign.get("phases") or [] for phase in phases: if phase.get("status") in {"active", "planned"}: return f"{phase.get('ordinal', '?')}. {phase.get('name', '')}" if phases: return "All phases resolved" return "Roadmap not drafted" def _campaign_action(campaign: dict[str, Any], counts: dict[str, int], active_task: str) -> str: status = str(campaign.get("status", "ready")) if status == "release_ready": return "needs release witness" if status == "completed": return "complete" if status in {"cancelled", "exhausted"}: return "stopped" if status == "escalated" or counts.get("escalated", 0): return "needs supervisor decision" if not campaign.get("plan_approved", False): return "needs roadmap approval" if active_task or status == "running": return "running" return "stopped" def _standalone_action(counts: dict[str, int], active_task: str, task_count: int) -> str: if counts.get("escalated", 0): return "needs supervisor decision" if active_task: return "running" resolved = counts.get("passed", 0) + counts.get("not_applicable", 0) if task_count and resolved == task_count: return "complete" return "stopped" def load_fleet_status_entries( projects_dir: Path, *, now: datetime | None = None ) -> list[FleetStatusEntry]: """Load every durable campaign and unowned standalone plan without taking locks.""" now = now or datetime.now(timezone.utc) plans: dict[str, JsonSnapshot] = {} for path in sorted(projects_dir.glob("*/plan.json")): try: snapshot = load_json_snapshot(path) except SnapshotLoadError: continue name = str(snapshot.payload.get("project_name") or path.parent.name) plans[name] = snapshot campaigns: list[JsonSnapshot] = [] campaign_dir = projects_dir / "campaigns" for path in sorted(campaign_dir.glob("*.json")): try: campaigns.append(load_json_snapshot(path)) except SnapshotLoadError: continue owned_plan_names = { str(item.get("plan_name")) for snapshot in campaigns for collection in ( snapshot.payload.get("phases") or [], snapshot.payload.get("batches") or [], ) for item in collection if item.get("plan_name") } entries: list[FleetStatusEntry] = [] for snapshot in campaigns: campaign = snapshot.payload plan_names = { str(item.get("plan_name")) for collection in (campaign.get("phases") or [], campaign.get("batches") or []) for item in collection if item.get("plan_name") } tasks = [ task for plan_name in plan_names if plan_name in plans for task in (plans[plan_name].payload.get("tasks") or []) ] counts = _task_counts(tasks) active_task = _active_task(tasks, now=now) updated_at = _parse_timestamp(campaign.get("updated_at")) or snapshot.mtime entries.append( FleetStatusEntry( name=str(campaign.get("name", "?")), target=str(campaign.get("project_dir", "")), state=str(campaign.get("status", "ready")), milestone=_campaign_milestone(campaign), passed=counts.get("passed", 0), pending=sum(counts.get(status, 0) for status in _PENDING_LIKE_STATUSES), escalated=counts.get("escalated", 0), active_task=active_task, updated_at=updated_at, action=_campaign_action(campaign, counts, active_task), ) ) for name, snapshot in plans.items(): if name in owned_plan_names: continue plan = snapshot.payload tasks = plan.get("tasks") or [] counts = _task_counts(tasks) active_task = _active_task(tasks, now=now) entries.append( FleetStatusEntry( name=name, target=str(plan.get("project_dir", "")), state="plan", milestone=str(plan.get("goal", ""))[:80], passed=counts.get("passed", 0), pending=sum(counts.get(status, 0) for status in _PENDING_LIKE_STATUSES), escalated=counts.get("escalated", 0), active_task=active_task, updated_at=snapshot.mtime, action=_standalone_action(counts, active_task, len(tasks)), ) ) return sorted(entries, key=lambda entry: entry.name.casefold()) def build_fleet_status_view( entries: list[FleetStatusEntry], *, now: datetime | None = None ) -> RenderableType: """Render the compact operator index used by bare ``afk status``.""" now = now or datetime.now(timezone.utc) table = Table.grid(padding=(0, 1)) table.add_column(overflow="fold") for entry in entries: table.add_row( "\n".join( [ ( f"[bold]{escape(_safe(entry.name))}[/bold] " f"{escape(_safe(f'[{entry.state}]'))} {escape(_safe(entry.action))}" ), f" Target: {escape(_safe(entry.target))}", f" Milestone: {escape(_safe(entry.milestone))}", ( f" Tasks P/P/E: {entry.passed}/{entry.pending}/{entry.escalated} " f"Lease: {escape(_safe(entry.active_task or '-'))} " f"Updated: {_format_timestamp(entry.updated_at)}" ), ] ) ) body: RenderableType if entries: body = table else: body = "[dim]No saved projects or campaigns.[/dim]" return Group( Panel.fit(body, title="AFK Projects", border_style="cyan", box=box.ASCII), f"[dim]Refreshed: {_format_timestamp(now)}[/dim]", ) def build_status_view( plan_payload: dict[str, Any] | None, campaign_state: dict[str, Any] | None = None, *, governance_state: dict[str, Any] | None = None, now: datetime | None = None, stale: bool = False, plan_mtime: datetime | None = None, ) -> RenderableType: """Render one snapshot of plan (and optional campaign) state. Pure function: both inputs are raw loaded JSON dicts (not typed pydantic models), so a viewer never crashes on a plan/campaign file a newer or older binary wrote. ``stale`` marks a snapshot that could not be freshly reloaded this poll -- the caller keeps passing the last good payload with this flag set rather than ever showing a blank screen. """ now = now or datetime.now(timezone.utc) renderables: list[RenderableType] = [] if plan_payload is None: renderables.append( Panel.fit("[red]No plan data available.[/red]", border_style="red", box=box.ASCII) ) return Group(*renderables) tasks = plan_payload.get("tasks") or [] counts = _task_counts(tasks) goal = _safe(str(plan_payload.get("goal", ""))) goal_display = escape(goal[:80] + ("..." if len(goal) > 80 else "")) project_name = escape(_safe(str(plan_payload.get("project_name", "?")))) stale_marker = " [yellow](stale)[/yellow]" if stale else "" pending_count = sum(counts.get(status, 0) for status in _PENDING_LIKE_STATUSES) header = "\n".join( [ f"[bold]{project_name}[/bold]{stale_marker}", f"Goal: {goal_display}", ( f"Passed: {counts.get('passed', 0)} Failed: {counts.get('failed', 0)} " f"Escalated: {counts.get('escalated', 0)} Decomposed: {counts.get('decomposed', 0)} " f"Pending: {pending_count} Blocked: {counts.get('blocked', 0)}" ), f"Last update: {_format_timestamp(plan_mtime)}", ] ) renderables.append(Panel.fit(header, title="Plan Status", border_style="cyan", box=box.ASCII)) table = Table(show_header=True, header_style="bold", box=box.ASCII) # overflow="fold" wraps long cell content onto extra lines instead of # Rich's default per-column ellipsis truncation, which uses a Unicode # "..." (U+2026) character -- exactly the non-ASCII console-crash class # this repo deliberately avoids (see cli.py's `_safe()`, test_reporter.py). table.add_column("Task", overflow="fold") table.add_column("Status", overflow="fold") table.add_column("Phase", overflow="fold") table.add_column("Retries", overflow="fold") table.add_column("Failure", overflow="fold") table.add_column("Attempts", overflow="fold") table.add_column("Lease", overflow="fold") for task in tasks: status = str(task.get("status", "pending")) style = _STATUS_STYLES.get(status, "white") table.add_row( escape(_safe(str(task.get("id", "?")))), f"[{style}]{status}[/{style}]", str(task.get("lifecycle_phase", "")), str(task.get("retry_count", 0)), str(task.get("failure_kind") or ""), str(len(task.get("attempts") or [])), _lease_label(task, now=now), ) renderables.append(table) governance = governance_state or {} environment_rejection = governance.get("environment_rejection") or {} environment_contract = governance.get("environment_contract") or {} environment_fingerprint = str(governance.get("environment_fingerprint") or "") pending_effects = governance.get("pending_effects") or {} decisions = governance.get("decisions") or {} counters = governance.get("counters") or {} latest_events = governance.get("latest_run_events") or {} attempt_summaries = governance.get("attempt_summaries") or {} product_validations = governance.get("product_validations") or {} if governance: environment_lines: list[str] = [] if environment_rejection: environment_lines.append( "[red]Environment rejected:[/red] " f"{escape(_safe(str(environment_rejection.get('code', '?'))))}" ) environment_lines.append(escape(_safe(str(environment_rejection.get("detail", ""))))) elif environment_fingerprint: target = (environment_contract.get("target") or {}).get("interpreter", "?") environment_lines.append("[green]Environment verified[/green]") environment_lines.append(f"Target: {escape(_safe(str(target)))}") environment_lines.append(f"Fingerprint: {escape(_safe(environment_fingerprint[:16]))}") if environment_lines: renderables.append( Panel.fit( "\n".join(environment_lines), title="Environment", border_style="blue", box=box.ASCII, ) ) event_table = Table(show_header=True, header_style="bold", box=box.ASCII) event_table.add_column("Task", overflow="fold") event_table.add_column("Latest event", overflow="fold") event_table.add_column("Attempts", overflow="fold") event_rows = 0 for task_id in sorted(set(latest_events) | set(attempt_summaries)): event = latest_events.get(task_id) or {} event_table.add_row( escape(_safe(str(task_id))), escape(_safe(str(event.get("kind", "")))), str(len(attempt_summaries.get(task_id) or [])), ) event_rows += 1 if event_rows: renderables.append(event_table) governance_lines = [ f"Worker attempts: {counters.get('worker_attempts', 0)}", f"Mechanical repairs: {counters.get('mechanical_repairs', 0)}", f"Supervisor decisions: {counters.get('supervisor_decisions', len(decisions))}", f"Strong-model calls: {counters.get('strong_model_calls', 0)}", f"Human escalations: {counters.get('human_escalations', 0)}", f"Pending effects: {len(pending_effects)}", ] if pending_effects: governance_lines.extend( f" {escape(_safe(str(effect_id)))}: {escape(_safe(str(operation)))}" for effect_id, operation in sorted(pending_effects.items()) ) renderables.append( Panel.fit( "\n".join(governance_lines), title="Governance", border_style="magenta", box=box.ASCII, ) ) checkpoints: list[str] = [] for task in tasks: checkpoint = task.get("product_validation") or {} if not checkpoint: continue task_id = escape(_safe(str(task.get("id", "?")))) status = str(checkpoint.get("status", "not_requested")) kind = escape(_safe(str(checkpoint.get("kind", "product validation")))) if status == "awaiting_human": instructions = escape(_safe(str(checkpoint.get("instructions", "")))) artifacts = ", ".join( escape(_safe(str(path))) for path in (checkpoint.get("artifact_paths") or []) ) checkpoints.extend( [ f"[yellow][>] {task_id}: {kind}[/yellow]", f" {instructions}", f" Artifacts: {artifacts or '(none)'}", f" Attest: afk attest-product-validation {task_id} --observation ...", ] ) elif status == "attested": observation = str(checkpoint.get("observation", "")) if not observation: observation = str( (product_validations.get(str(task.get("id", ""))) or {}).get("observation", "") ) checkpoints.append( f"[green][x] {task_id}: {kind} attested[/green] {escape(_safe(observation[:200]))}" ) if checkpoints: renderables.append( Panel.fit( "\n".join(checkpoints), title="Human Product Validation", border_style="yellow", box=box.ASCII, ) ) phases = (campaign_state or {}).get("phases") or [] if phases: resolved = sum(1 for phase in phases if phase.get("status") in ("completed", "skipped")) phase_lines = [f"Phases: {resolved}/{len(phases)} resolved"] for phase in phases: marker = _PHASE_MARKERS.get( str(phase.get("status", "planned")), _PHASE_MARKERS["planned"] ) phase_lines.append( f" {marker} {phase.get('ordinal', '?')}. {escape(_safe(str(phase.get('name', ''))))}" ) renderables.append( Panel.fit("\n".join(phase_lines), title="Phases", border_style="magenta", box=box.ASCII) ) renderables.append(f"[dim]Refreshed: {_format_timestamp(now)}[/dim]") return Group(*renderables) def watch_loop( console: Console, interval: float, render: Callable[[], RenderableType], ) -> None: """Drive a ``rich.live.Live`` loop calling ``render()`` every ``interval`` seconds until Ctrl+C. Strictly read-only: this helper only handles poll timing and redraw / clean-interrupt mechanics -- ``render`` is expected to reload and re-render from disk itself (e.g. via ``load_json_snapshot`` + ``build_status_view``), and is shared by ``afk status --watch`` and ``afk campaign status --watch``. """ from rich.live import Live with Live(render(), console=console, refresh_per_second=4, screen=False) as live: try: while True: time.sleep(interval) live.update(render()) except KeyboardInterrupt: pass