"""Tests for afk_developer/watch.py (afk status [--watch] rendering). Session 3 of the refactor-handoffs plan (docs/refactor-handoffs/03-tui-watch.md Part 2). ``build_status_view`` is a pure function -- no filesystem, no ``rich.live`` loop -- exercised here via a real ``Console`` bound to an in-memory buffer so assertions check actual rendered text, not internals. ``load_json_snapshot`` is exercised against real temp files including a mid-write/invalid-JSON failure case. """ import json from datetime import datetime, timedelta, timezone from io import StringIO from pathlib import Path import pytest from rich.console import Console from afk_developer import watch as watch_module from afk_developer.watch import ( FleetStatusEntry, JsonSnapshot, SnapshotLoadError, build_fleet_status_view, build_status_view, load_fleet_status_entries, load_json_snapshot, watch_loop, ) def _render(renderable) -> str: buffer = StringIO() console = Console(file=buffer, force_terminal=False, width=200) console.print(renderable) return buffer.getvalue() def _plan(tasks: list[dict], **overrides) -> dict: payload = { "project_name": "widget-factory", "goal": "Build a working widget factory end to end", "tasks": tasks, } payload.update(overrides) return payload def _task(task_id: str, status: str, **overrides) -> dict: task = { "id": task_id, "status": status, "lifecycle_phase": "implementing", "retry_count": 0, "failure_kind": None, "attempts": [], } task.update(overrides) return task def _write_json(path: Path, payload: dict) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(payload), encoding="utf-8") def test_build_status_view_renders_header_counts_and_goal() -> None: plan = _plan( [ _task("t1", "passed"), _task("t2", "failed"), _task("t3", "escalated"), _task("t4", "decomposed"), _task("t5", "pending"), _task("t6", "blocked"), ] ) text = _render(build_status_view(plan, now=datetime.now(timezone.utc))) assert "widget-factory" in text assert "Build a working widget factory end to end" in text assert "Passed: 1" in text assert "Failed: 1" in text assert "Escalated: 1" in text assert "Decomposed: 1" in text assert "Pending: 1" in text assert "Blocked: 1" in text def test_build_status_view_truncates_a_long_goal_to_about_80_characters() -> None: long_goal = "x" * 200 plan = _plan([], goal=long_goal) text = _render(build_status_view(plan, now=datetime.now(timezone.utc))) assert "x" * 80 in text assert "x" * 84 not in text assert "..." in text @pytest.mark.parametrize( "status", ["passed", "failed", "escalated", "decomposed", "pending", "blocked", "retrying"], ) def test_build_status_view_renders_every_task_status(status: str) -> None: plan = _plan([_task("only-task", status)]) text = _render(build_status_view(plan, now=datetime.now(timezone.utc))) assert "only-task" in text assert status in text def test_build_status_view_marks_an_active_lease_as_running() -> None: now = datetime.now(timezone.utc) task = _task( "running-task", "in_progress", lease_owner="4321", lease_expires_at=(now + timedelta(minutes=5)).isoformat(), ) text = _render(build_status_view(_plan([task]), now=now)) assert "RUNNING" in text assert "4321" in text def test_build_status_view_does_not_mark_an_expired_lease_as_running() -> None: now = datetime.now(timezone.utc) task = _task( "stale-lease-task", "in_progress", lease_owner="4321", lease_expires_at=(now - timedelta(minutes=5)).isoformat(), ) text = _render(build_status_view(_plan([task]), now=now)) assert "RUNNING" not in text def test_build_status_view_renders_a_phase_checklist_with_ascii_markers() -> None: plan = _plan([_task("t1", "passed")]) campaign_state = { "phases": [ {"ordinal": 1, "name": "Foundations", "status": "completed"}, {"ordinal": 2, "name": "Core features", "status": "active"}, {"ordinal": 3, "name": "Polish", "status": "planned"}, {"ordinal": 4, "name": "Stretch goals", "status": "skipped"}, ] } text = _render(build_status_view(plan, campaign_state, now=datetime.now(timezone.utc))) assert "[x]" in text assert "[>]" in text assert "[ ]" in text assert "[skip]" in text assert "Phases: 2/4 resolved" in text def test_build_status_view_omits_phase_panel_when_no_campaign_state_given() -> None: plan = _plan([_task("t1", "passed")]) text = _render(build_status_view(plan, now=datetime.now(timezone.utc))) assert "Phases" not in text def test_build_status_view_marks_a_stale_snapshot() -> None: plan = _plan([_task("t1", "passed")]) text = _render(build_status_view(plan, now=datetime.now(timezone.utc), stale=True)) assert "(stale)" in text def test_build_status_view_renders_environment_and_governance_projection() -> None: plan = _plan([_task("t1", "passed")]) governance = { "environment_fingerprint": "abcdef0123456789", "environment_contract": {"target": {"interpreter": "C:/project/.venv/python.exe"}}, "environment_rejection": {}, "pending_effects": {"quarantine:t1:hash": "quarantine"}, "decisions": {"foreman-proposal:p1": "approve_decomposition"}, "counters": { "worker_attempts": 2, "mechanical_repairs": 1, "supervisor_decisions": 1, "strong_model_calls": 1, "human_escalations": 0, }, "latest_run_events": {"t1": {"kind": "task_passed"}}, "attempt_summaries": {"t1": [{"data": {"total_tokens": 42}}]}, } text = _render( build_status_view(plan, governance_state=governance, now=datetime.now(timezone.utc)) ) assert "Environment verified" in text assert "abcdef0123456789" in text assert "Supervisor decisions: 1" in text assert "Worker attempts: 2" in text assert "Mechanical repairs: 1" in text assert "Strong-model calls: 1" in text assert "Pending effects: 1" in text assert "task_passed" in text assert "Attempts" in text def test_build_status_view_renders_pending_human_checkpoint_instructions() -> None: task = _task( "audio-demo", "blocked", product_validation={ "kind": "audio listening", "status": "awaiting_human", "instructions": "Listen for the intended envelope.", "artifact_paths": ["output/demo.wav"], }, ) text = _render(build_status_view(_plan([task]), now=datetime.now(timezone.utc))) assert "Human Product Validation" in text assert "audio listening" in text assert "Listen for the intended envelope" in text assert "output/demo.wav" in text assert "attest-product-validation" in text def test_build_status_view_renders_attested_human_checkpoint_observation() -> None: task = _task( "audio-demo", "passed", product_validation={ "kind": "audio listening", "status": "attested", "observation": "Envelope and timbre are acceptable.", }, ) text = _render(build_status_view(_plan([task]), now=datetime.now(timezone.utc))) assert "attested" in text assert "Envelope and timbre are acceptable" in text def test_build_status_view_handles_missing_plan_payload_without_crashing() -> None: text = _render(build_status_view(None, now=datetime.now(timezone.utc))) assert "No plan data available" in text def test_build_status_view_encodes_unencodable_goal_text_for_a_legacy_console() -> None: """Reproduces the same cp1252-console crash class documented in tests/test_reporter.py -- a goal containing a character the active console codepage can't represent must not raise.""" plan = _plan([], goal="16\u2011bit widget goal") text = _render(build_status_view(plan, now=datetime.now(timezone.utc))) text.encode("ascii") # must not raise assert "16?bit widget goal" in text def test_build_status_view_never_introduces_richs_own_unicode_ellipsis_truncation() -> None: """Real bug found via manual smoke-testing against a real plan.json: Rich's default Table column overflow behavior truncates long cell content with a Unicode ellipsis (U+2026), which is not ASCII-safe -- exactly the crash class this repo's console output deliberately avoids. Uses a narrow console width and long IDs/failure text to force the overflow path.""" plan = _plan( [ _task( "a-very-long-task-id-that-will-not-fit-in-a-narrow-column", "failed", failure_kind="a_very_long_failure_kind_that_also_will_not_fit", ) ] ) buffer = StringIO() console = Console(file=buffer, force_terminal=False, width=60) console.print(build_status_view(plan, now=datetime.now(timezone.utc))) text = buffer.getvalue() assert "\u2026" not in text text.encode("ascii") # must not raise def test_load_fleet_status_entries_derives_actions_and_omits_owned_plans(tmp_path: Path) -> None: now = datetime(2026, 8, 28, 20, 0, tzinfo=timezone.utc) projects_dir = tmp_path / "projects" campaigns_dir = projects_dir / "campaigns" _write_json( projects_dir / "decision-phase" / "plan.json", _plan([_task("blocked-task", "escalated")], project_name="decision-phase"), ) _write_json( projects_dir / "running-phase" / "plan.json", _plan( [ _task( "active-task", "in_progress", lease_owner="1234", lease_expires_at=(now + timedelta(minutes=5)).isoformat(), ) ], project_name="running-phase", ), ) _write_json( projects_dir / "standalone" / "plan.json", _plan( [_task("finished-task", "passed")], project_name="standalone", project_dir="C:/work/standalone", ), ) campaign_payloads = { "approval": { "name": "approval", "project_dir": "C:/work/approval", "status": "ready", "plan_approved": False, "phases": [], }, "decision": { "name": "decision", "project_dir": "C:/work/decision", "status": "escalated", "plan_approved": True, "phases": [ { "ordinal": 2, "name": "Instruction repair", "status": "active", "plan_name": "decision-phase", } ], }, "running": { "name": "running", "project_dir": "C:/work/running", "status": "running", "plan_approved": True, "phases": [ { "ordinal": 1, "name": "Opcode execution", "status": "active", "plan_name": "running-phase", }, { "ordinal": 2, "name": "External validation", "status": "planned", "plan_name": "not-created-yet", }, ], }, "complete": { "name": "complete", "project_dir": "C:/work/complete", "status": "completed", "plan_approved": True, "phases": [{"ordinal": 1, "name": "Done", "status": "completed"}], }, "stopped": { "name": "stopped", "project_dir": "C:/work/stopped", "status": "cancelled", "plan_approved": True, "phases": [], }, "witness": { "name": "witness", "project_dir": "C:/work/witness", "status": "release_ready", "plan_approved": True, "phases": [{"ordinal": 1, "name": "Done", "status": "completed"}], }, } for name, payload in campaign_payloads.items(): _write_json(campaigns_dir / f"{name}.json", payload) entries = load_fleet_status_entries(projects_dir, now=now) by_name = {entry.name: entry for entry in entries} assert set(by_name) == { "approval", "decision", "running", "complete", "stopped", "witness", "standalone", } assert by_name["approval"].action == "needs roadmap approval" assert by_name["decision"].action == "needs supervisor decision" assert by_name["running"].action == "running" assert by_name["running"].active_task == "active-task" assert by_name["running"].milestone == "1. Opcode execution" assert by_name["complete"].action == "complete" assert by_name["stopped"].action == "stopped" assert by_name["witness"].action == "needs release witness" assert by_name["standalone"].action == "complete" def test_build_fleet_status_view_is_readable_and_ascii_safe_at_narrow_width() -> None: entry = FleetStatusEntry( name="new-processor-core", target="C:/work/new-processor-core", state="running", milestone="2. Implement documented opcodes", passed=12, pending=4, escalated=0, active_task="implement-load-store", updated_at=datetime(2026, 8, 28, 20, 0, tzinfo=timezone.utc), action="running", ) buffer = StringIO() console = Console(file=buffer, force_terminal=False, width=60) console.print(build_fleet_status_view([entry])) text = buffer.getvalue() assert "new-processor-core" in text assert "[running]" in text assert "Implement documented opcodes" in text assert "12/4/0" in text assert "Lease:" in text assert "implement-load-store" in text assert "\u2026" not in text text.encode("ascii") def test_load_json_snapshot_reads_a_valid_file(tmp_path: Path) -> None: path = tmp_path / "plan.json" path.write_text(json.dumps({"tasks": []}), encoding="utf-8") snapshot = load_json_snapshot(path) assert snapshot.payload == {"tasks": []} assert snapshot.stale is False assert snapshot.mtime is not None def test_load_json_snapshot_raises_with_no_prior_snapshot_to_fall_back_to( tmp_path: Path, ) -> None: missing = tmp_path / "does-not-exist.json" with pytest.raises(SnapshotLoadError): load_json_snapshot(missing) def test_load_json_snapshot_falls_back_to_the_previous_snapshot_on_invalid_json( tmp_path: Path, ) -> None: """Reproduces a poll landing mid atomic-replace: the file momentarily contains invalid JSON (or is briefly missing). The loader must keep serving the last good payload, marked stale, rather than crash.""" path = tmp_path / "plan.json" path.write_text(json.dumps({"tasks": [{"id": "t1"}]}), encoding="utf-8") good = load_json_snapshot(path) path.write_text("{not valid json", encoding="utf-8") snapshot = load_json_snapshot(path, previous=good) assert snapshot.stale is True assert snapshot.payload == {"tasks": [{"id": "t1"}]} def test_load_json_snapshot_falls_back_when_the_file_is_briefly_missing( tmp_path: Path, ) -> None: path = tmp_path / "plan.json" path.write_text(json.dumps({"tasks": [{"id": "t1"}]}), encoding="utf-8") good = load_json_snapshot(path) path.unlink() snapshot = load_json_snapshot(path, previous=good) assert snapshot.stale is True assert snapshot.payload == good.payload def test_load_json_snapshot_recovers_once_the_file_is_valid_again(tmp_path: Path) -> None: path = tmp_path / "plan.json" path.write_text(json.dumps({"tasks": [{"id": "t1"}]}), encoding="utf-8") good = load_json_snapshot(path) path.write_text("{not valid json", encoding="utf-8") stale = load_json_snapshot(path, previous=good) assert stale.stale is True path.write_text(json.dumps({"tasks": [{"id": "t2"}]}), encoding="utf-8") recovered = load_json_snapshot(path, previous=stale) assert recovered.stale is False assert recovered.payload == {"tasks": [{"id": "t2"}]} def test_json_snapshot_is_a_plain_dataclass_with_defaults() -> None: snapshot = JsonSnapshot(payload={"a": 1}, mtime=None) assert snapshot.stale is False def test_watch_loop_renders_immediately_then_again_after_each_interval(monkeypatch) -> None: """Drives a real rich.live.Live instance (not mocked) -- only time.sleep is faked, raising KeyboardInterrupt on the 3rd call to simulate Ctrl+C after two full poll intervals, exactly like a user stopping `afk status --watch`.""" calls = {"count": 0} sleep_calls = {"count": 0} def render(): calls["count"] += 1 return f"snapshot #{calls['count']}" def fake_sleep(_seconds): sleep_calls["count"] += 1 if sleep_calls["count"] >= 3: raise KeyboardInterrupt monkeypatch.setattr(watch_module.time, "sleep", fake_sleep) buffer = StringIO() console = Console(file=buffer, force_terminal=False, width=80) watch_loop(console, 0.01, render) # One render for the initial Live() renderable, plus one per successful # sleep before the interrupt (2 successful sleeps -> 3 total renders). assert calls["count"] == 3 assert sleep_calls["count"] == 3 def test_watch_loop_returns_cleanly_without_raising_keyboardinterrupt(monkeypatch) -> None: def fake_sleep(_seconds): raise KeyboardInterrupt monkeypatch.setattr(watch_module.time, "sleep", fake_sleep) buffer = StringIO() console = Console(file=buffer, force_terminal=False, width=80) watch_loop(console, 0.01, lambda: "one snapshot") # must not raise