# Session 3 of 3: Event seam + live `--watch` status view You are working in `d:\dev\afk-developer` (Windows, PowerShell, branch `master`). This is the last of three sequential refactor sessions; **Sessions 1 and 2 must already be complete** (see Prerequisite gate). Your job has two parts: (1) put a structured event seam between the orchestration code and its console output, with byte-identical rendering today; (2) add a read-only live status view (`afk status --watch`) polling the already-durable state files. **Scope guard — explicitly excluded** (later steps of a larger plan; do not build any of them): JSONL event-log persistence, desktop/webhook notifications, a fleet-wide multi-project dashboard, anything using Textual or any new dependency. This session adds **zero new dependencies** — `rich` is already a dependency (verify in `pyproject.toml`) and `rich.live` is part of it. ## What this codebase is / why this matters afk-developer is an autonomous LLM coding orchestrator (Click CLI `afk`): task DAGs executed by LLM worker loops with git isolation, deterministic review, a recovery/escalation ladder, and a durable campaign layer. Runs last hours; today the only "UI" is scrolling Rich console text the user pipes through `Tee-Object` and tails manually. State, however, is already durable and atomically written — a live viewer is cheap; it was just never built: - Plan state: `~/.afk-developer/projects//plan.json` — task list with `status`, `lifecycle_phase`, `retry_count`, `failure_kind`, `failure_detail`, `attempts[]` (timestamps, outcome, usage), lease fields (`leased_at`, `lease_expires_at`, `lease_owner` = PID), recovery budgets. Loaded/saved by `cli.py::_load_plan`/`_save_plan` (atomic temp-file+replace with Windows retry). - Campaign state: `~/.afk-developer/projects/campaigns/.json` — `CampaignState` (status, batches, `phases[]` with per-phase status, active_seconds, stop_reason), managed by `CampaignStore` (also atomic writes) in `campaign_store.py` (post-Session-1 location). Console output today: module-level `console = Console()` singletons; ~115 call sites in `cli.py` (interactive command UX — NOT your target), ~30 in `scheduler/queue.py` (per-task run events), ~16 in `scheduler/worker.py` (tool-action lines via `_log_tool_action`), a handful in `campaign.py` business logic, ~15 in `reporter.py` (end-of-run summary tables — already pure rendering, leave as-is). ## Prerequisite gate ```powershell cd d:\dev\afk-developer git log --oneline -12 # expect Session 1 extraction + Session 2 dedup commits Test-Path afk_developer\scheduler\manual_retry.py # True Test-Path afk_developer\campaign_cli.py # True git status --short # clean python -m pytest -q # record counts — YOUR baseline python -m ruff check . # clean ``` If the Session 1/2 artifacts are missing, STOP and report. ## Ground rules (non-negotiable) 1. **Known env-specific failures — never "fix", never touch** (expect exactly these 3 at baseline): - `tests/test_config.py::test_default_environment_config_prefers_copilot_without_api_key` - `tests/test_auto_resume_guards.py::test_retry_commits_and_merges_the_resumed_task_branch` - `tests/test_auto_resume_guards.py::test_retry_required_profile_runs_validator_before_merging` 2. Part 1 is **zero behavior change**: identical rendered output through the seam. Part 2 is purely additive and strictly **read-only** — the watch view must never write any state file and never acquire the campaign run lock (`CampaignStore.acquire_run_lock`); it observes files owned by a different live process. 3. Full suite green after every commit; granular commits; never `git add -A` (stray untracked `prompts/*.md` files exist — leave them); never touch `projects/` or `.env`. Commit locally; do not push. 4. **Windows console safety:** this repo deliberately avoids non-ASCII in Rich output (see `_safe()` in cli.py and `tests/test_reporter.py`'s cp1252 tests). Use plain ASCII markers (`[ ]`, `[>]`, `[x]`, `[skip]` — the existing phase-list convention) in everything you render. 5. Circular-import rule: new modules imported by `cli.py` at module level must not import `cli.py` at module level — use function-body-local `import afk_developer.cli as cli` + attribute access (established repo pattern; also keeps test monkeypatch targets working). 6. Thread safety: run events are emitted from worker threads (`--workers N`). The default sink must serialize emission (a `threading.Lock` around the console call). Note: `threading.Lock | None` as a bare annotation crashes at import time in modules without `from __future__ import annotations` — quote the annotation (`"threading.Lock | None"`); this repo has hit that before. ## Part 1 — `RunEvent` / `EventSink` seam New module `afk_developer/events.py` (name chosen to avoid clashing with the existing `reporter.py`): ```python @dataclass(frozen=True) class RunEvent: kind: str # coarse taxonomy, see below text: str # the EXACT pre-formatted Rich-markup line printed today data: dict = field(default_factory=dict) # structured payload for future sinks class EventSink(Protocol): def emit(self, event: RunEvent) -> None: ... class ConsoleSink: # default; lock + console.print(event.text) — byte-identical output def get_sink() -> EventSink: ... def set_sink(sink: EventSink) -> None: ... # module-level default = ConsoleSink() def emit(kind: str, text: str, **data) -> None: ... # convenience ``` Migration (mechanical, one module per commit): 1. `scheduler/queue.py` (~30 sites): replace `console.print(X)` with `emit(kind, X, ...)`. 2. `scheduler/worker.py` (~16 sites, mostly `_log_tool_action`): same. 3. `campaign.py` business-logic prints: same. 4. `cli.py`'s ~115 interactive prints **stay as `console.print`** — command UX, not run events. `reporter.py` stays untouched. Taxonomy: keep it coarse and honest — `task_started`, `task_passed`, `task_failed`, `task_escalated`, `task_decomposed`, `attempt`, `tool_action`, `review`, `merge`, `warning`, `info` (fallback). Don't over-engineer: `info` for anything that doesn't cleanly fit. Populate `data` with obvious fields where they're already at hand (task_id, attempt number, tool name) — do not restructure calling code to enrich payloads. Zero-change proof: existing tests that capture output (CliRunner-based tests, capsys users, `test_reporter.py`) must pass **untouched**. Add a small `tests/test_events.py`: ConsoleSink renders `event.text` verbatim; `set_sink` swap captures events; concurrent emit from 2 threads doesn't interleave partial lines (lock works). ## Part 2 — `afk status [--watch]` New module `afk_developer/watch.py` + CLI wiring: 1. **Pure render function first** (this is what gets unit-tested): `build_status_view(plan_payload: dict, campaign_state, *, now: datetime) -> RenderableType`. Input = the raw loaded plan dict (+ optional CampaignState). Output = a Rich renderable: - Header: project name, goal (truncated ~80 chars), overall counts (passed/failed/escalated/decomposed/pending/blocked), plan-file mtime as "last update". - Task table: id, status (color-coded: green passed, red failed/escalated, yellow in_progress/retrying, cyan decomposed, dim pending), lifecycle_phase, retry_count, failure_kind (blank when none), attempt count. - **Lease column** — the "what is running right now" signal: when `lease_expires_at` > now, mark `[>] RUNNING (pid )`; expired lease ≠ running. - Phase checklist (`[ ]`/`[>]`/`[x]`/`[skip]`) when campaign state with phases is provided. - Footer: refresh timestamp; ASCII only throughout. 2. **Tolerant loader wrapper**: read plan.json (and campaign JSON when relevant) fresh each poll. On `FileNotFoundError`/`json.JSONDecodeError` (a poll can land mid-atomic-replace): keep and render the **last good snapshot** with a `(stale)` marker — never crash, never show a blank screen. First-ever load failing → clear one-line error and exit non-zero. 3. **CLI**: new top-level `afk status PROJECT_NAME [--watch] [--interval FLOAT]` in `cli.py` (default: one-shot snapshot print; `--watch`: `rich.live.Live` loop, default interval ~2s, clean Ctrl+C exit). Add a `--watch/--interval` flag to `campaign status` in `campaign_cli.py`, reusing the same loop with the campaign+phase view. Path resolution via the existing helpers (`cli._get_plan_path` / `cli._load_plan` — but note `_load_plan` constructs typed models and **raises** on some invalid fields; for the viewer prefer reading the raw JSON dict so a viewer never crashes on a plan a newer/older binary wrote — `build_status_view` takes the raw dict for exactly this reason). 4. Stretch only (skip freely): `afk status` with no argument lists all projects under `~/.afk-developer/projects/` one summary row each. ## Verification 1. Unit tests for `build_status_view` with synthetic plan dicts: each status color/marker branch; active vs expired lease; phase checklist; totals row; goal truncation. Pure function — no filesystem, no Live loop. 2. Loader-tolerance test: feed a half-written/invalid JSON file, assert last-good snapshot retention + stale marker. 3. Seam tests per Part 1; full suite ≥ baseline, same 3 env failures identical; ruff clean. 4. **Manual smoke** (do it, describe results in the completion report): pick an existing project dir under `~/.afk-developer/projects/` (e.g. a finished past run — `retro-editor` or `galemu` likely exist on this machine); run `afk status ` one-shot, then `afk status --watch` while (from a second terminal) copying a modified plan.json over the real one to observe a refresh, then restoring the original. If none exist, create a throwaway plan.json from test fixtures under a scratch project name and view that. ## Definition of done - `events.py` seam in place; queue/worker/campaign emit through it; rendered output byte-identical (all pre-existing output-asserting tests pass untouched). - `afk status` + `--watch` working one-shot and live against a real project dir; read-only; ASCII-safe; survives mid-write polls. - `campaign status --watch` works for a phased campaign file. - Suite ≥ baseline, same 3 env failures, ruff clean. `AGENTS.md` updated (events.py, watch.py, and the "orchestration emits events, sinks render" boundary). Nothing pushed. ## Completion report (fill in before ending the session) Append here: baseline vs final test counts; sites migrated per module (queue/worker/campaign); any print site you deliberately did NOT migrate and why; watch-view smoke-test observations (including what stale-tolerance looked like in practice); leftovers/ideas for the deferred steps (JSONL log, notifications, fleet viewer) WITHOUT building them. **Prerequisite gate**: confirmed clean before starting -- `scheduler/manual_retry.py` and `campaign_cli.py` both exist (Session 1/2 artifacts), `git status --short` clean, Session 2's work (`a1942b8` "Fill in Session 2 completion report") was already committed and matched what repo memory expected. Baseline: **337 passed / 3 known env-specific failures** (never touched -- same 3, same reasons, verified identical at every commit below): `test_default_environment_config_prefers_copilot_without_api_key`, `test_retry_commits_and_merges_the_resumed_task_branch`, `test_retry_required_profile_runs_validator_before_merging`. Ruff clean throughout. **Final: 369 passed / same 3 failures.** 7 commits, all local, nothing pushed (verified `git log origin/master..HEAD` before finishing): `8a8a8e2` events.py seam -> `dff158c` queue.py migration -> `11d04bc` worker.py migration -> `98b3d53` best_of_n.py migration + dead-code cleanup -> `39845b9` watch.py + `afk status` -> `bc8abf1` `campaign status --watch` + a real bugfix -> `f0f48b5` a second real bugfix + AGENTS.md. ### Part 1 -- event seam: sites migrated per module Read every module in full before migrating (not just grep hits) to assign an honest `kind` per call site and to catch fallout in files not named in this doc. **Actual counts differed from the doc's estimate** -- worth noting for anyone estimating a similar migration later: greps count call sites more reliably than a prior line-span read-through does. - **`scheduler/queue.py`: 56 sites** (doc estimated ~30) -- all of them, no exceptions. Classified each into the taxonomy (`task_started/task_passed/task_failed/task_escalated/task_decomposed/ merge/warning/info`; none needed `attempt`/`review` as the top-level kind since those turned out to already be covered by the others in context). Added `task_id=task.id` (or `parent.id`/ `task_id` where the in-scope variable was named differently) to nearly every call as free, zero-restructuring `data` -- `task`/`task_id` was already a plain local in every case, matching the doc's "populate where obvious, don't restructure" instruction literally. Migrated mechanically via a throwaway line-indexed Python script (same technique as Session 1's extractions: never hand-transcribe), reviewed the diff, then deleted the script. One real bug in the script's first draft: it inserted a new `task_id=...,` line before the closing paren of a multi-line call without first adding a trailing comma after the last string-literal argument line (implicit string concatenation has no comma today) -- caught immediately by `ast.parse` failing on 20+ sites at once, fixed by making the script always append a comma to the last argument line before inserting the kwarg line, verified again with `ast.parse` before running ruff/pytest. - **`scheduler/worker.py`: 9 of 16 `console.print` sites migrated** (all of `_log_tool_action`, kind `tool_action`, `tool=name` data). **7 sites deliberately NOT migrated**: `_hitl_approve`'s `Panel.fit(...)` prompts, the `[A]pprove/[R]eject/[F]ull-auto/[Q]uit` prompt line, the blank `console.print()` before reading a key, and the "Switching to full-auto (AFK) mode" line. Two independent reasons, either alone sufficient: (1) `RunEvent.text` is typed `str` and `ConsoleSink` renders it directly -- a `Panel` object isn't a string and migrating would have required a design change the doc didn't ask for; (2) this whole method blocks synchronously on `click.getchar()` for human approval -- it is interactive command UX (same category as `cli.py`'s ~115 prints the doc explicitly excludes), not a one-way orchestration event a future sink would ever want to replay. - **`scheduler/best_of_n.py`: 2 sites, not named in this doc** (that file didn't exist when the ~30-site estimate for queue.py was likely written -- it was extracted FROM queue.py in Session 1). Found only because `AGENTS.md`'s own module-boundaries note for `best_of_n.py` mentioned it reaches back into `queue_mod.console` for monkeypatch-compatibility reasons -- grepped for that exact pattern before assuming queue.py's migration was complete. Migrated both (`task_escalated`/`task_passed`, `task_id=task.id`) via a direct import of `events.emit` (no `queue_mod` indirection needed, since `emit` is a plain leaf-module function). - **`campaign.py` / `campaign_runner.py`: zero sites, confirmed before starting, nothing to do.** Grepped for even a bare `console` reference in both files (not just `console.print`) and found none -- whatever business-logic prints this doc anticipated must have already been extracted or never existed by the time Sessions 1/2 landed. Not a gap in this session's migration; verified, not assumed. - **Drive-by cleanup**: once best_of_n.py's 2 sites were migrated, `queue.py`'s own `console = Console()` (kept alive only because best_of_n.py referenced it as `queue_mod.console`) became fully dead code with zero references anywhere in the codebase or tests (grepped both before removing) -- deleted it and the now-unused `from rich.console import Console` import from `queue.py`. `worker.py` keeps its own `console`/`Console` import for the HITL flow above. - **Zero-change proof**: no test in this repo captures `queue.py`/`worker.py`/`best_of_n.py`'s printed text via `capsys` or a `console` monkeypatch (grepped for `queue_mod.console`, `queue.console`, `worker.console` across `tests/` before migrating -- only `reporter.console` gets monkeypatched, and `reporter.py` was untouched) -- so "zero behavior change" was verified by full-suite-green rather than by any test literally diffing rendered text before/after. New `tests/test_events.py` (4 tests) covers `ConsoleSink` rendering `event.text` verbatim, a `set_sink` capture swap, the default-sink type, and concurrent-emit thread-safety (a real `threading.Barrier`-style two-thread race asserting no interleaved partial lines). ### Part 2 -- `afk_developer/watch.py` Built `RunEvent`-adjacent but independent: `JsonSnapshot`/`SnapshotLoadError`/ `load_json_snapshot` (generic tolerant loader, reused for both plan.json and campaign JSON -- not two copies), `build_status_view` (pure, ASCII-only, escapes every free-text field), and `watch_loop` (shared `rich.live.Live` polling helper used by both `afk status --watch` and `afk campaign status --watch`). Wired `afk status PROJECT_NAME [--watch] [--interval]` into `cli.py` and `--watch/--interval` onto the existing `campaign status` command in `campaign_cli.py`. Stretch goal (`afk status` with no argument listing all projects) skipped per the doc's own "skip freely." **Two real bugs found, both caught by testing against actual rendered output, not by reading the code** -- worth remembering generally: Rich's markup language silently reinterprets literal text that merely *looks like* its own control syntax, and this is easy to miss by inspection: 1. **Rich markup silently swallows `[x]`/`[skip]` as unclosed style tags** (`[ ]`/`[>]` survive because a space/`>` never matches Rich's tag-name grammar, but `x`/`skip` do look like plausible tag names). Caught immediately -- my own new `build_status_view` phase-checklist test failed with the markers simply missing from rendered output. Reproduced the *exact* pre-existing `campaign_cli.py::campaign_status` marker dict standalone (a bare `console.print(f"{marker} ...")`, no Panel involved) and confirmed **this is a real, independently pre-existing bug in already-shipped code**, not something this session introduced -- `campaign_cli.py`'s one-shot phase list has been silently dropping `[x]`/`[skip]` since Session 1 wrote it. No existing test caught it because `test_campaign_status_shows_phase_progress` only ever exercises a freshly-drafted roadmap (all phases still `PLANNED`, never `COMPLETED`/`SKIPPED`). Fixed both call sites with `rich.markup.escape()`: the new `watch.py` markers/lease-label and the pre-existing `campaign_cli.py::campaign_status` marker dict (a deliberate small drive-by fix, justified because it's literally "the existing phase-list convention" this session's own code was asked to reuse -- shipping my copy fixed while leaving its own source broken felt wrong, the fix is one line per marker, and a new regression test (`test_campaign_status_renders_completed_and_skipped_phase_markers`) pins it going forward). Also escaped `goal`/task `id`/phase `name` defensively (free LLM-generated text that could plausibly contain a literal bracket), not just the 4 static markers. 2. **Rich's `Table` default column-overflow behavior truncates long cell content with a Unicode ellipsis (U+2026)** -- exactly the non-ASCII-console crash class this repo's `_safe()`/ `test_reporter.py` cp1252 tests already guard against elsewhere, but a fresh instance of it in brand-new code. **Not caught by any unit test** (my synthetic fixtures used a 200-column test console, wide enough that nothing ever overflowed) -- caught only during the manual smoke test against the real `galemu` plan.json (30 real tasks, genuinely long ids/failure_kind strings), where `text.encode("ascii")` raised for real. Fixed with `overflow="fold"` on every column (wraps onto extra lines instead of eliding -- keeps all the data, at the cost of taller rows for long ids in a narrow terminal). Added a dedicated regression test using a deliberately narrow (60-column) console and long ids/failure_kind text, asserting no `\u2026` and a clean `.encode("ascii")`. **Lesson for next time**: a synthetic-fixture unit test with a generous fixed console width cannot catch a real terminal-width-dependent Rich rendering bug -- the manual smoke-test step in this doc's Verification section is not optional busywork, it caught something the automated tests structurally could not. **Manual smoke test** (real files, not just synthetic fixtures): one-shot `afk status galemu` and `afk status retro-editor` against this machine's actual production plan.json files rendered cleanly (confirmed ASCII-safe end-to-end after fix #2 above). For the live `--watch` + campaign path (no real campaign existed on this machine yet), created a throwaway `watch-smoke-test` campaign via the real `afk campaign create` CLI, then populated synthetic phases/tasks directly via `CampaignStore`/`_save_plan` (no real LLM calls, matching this doc's own sanctioned "throwaway plan.json from test fixtures" fallback) -- one task given an active `lease_expires_at`/`lease_owner` to exercise the running-lease column. Ran `afk campaign status watch-smoke-test --watch --interval 2` in the background and, from a second call: (a) flipped two phase statuses via `CampaignStore` directly and confirmed the live view picked up the new `[x]`/`[>]` markers and an updated "Refreshed" timestamp within one poll, with no restart; (b) overwrote the batch's `plan.json` with `"{not valid json"` (simulating a poll landing mid atomic-replace) and confirmed the view kept rendering the **last good snapshot with a `(stale)` marker** next to the project name rather than crashing or blanking; (c) restored the original `plan.json` and confirmed the `(stale)` marker disappeared on the next poll with no further intervention. Also ran `afk status galemu --watch` briefly against the real 30-task production plan to confirm no crash under real production-shaped data (attempts arrays, long `failure_detail` text, mixed statuses). All scratch campaign/plan/lock files and the throwaway setup script were deleted after verification -- nothing scratch was left on the machine or in the repo. **Leftovers / explicitly not built, matching this doc's own scope guard**: JSONL event-log persistence, desktop/webhook notifications, and a fleet-wide multi-project dashboard were not started -- all three remain exactly where `afk-developer.md` repo memory's "UI is literally tailed output" critique left them (steps 3-5 of that section's plan), now genuinely easier to add given the `events.py` seam and `watch.py`'s tolerant loader both exist as a foundation. One new, concrete idea surfaced by this session specifically: `afk status` with no `PROJECT_NAME` argument listing every project under `~/.afk-developer/projects/` (the doc's own stretch goal) would now be a small, mechanical addition -- `load_json_snapshot` + `build_status_view` already handle one project cleanly, this would just be a loop over `config.projects_dir.iterdir()` printing one summary line each, no design work needed.