"""Structured run-event seam between orchestration code and its rendering. Business logic in ``scheduler/queue.py``, ``scheduler/worker.py``, and ``scheduler/best_of_n.py`` emits coarse ``RunEvent`` objects instead of calling Rich's console directly. The default sink (``ConsoleSink``) renders byte-identical output to the pre-seam behavior -- this module adds an observability seam, not a behavior change. A future sink (e.g. a JSONL event log, or ``afk status --watch``) could observe the same events without any orchestration code changing. Deliberately NOT in scope here (see docs/refactor-handoffs/03-tui-watch.md): ``cli.py``'s interactive command-UX prints (~115 sites) and ``reporter.py``'s end-of-run summary tables stay on plain ``console.print`` -- neither is a "run event" in this sense. ``scheduler/worker.py``'s HITL approval prompts (``Panel.fit`` renderables plus a blocking ``click.getchar()`` read) are the same kind of interactive command UX and also stay untouched. """ from __future__ import annotations import threading import json from contextlib import contextmanager from dataclasses import dataclass, field from datetime import datetime, timezone from pathlib import Path from typing import Protocol from rich.console import Console console = Console() # Coarse, intentionally non-exhaustive taxonomy -- add a new kind only when an # existing one is genuinely a poor fit. "info" is the deliberate fallback for # anything that doesn't cleanly belong to one of the others. RUN_EVENT_KINDS = frozenset( { "task_started", "task_passed", "task_failed", "task_escalated", "task_decomposed", "attempt", "tool_action", "review", "merge", "warning", "info", } ) @dataclass(frozen=True) class RunEvent: """One coarse orchestration event. ``text`` is the exact pre-formatted Rich-markup line that used to be passed straight to ``console.print`` -- ``ConsoleSink`` renders it verbatim, so migrating a call site to ``emit()`` changes nothing about what a user watching the terminal sees today. ``data`` carries whatever structured fields are already on hand at the call site (task id, tool name, ...) for a future non-console sink; callers are not restructured just to populate it. """ kind: str text: str data: dict = field(default_factory=dict) class EventSink(Protocol): def emit(self, event: RunEvent) -> None: ... class ConsoleSink: """Default sink: renders exactly what ``console.print(event.text)`` did before. Run events are emitted from worker threads (``--workers N``), so emission is serialized with a lock to keep concurrent lines from interleaving mid-print. """ def __init__(self, console_: Console | None = None) -> None: self._console = console_ if console_ is not None else console self._lock = threading.Lock() def emit(self, event: RunEvent) -> None: with self._lock: # Live worker summaries are model-authored and can contain glyphs # unsupported by a legacy Windows cp1252 terminal (for example # arrows or narrow no-break spaces). A display failure must never # terminate the scheduler after a task has already completed. safe_text = event.text.encode("ascii", "replace").decode("ascii") self._console.print(safe_text) class JsonlSink: """Append safe coarse events as complete UTF-8 JSONL records.""" def __init__(self, path: Path) -> None: self.path = path self._lock = threading.Lock() def emit(self, event: RunEvent) -> None: record = { "timestamp": datetime.now(timezone.utc).isoformat(), "kind": event.kind, "text": event.text[:2_000], "data": event.data, } serialized = json.dumps(record, ensure_ascii=True, default=str) with self._lock: try: self.path.parent.mkdir(parents=True, exist_ok=True) with self.path.open("a", encoding="utf-8", newline="\n") as handle: handle.write(serialized + "\n") handle.flush() except OSError as exc: console.print(f"[yellow]Audit logging disabled: {exc}[/yellow]") class TeeSink: """Deliver an event to multiple sinks in the caller's emission order.""" def __init__(self, *sinks: EventSink) -> None: self._sinks = sinks def emit(self, event: RunEvent) -> None: for sink in self._sinks: sink.emit(event) class GovernanceSink: """Persist existing coarse scheduler events into the authoritative run log.""" def __init__(self, events_path: Path, snapshot_path: Path) -> None: from afk_developer.event_store import DurableEventStore self._store = DurableEventStore(events_path) self._snapshot_path = snapshot_path self._lock = threading.Lock() def emit(self, event: RunEvent) -> None: from afk_developer.event_store import EventProjector payload = { "run_kind": event.kind, "text": event.text[:2_000], "task_id": str(event.data.get("task_id", "")), "data": _json_safe(event.data), } with self._lock: self._store.append("run_event_recorded", payload) projector = EventProjector() projector.save_snapshot( self._snapshot_path, projector.rebuild(self._store, self._snapshot_path) ) def load_attempt_summaries(path: Path, task_id: str) -> list[dict]: """Read valid summary records only; a corrupt trailing line is ignored.""" if not path.is_file(): return [] summaries: list[dict] = [] try: lines = path.read_text(encoding="utf-8").splitlines() except OSError: return [] for line in lines: try: record = json.loads(line) except json.JSONDecodeError: continue data = record.get("data") if ( record.get("kind") == "attempt_summary" and isinstance(data, dict) and data.get("task_id") == task_id ): summaries.append(data) return summaries _default_sink: EventSink = ConsoleSink() def get_sink() -> EventSink: return _default_sink def set_sink(sink: EventSink) -> None: global _default_sink _default_sink = sink @contextmanager def audit_sink(path: Path | None): """Temporarily tee events to an opt-in JSONL file beside durable AFK state.""" if path is None: yield return previous = get_sink() set_sink(TeeSink(previous, JsonlSink(path))) try: yield finally: set_sink(previous) @contextmanager def governance_sink(events_path: Path, snapshot_path: Path): """Temporarily mirror scheduler events to a replayable durable projection.""" previous = get_sink() set_sink(TeeSink(previous, GovernanceSink(events_path, snapshot_path))) try: yield finally: set_sink(previous) def emit(kind: str, text: str, **data) -> None: get_sink().emit(RunEvent(kind=kind, text=text, data=data)) def _json_safe(value): if isinstance(value, dict): return {str(key): _json_safe(item) for key, item in value.items()} if isinstance(value, (list, tuple)): return [_json_safe(item) for item in value] if value is None or isinstance(value, (bool, int, float, str)): return value return str(value)