Coverage for src/ai_jury/theater.py: 100%
530 statements
« prev ^ index » next coverage.py v7.15.4, created at 2026-08-17 21:31 +0000
« prev ^ index » next coverage.py v7.15.4, created at 2026-08-17 21:31 +0000
1"""Animated "deliberation" scene for a live jury run (opt-in ``--theater`` mode).
3A presentation-only consumer of the orchestrator's ``on_event`` stream: it draws
4a top-down **deliberation room** where the models sit around a table, take turns
5speaking as the run moves through its phases (review -> debate -> verify ->
6decision), and reach a decision together — by panel vote, or recorded by the
7chair (the synthesizer). There is no judge; the jurors deliberate with each
8other. Pure stdlib (ANSI escapes; no curses, no deps).
10It reflects the REAL run — seats come from the configured panel, and every
11speech bubble / finding / decision is the actual structured output of that phase
12(``--mock`` drives the deterministic mock panel for a demo). It is a side
13channel only: it never touches the structured outcome, the report, or the CI
14gate, and it degrades to the plain ``--live`` transcript on a non-TTY.
16The design follows ``docs/theater-design.md``.
17"""
19from __future__ import annotations
21import shutil
22import sys
23import threading
24import time
26from .adapters import AgentResult
27from .findings import SEVERITY_ORDER, flatten_inline, parse_findings, parse_verdicts
29# ---- styling ---------------------------------------------------------------
30_RESET = "\033[0m"
31# Each vendor's own product brand colour (24-bit truecolor SGR). Matches the
32# website's vendor tokens: Anthropic coral, OpenAI teal, Google blue, local
33# violet. Terminals without truecolor degrade to the nearest available colour.
34_VENDOR_SGR = {
35 "anthropic": "38;2;217;119;87", # Claude #d97757
36 "anthropic-api": "38;2;217;119;87", # Claude API
37 "openai": "38;2;16;163;127", # Codex #10a37f
38 "openai-api": "38;2;16;163;127", # OpenAI API
39 "google": "38;2;66;133;244", # Antigravity #4285f4
40 "google-api": "38;2;66;133;244", # Gemini API
41 "local": "38;2;168;85;247", # local / open-weight #a855f7
42 "openai-compatible": "38;2;139;92;246", # OpenRouter/DeepSeek/Groq #8b5cf6
43 "cli": "38;2;236;72;153", # arbitrary CLI agent #ec4899
44}
45# Same brand palette as RGB tuples, for the pixel-art style (half-block render).
46_VENDOR_RGB = {
47 "anthropic": (217, 119, 87),
48 "anthropic-api": (217, 119, 87),
49 "openai": (16, 163, 127),
50 "openai-api": (16, 163, 127),
51 "google": (66, 133, 244),
52 "google-api": (66, 133, 244),
53 "local": (168, 85, 247),
54 "openai-compatible": (139, 92, 246),
55 "cli": (236, 72, 153),
56}
57# Pixel-art scene palette (RGB). The room is drawn into a pixel buffer and folded
58# to the terminal two rows at a time via the upper-half-block ▀ (fg = top pixel,
59# bg = bottom pixel), so it needs a truecolor + unicode terminal.
60_HALF = "▀" # ▀
61_PIX = {
62 "bg": (16, 16, 20), "floor_a": (208, 170, 120), "floor_b": (196, 156, 108),
63 "rug": (34, 36, 54), "table": (176, 110, 38), "table_edge": (150, 92, 28),
64 "glow": (210, 210, 210), "skin": (226, 208, 182), "spk": (255, 255, 255),
65}
66_PHASES = (("review", "REVIEW"), ("debate", "DEBATE"), ("verify", "VERIFY"),
67 ("synthesis", "DECISION"))
69_GLYPHS = {"caret": "▲", "ok": "✓", "no": "✗", "dispute": "⚖", "play": "⏵",
70 "idle": "•", "speak": "●", "table": "═"}
71_ASCII_GLYPHS = {"caret": "^", "ok": "v", "no": "x", "dispute": "?", "play": ">",
72 "idle": ".", "speak": "*", "table": "="}
73# Positive / negative / neutral verdict vocab for code AND issue modes.
74_VERDICT_POS = ("APPROVE", "READY")
75_VERDICT_NEG = ("REQUEST", "BLOCK", "NEEDS-INFO", "NEEDS INFO", "CHANGES")
78def _banner_sgr(verdict: str) -> str:
79 up = verdict.upper()
80 if any(k in up for k in _VERDICT_NEG):
81 return "97;41;1" # white on red
82 if any(k in up for k in _VERDICT_POS):
83 return "30;42;1" # black on green
84 return "30;43;1" # black on yellow (COMMENT / UNCLEAR / neutral)
87def supports_scene(stream) -> bool:
88 """True when ``stream`` is a TTY wide enough for the deliberation scene."""
89 try:
90 if not stream.isatty():
91 return False
92 except Exception: # noqa: BLE001
93 return False
94 return shutil.get_terminal_size((80, 24)).columns >= 60
97def _unsafe_cell_char(ch: str) -> bool:
98 """True for characters that must never appear in agent-influenced terminal
99 cell content: C0 controls (incl. ESC), DEL, C1 controls, and the Unicode
100 bidi/zero-width format characters used for text-spoofing (Trojan Source,
101 CVE-2021-42574). Styling escapes arrive separately via the trusted ``sgr``
102 argument, so any of these in the *content* is an injection/spoof attempt."""
103 o = ord(ch)
104 return (
105 o < 0x20 or o == 0x7F or 0x80 <= o <= 0x9F # C0 / DEL / C1
106 or 0x200B <= o <= 0x200F or 0x202A <= o <= 0x202E # zero-width / bidi
107 or 0x2066 <= o <= 0x2069 or o == 0xFEFF # bidi isolates / BOM
108 )
111class Screen:
112 """A fixed grid of (char, sgr) cells rendered to ANSI or plain text."""
114 def __init__(self, cols: int, rows: int):
115 self.cols, self.rows = cols, rows
116 self.clear()
118 def clear(self) -> None:
119 self._g = [[(" ", "")] * self.cols for _ in range(self.rows)]
121 def put(self, r: int, c: int, text: str, sgr: str = "") -> None:
122 if not (0 <= r < self.rows):
123 return
124 row = self._g[r]
125 for i, ch in enumerate(text):
126 # Scrub control / bidi / zero-width characters from agent-influenced
127 # cell content (finding claims, the verdict line). Styling arrives
128 # separately via ``sgr`` (trusted), so any of these in the content is
129 # a terminal-injection (cursor/clear/title) or text-spoof (bidi
130 # override) attempt. Replace with a space to keep the layout width.
131 if _unsafe_cell_char(ch):
132 ch = " "
133 x = c + i
134 if 0 <= x < self.cols:
135 row[x] = (ch, sgr)
137 def center(self, r: int, text: str, sgr: str = "") -> None:
138 self.put(r, max(0, (self.cols - len(text)) // 2), text, sgr)
140 def _row_ansi(self, row) -> str:
141 out, cur = [], None
142 for ch, sgr in row:
143 if sgr != cur:
144 out.append(_RESET if not sgr else f"\033[{sgr}m")
145 cur = sgr
146 out.append(ch)
147 if cur:
148 out.append(_RESET)
149 return "".join(out).rstrip()
151 def to_ansi(self) -> str:
152 return "\n".join(self._row_ansi(r) for r in self._g)
154 def to_plain(self) -> str:
155 return "\n".join("".join(ch for ch, _ in r).rstrip() for r in self._g)
158# Table geometry (rows on the fixed grid).
159_TABLE_TOP = 8
160_TABLE_BOT = 14
161_SEAT_SLOT = 14 # min horizontal room per seat before we fall back to a roster
163# Pixel-art band geometry (terminal rows occupied by the half-block scene).
164_PIX_TOP = 5
165_PIX_BOT = 17
168class Courtroom:
169 """Draws and animates the deliberation from the on_event stream.
171 (Class name kept for back-compat; the scene is a round-table deliberation.)
172 """
174 def __init__(self, agents, chair: str, *, case: str = "", stream=None,
175 animate: bool = True, cols: int | None = None, rows: int = 30,
176 capture=None, mode: str = "code", decision: str = "chair",
177 unicode: bool = True, style: str = "flat"):
178 # agents: list of (name, vendor); chair: the synthesizer (records the
179 # decision in chair mode). mode: "code"/"issue". decision: "chair" or
180 # "vote" (the panel tallies ballots) — different decision beat. style:
181 # "flat" (ANSI line scene) or "pixel" (half-block pixel-art room).
182 self.agents = list(agents)
183 self.chair = chair
184 self.case = case
185 self.mode = mode
186 self.decision = decision
187 self.out = stream if stream is not None else sys.stdout
188 self.animate = animate
189 self.cols = cols or min(98, max(70, shutil.get_terminal_size((90, 30)).columns))
190 self.rows = rows
191 self._capture = capture
192 self.unicode = unicode
193 # Pixel-art needs the half-block glyph + truecolor; with unicode off it
194 # transparently falls back to the flat line scene.
195 self.pixel = (style == "pixel" and unicode)
196 self.g = _GLYPHS if unicode else _ASCII_GLYPHS
197 self.hr = "─" if unicode else "-"
198 self.dot = "·" if unicode else "."
199 self.screen = Screen(self.cols, self.rows)
200 self.phase = None
201 self.done_phases: set[str] = set()
202 self.state: dict[str, str] = {a[0]: "idle" for a in self.agents}
203 self.log: list[str] = []
204 self.bubble: tuple[str, str] = ("", "")
205 self.verifies: list = []
206 self.verdict: str | None = None
207 self.vote = None
208 self.ballots: dict[str, str] = {}
209 self.debate_seen = False
210 self.max_round = 0
211 self.disputes = 0
212 self.start = time.monotonic()
213 # Background ticker: repaint on an interval so the clock stays live and
214 # the scene doesn't freeze between on_event callbacks (agents can run for
215 # tens of seconds). Guarded by a lock shared with event-driven repaints.
216 self.tick_interval = 1.0
217 self._lock = threading.RLock()
218 self._tick_stop: threading.Event | None = None
219 self._tick_thread: threading.Thread | None = None
221 # -- geometry --------------------------------------------------------
222 def _split_seats(self):
223 """Split jurors into the top edge and bottom edge of the table."""
224 n = len(self.agents)
225 top = self.agents[: (n + 1) // 2]
226 bottom = self.agents[(n + 1) // 2:]
227 return top, bottom
229 def _slots(self, count: int):
230 """Evenly spaced seat centre-x across the table's width."""
231 if count <= 0:
232 return []
233 x0, x1 = 4, self.cols - 4
234 span = x1 - x0
235 return [x0 + span * (2 * i + 1) // (2 * count) for i in range(count)]
237 def _seats_fit(self) -> bool:
238 top, bottom = self._split_seats()
239 widest = max(len(top), len(bottom), 1)
240 return (self.cols - 8) // widest >= _SEAT_SLOT
242 # -- painting --------------------------------------------------------
243 def _paint(self) -> None:
244 self.screen.clear()
245 self._title()
246 self._strip()
247 if self.pixel and self._seats_fit():
248 self._pixel_room()
249 elif self._seats_fit():
250 self._table_and_seats()
251 else:
252 self._roster()
253 self._speaking_area()
254 self._transcript()
255 self._status()
257 def _title(self) -> None:
258 s = self.screen
259 s.put(0, 1, f"{self.g['speak']} ai-jury - deliberation", "1")
260 decided = "panel vote" if self.decision == "vote" else f"chair: {self.chair[:10]}"
261 meta = f"{len(self.agents)} jurors {self.dot} {decided}"
262 if self.case:
263 meta = f"case: {self.case} {self.dot} " + meta
264 s.put(0, 34, meta, "2")
265 s.put(1, 0, self.hr, "2")
267 def _strip(self) -> None:
268 s = self.screen
269 x = 2
270 for kind, label in _PHASES:
271 text = label
272 if kind == "debate" and self.max_round > 1 and kind in (self.phase, *self.done_phases):
273 text = f"{label}{self.dot}r{self.max_round}"
274 if kind in self.done_phases:
275 mark, sgr = self.g["ok"], "32"
276 elif kind == self.phase:
277 mark, sgr = ">", "96;1"
278 else:
279 mark, sgr = self.dot, "2"
280 cell = f"{mark} {text}"
281 s.put(2, x, cell, sgr)
282 x += len(cell) + 1
283 if kind != _PHASES[-1][0]:
284 s.put(2, x, "--", "2")
285 x += 3
286 elapsed = int(time.monotonic() - self.start)
287 s.put(2, self.cols - 8, f"{elapsed // 60:02d}:{elapsed % 60:02d}", "96")
288 s.put(3, 0, self.hr, "2")
290 def _seat(self, x: int, name: str, vendor: str, *, facing: str) -> None:
291 """Draw one juror seated at the table (facing 'down' = top edge, 'up' =
292 bottom edge), with vendor-coloured nameplate + a chair/figure glyph."""
293 s = self.screen
294 st = self.state.get(name, "idle")
295 hi = st in ("speaking", "arguing")
296 vsgr = _VENDOR_SGR.get(vendor, "1") + (";1" if hi else "")
297 figure = self.g["speak"] if hi else self.g["idle"]
298 if st == "done":
299 figure = self.g["ok"]
300 elif st == "error":
301 figure = "!"
302 plate = f"{name[:10]}"
303 if self.chair == name and self.decision != "vote":
304 plate += "*" # chair/moderator marker
305 ballot = self.ballots.get(name)
306 plate_x = x - len(plate) // 2
307 fig = f"({figure})"
308 fx = x - 1
309 if facing == "down": # top edge: nameplate above, figure toward table
310 s.put(_TABLE_TOP - 3, plate_x, plate, vsgr)
311 s.put(_TABLE_TOP - 2, fx, fig, "96;1" if hi else "2")
312 if ballot:
313 s.put(_TABLE_TOP - 4, x - len(ballot) // 2 - 1, f"[{ballot[:8]}]",
314 _banner_sgr(ballot))
315 if hi:
316 s.put(_TABLE_TOP - 1, x, self.g["caret"], "96")
317 else: # bottom edge: figure toward table, nameplate below
318 if hi:
319 s.put(_TABLE_BOT, x, self.g["caret"], "96")
320 s.put(_TABLE_BOT + 1, fx, fig, "96;1" if hi else "2")
321 s.put(_TABLE_BOT + 2, plate_x, plate, vsgr)
322 if ballot:
323 s.put(_TABLE_BOT + 3, x - len(ballot) // 2 - 1, f"[{ballot[:8]}]",
324 _banner_sgr(ballot))
326 def _table_and_seats(self) -> None:
327 s = self.screen
328 tx0, tx1 = 6, self.cols - 7
329 # table border
330 s.put(_TABLE_TOP, tx0, "." + self.hr * (tx1 - tx0 - 1) + ".", "33")
331 for r in range(_TABLE_TOP + 1, _TABLE_BOT):
332 s.put(r, tx0, "|", "33")
333 s.put(r, tx1, "|", "33")
334 s.put(_TABLE_BOT, tx0, "'" + self.hr * (tx1 - tx0 - 1) + "'", "33")
335 self._table_interior()
336 top, bottom = self._split_seats()
337 for x, (name, vendor) in zip(self._slots(len(top)), top, strict=True):
338 self._seat(x, name, vendor, facing="down")
339 for x, (name, vendor) in zip(self._slots(len(bottom)), bottom, strict=True):
340 self._seat(x, name, vendor, facing="up")
342 def _table_interior(self) -> None:
343 """What's 'on the table': the decision, the verify checklist, or a hint."""
344 s = self.screen
345 mid = (_TABLE_TOP + _TABLE_BOT) // 2
346 if self.verdict:
347 extra = ""
348 if self.decision == "vote" and self.vote is not None:
349 extra = " (" + " · ".join(
350 f"{n} {lbl.lower()}" for lbl, n in self.vote.tally.items()
351 ) + ")"
352 label = ("DECISION by panel vote" if self.decision == "vote"
353 else "DECISION (chair)")
354 s.center(_TABLE_TOP + 1, label, "2")
355 sgr = _banner_sgr(self.verdict)
356 for j, ln in enumerate(self._wrap_banner(self.verdict + extra,
357 self.cols - 16, 3)):
358 s.center(_TABLE_TOP + 3 + j, f" {ln} ", sgr)
359 return
360 if self.phase == "verify" and self.verifies:
361 s.center(_TABLE_TOP + 1, "- verifying findings -", "1")
362 for j, v in enumerate(self.verifies[:4]):
363 mk, msg, sgr = self._verify_row(v)
364 s.put(_TABLE_TOP + 2 + j, 9, f"{mk} {msg}", sgr)
365 return
366 s.center(mid, f"case: {self.case}" if self.case else "deliberating…", "2")
368 def _roster(self) -> None:
369 # Compact fallback (many jurors / narrow terminal): a wrapped row of
370 # juror chips with state marks, no clipping.
371 s = self.screen
372 marks = {"speaking": self.g["caret"], "arguing": self.g["caret"],
373 "done": self.g["ok"], "error": "!"}
374 s.put(_TABLE_TOP, 2, "JURY:", "2")
375 row, x = _TABLE_TOP + 1, 4
376 for name, vendor in self.agents:
377 st = self.state.get(name, "idle")
378 label = f"{name[:10]}{marks.get(st, self.dot)}"
379 if x + len(label) + 2 > self.cols - 2:
380 row += 1
381 x = 4
382 if row > _TABLE_BOT:
383 break
384 s.put(row, x, label, _VENDOR_SGR.get(vendor, "1")
385 + (";1" if st in ("speaking", "arguing") else ""))
386 x += len(label) + 2
387 self._table_interior()
389 def _fit(self, text: str, width: int) -> str:
390 """Truncate ``text`` to ``width`` columns with an ellipsis so a long
391 verdict line never overflows the table / screen edge."""
392 if width <= 0:
393 return ""
394 if len(text) <= width:
395 return text
396 ell = "…" if self.unicode else "..."
397 return text[: max(0, width - len(ell))].rstrip() + ell
399 def _verdict_label(self, verdict: str) -> str:
400 """Short verdict keyword for the transcript log (the full rationale is on
401 the banner), e.g. 'NEEDS-INFO — long reason…' -> 'NEEDS-INFO'. Splits on
402 the em-dash / spaced-hyphen separator, never the keyword's own hyphen."""
403 head = verdict.split("—")[0].split(" - ")[0].strip()
404 return head or verdict
406 def _wrap_banner(self, text: str, width: int, max_lines: int) -> list[str]:
407 """Wrap ``text`` to ``width`` over at most ``max_lines`` rows so the
408 verdict is readable; if it still overflows, the last line gets an
409 ellipsis (better than truncating the whole verdict to one line)."""
410 lines = _wrap(text, width)
411 if len(lines) > max_lines:
412 lines = lines[:max_lines]
413 ell = "…" if self.unicode else "..."
414 # plain slice (not _fit, which would add its own ellipsis → "x… …")
415 lines[-1] = lines[-1][: max(0, width - len(ell) - 1)].rstrip() + " " + ell
416 return lines
418 def _verify_row(self, v):
419 msg = f"{v.status:<18} {flatten_inline(v.claim)[:40]}"
420 if v.status == "verified":
421 return self.g["ok"], msg, "32;1"
422 if v.status == "unsupported":
423 return self.g["no"], msg, "2;31"
424 return self.g["dispute"], msg, "33"
426 # -- pixel-art scene (--theater-style pixel) -------------------------
427 def _pix_slots(self, count: int, width: int):
428 """Evenly spaced seat centre-x in pixel columns across the room width."""
429 if count <= 0:
430 return []
431 x0, x1 = 9, width - 9
432 span = x1 - x0
433 return [x0 + span * (2 * i + 1) // (2 * count) for i in range(count)]
435 def _pixel_room(self) -> None:
436 """Draw the top-down room as pixel-art (half-block) and overlay labels."""
437 pw, ph = self.cols, (_PIX_BOT - _PIX_TOP + 1) * 2
438 px = [[_PIX["bg"]] * pw for _ in range(ph)]
440 def rect(x0, y0, x1, y1, c):
441 for y in range(max(0, y0), min(ph, y1 + 1)):
442 rowp = px[y]
443 for x in range(max(0, x0), min(pw, x1 + 1)):
444 rowp[x] = c
446 for y in range(ph): # warm checkerboard floor
447 for x in range(pw):
448 px[y][x] = _PIX["floor_a"] if (x // 2 + y // 2) % 2 else _PIX["floor_b"]
449 mx = 4
450 rect(mx, 2, pw - 1 - mx, ph - 3, _PIX["rug"])
451 tx0, ty0, tx1, ty1 = mx + 6, 8, pw - 1 - mx - 6, 17
452 rect(tx0, ty0, tx1, ty1, _PIX["table"])
453 rect(tx0, ty0, tx1, ty0 + 1, _PIX["table_edge"])
454 cx, cy = (tx0 + tx1) // 2, (ty0 + ty1) // 2
455 rect(cx - 6, cy - 1, cx + 6, cy + 1, _PIX["glow"])
457 eye = (40, 40, 54)
459 def figure(axc, heady, vendor, name):
460 body = _VENDOR_RGB.get(vendor, (180, 180, 190))
461 hair = tuple(int(c * 0.55) for c in body) # darker vendor tint
462 hi = self.state.get(name) in ("speaking", "arguing")
463 rect(axc - 2, heady, axc + 2, heady + 2, _PIX["skin"]) # head (5×3)
464 rect(axc - 2, heady, axc + 2, heady, hair) # hair on top
465 rect(axc - 1, heady + 1, axc - 1, heady + 1, eye) # left eye
466 rect(axc + 1, heady + 1, axc + 1, heady + 1, eye) # right eye
467 rect(axc - 2, heady + 3, axc + 2, heady + 5, body) # torso (5×3)
468 rect(axc - 3, heady + 3, axc - 3, heady + 4, body) # left arm
469 rect(axc + 3, heady + 3, axc + 3, heady + 4, body) # right arm
470 if hi: # speaking halo
471 rect(axc - 3, heady - 1, axc + 3, heady - 1, _PIX["spk"])
473 top, bottom = self._split_seats()
474 txs, bxs = self._pix_slots(len(top), pw), self._pix_slots(len(bottom), pw)
475 for axc, (name, vendor) in zip(txs, top, strict=True):
476 figure(axc, 2, vendor, name)
477 for axc, (name, vendor) in zip(bxs, bottom, strict=True):
478 figure(axc, 18, vendor, name)
480 self._blit_band(px)
481 self._pixel_overlays(txs, bxs, top, bottom)
483 def _blit_band(self, px) -> None:
484 """Fold the pixel buffer into the screen, two rows per cell via ▀."""
485 s = self.screen
486 for i in range(_PIX_BOT - _PIX_TOP + 1):
487 top_row, bot_row = px[2 * i], px[2 * i + 1]
488 for c in range(self.cols):
489 tr, tg, tb = top_row[c]
490 br, bg, bb = bot_row[c]
491 s.put(_PIX_TOP + i, c, _HALF, f"38;2;{tr};{tg};{tb};48;2;{br};{bg};{bb}")
493 def _pixel_overlays(self, txs, bxs, top, bottom) -> None:
494 """Names, ballots and the decision/verify text laid over the pixel band."""
495 s = self.screen
496 # name labels: top edge along the top of the band, bottom edge below it.
497 # Top ballots sit in the gap above the band; the bottom edge has no spare
498 # row (the speech band follows), so the panel tally on the table banner is
499 # the per-juror vote record there.
500 for x, (name, vendor) in zip(txs, top, strict=True):
501 self._pix_label(x, name, vendor, _PIX_TOP, ballot_row=_PIX_TOP - 1)
502 for x, (name, vendor) in zip(bxs, bottom, strict=True):
503 self._pix_label(x, name, vendor, _PIX_BOT, ballot_row=None)
505 mid = (_PIX_TOP + _PIX_BOT) // 2
506 if self.verdict:
507 extra = ""
508 if self.decision == "vote" and self.vote is not None:
509 extra = " (" + " · ".join(
510 f"{n} {lbl.lower()}" for lbl, n in self.vote.tally.items()) + ")"
511 label = ("DECISION by panel vote" if self.decision == "vote"
512 else "DECISION (chair)")
513 s.center(mid - 1, f" {label} ", "97;1")
514 sgr = _banner_sgr(self.verdict)
515 for j, ln in enumerate(self._wrap_banner(self.verdict + extra,
516 self.cols - 8, 3)):
517 s.center(mid + j, f" {ln} ", sgr)
518 elif self.phase == "verify" and self.verifies:
519 s.center(mid - 1, " verifying findings ", "97;1")
520 for j, v in enumerate(self.verifies[:3]):
521 mk, msg, sgr = self._verify_row(v)
522 s.center(mid + j, f"{mk} {msg}", sgr)
523 elif self.case:
524 s.center(mid, f" case: {self.case} ", "97;1")
526 def _pix_label(self, x, name, vendor, row, *, ballot_row) -> None:
527 st = self.state.get(name, "idle")
528 plate = name[:10]
529 if self.chair == name and self.decision != "vote":
530 plate += "*"
531 plate = f" {plate} " # padding for the dark pill
532 # Vendor-coloured, bold, on a dark pill so the name reads over the floor.
533 speaking = st in ("speaking", "arguing")
534 sgr = _VENDOR_SGR.get(vendor, "37") + ";48;2;22;22;32;1"
535 if speaking:
536 sgr = "30;47;1" # invert (black on white) while speaking
537 self.screen.put(row, max(0, x - len(plate) // 2), plate, sgr)
538 ballot = self.ballots.get(name)
539 if ballot and ballot_row is not None:
540 chip = f"[{ballot[:8]}]"
541 self.screen.put(ballot_row, max(0, x - len(chip) // 2), chip,
542 _banner_sgr(ballot))
544 def _speaking_area(self) -> None:
545 s = self.screen
546 r0 = 18
547 s.put(r0, 0, self.hr, "2")
548 speaker, text = self.bubble
549 if speaker and not self.verdict:
550 s.put(r0, 2, f" {speaker} is speaking ", "96;1")
551 wrapped = _wrap(text, self.cols - 12)[:3]
552 width = max((len(w) for w in wrapped), default=0)
553 s.put(r0 + 1, 6, "." + "-" * (width + 2) + ".", "2")
554 for j, w in enumerate(wrapped):
555 s.put(r0 + 2 + j, 6, f"( {w:<{width}} )", "39")
556 s.put(r0 + 2 + len(wrapped), 6, "'" + "-" * (width + 2) + "'", "2")
557 elif self.verdict:
558 # The full verdict is shown wrapped on the table banner now, so this
559 # is just the closing note.
560 s.put(r0, 2, " the panel has decided ", "1")
562 def _transcript(self) -> None:
563 s = self.screen
564 r0 = 23
565 s.put(r0, 0, self.hr, "2")
566 s.put(r0, 2, " TRANSCRIPT ", "2")
567 for j, line in enumerate(self.log[-4:]):
568 s.put(r0 + 1 + j, 2, self._fit(flatten_inline(line), self.cols - 4), "")
570 def _status(self) -> None:
571 s = self.screen
572 msg = "deliberation closed" if self.verdict else (f"{self.phase or 'opening'}...")
573 s.put(self.rows - 1, 2, f"{self.g['play']} {msg}", "96")
575 # -- emit / animate --------------------------------------------------
576 def _flush(self) -> None:
577 frame = self.screen.to_ansi()
578 if self._capture is not None:
579 self._capture.append(frame)
580 if self.animate:
581 self.out.write("\033[H\033[J" + frame)
582 self.out.flush()
584 def _render(self) -> None:
585 # Paint + flush as one critical section so an event-driven repaint and a
586 # background tick never interleave writes (torn frames) on the terminal.
587 with self._lock:
588 self._paint()
589 self._flush()
591 def _beat(self, secs: float) -> None:
592 if self.animate:
593 time.sleep(secs)
595 def _frame(self, beat: float = 0.0) -> None:
596 self._render()
597 self._beat(beat)
599 def _tick_loop(self) -> None:
600 # Repaint every ``tick_interval`` until stopped — keeps the clock live and
601 # the scene from freezing while the orchestrator waits on the agents.
602 assert self._tick_stop is not None
603 while not self._tick_stop.wait(self.tick_interval):
604 self._render()
606 def _start_ticker(self) -> None:
607 if not self.animate or self._tick_thread is not None:
608 return
609 self._tick_stop = threading.Event()
610 self._tick_thread = threading.Thread(target=self._tick_loop, daemon=True)
611 self._tick_thread.start()
613 def _stop_ticker(self) -> None:
614 if self._tick_stop is not None:
615 self._tick_stop.set()
616 if self._tick_thread is not None:
617 self._tick_thread.join(timeout=1.0)
618 self._tick_thread = None
620 # -- public API ------------------------------------------------------
621 def open(self) -> None:
622 if self.animate:
623 self.out.write("\033[2J\033[?25l")
624 self.phase = "review"
625 self.log.append("the jury convenes")
626 self._frame(0.4)
627 self._start_ticker()
629 def step(self, kind: str, result: AgentResult, round_no: int | None = None) -> None:
630 skipped_debate = (
631 kind in ("verify", "synthesis")
632 and not self.debate_seen
633 and "debate" not in self.done_phases
634 )
635 if kind != self.phase and self.phase is not None:
636 self.done_phases.update(
637 k for k, _ in _PHASES if k != kind and self._phase_before(k, kind)
638 )
639 if skipped_debate:
640 self.done_phases.add("debate")
641 self.log.append("no debate - the jurors agreed")
642 self.phase = kind
643 if kind == "debate":
644 self.debate_seen = True
645 self.max_round = max(self.max_round, round_no or 1)
646 if kind in ("review", "debate"):
647 self._speak(kind, result, round_no)
648 elif kind == "verify":
649 self._verify(result)
650 else: # synthesis (the four phases are exhaustive)
651 self._synthesize(result)
653 @staticmethod
654 def _phase_before(a: str, b: str) -> bool:
655 order = [k for k, _ in _PHASES]
656 return order.index(a) < order.index(b)
658 def _speak(self, kind, result, _round_no=None):
659 name = result.agent
660 for k in self.state:
661 if self.state[k] != "done":
662 self.state[k] = "idle"
663 self.state[name] = "arguing" if kind == "debate" else "speaking"
664 if not result.ok:
665 self.state[name] = "error"
666 self.bubble = (name, flatten_inline(result.error or "no output"))
667 self.log.append(f"{name}: failed")
668 self._frame(0.5)
669 return
670 findings, _ = parse_findings(result.output or "", name)
671 if findings:
672 top = sorted(findings, key=lambda f: SEVERITY_ORDER.get(f.severity, 9))[0]
673 text = f"[{top.severity}] {flatten_inline(top.claim)}"
674 verb = "raises" if kind == "review" else "argues"
675 self.log.append(f"{name} {verb} {top.severity}: {flatten_inline(top.claim)[:48]}")
676 else:
677 text = _gist(result.output or "")
678 self.log.append(f"{name}: {text[:54]}")
679 self.bubble = (name, text)
680 self._frame(0.6)
681 self.state[name] = "idle"
683 def _verify(self, result):
684 for k in self.state:
685 self.state[k] = "done" if self.state[k] != "error" else "error"
686 verdicts, _ = parse_verdicts(result.output or "", result.agent)
687 self.verifies = verdicts
689 ok = 0
690 self.disputes = 0
691 for v in verdicts:
692 if v.status == "verified":
693 ok += 1
694 elif v.status == "needs_human_decision":
695 self.disputes += 1
697 note = f"the jury verifies: {ok}/{len(verdicts) or 0} upheld"
698 if self.disputes:
699 note += f" {self.dot} {self.disputes} disputed"
700 self.log.append(note)
701 self.bubble = ("", "")
702 self._frame(0.6)
704 def _synthesize(self, result):
705 self.done_phases.update({"review", "debate", "verify"})
706 if self.decision != "vote":
707 self.verdict = _verdict_headline(result.output or "") if result.ok else "NO DECISION"
708 self.log.append(f"DECISION -> {self._verdict_label(self.verdict)}")
709 self._frame(0.4)
711 def set_vote(self, vote) -> None:
712 """Provide the panel-vote result (decided after the run) for the finale."""
713 self.vote = vote
714 self.verdict = getattr(vote, "verdict", None)
715 for b in getattr(vote, "ballots", []):
716 self.ballots[b.reviewer] = b.vote
718 def close(self) -> None:
719 self._stop_ticker()
720 self.done_phases.update(k for k, _ in _PHASES)
721 if self.decision == "vote" and self.vote is not None:
722 self.log.append(f"the panel votes -> {self._verdict_label(self.verdict)}")
723 self._frame(0.6)
724 self._frame()
725 if self.animate:
726 self.out.write("\033[?25h\n")
727 self.out.flush()
730# ---- helpers ---------------------------------------------------------------
731def _wrap(text: str, width: int) -> list[str]:
732 words, lines, cur = text.split(), [], ""
733 for w in words:
734 if len(cur) + len(w) + 1 > width and cur:
735 lines.append(cur)
736 cur = w
737 else:
738 cur = f"{cur} {w}".strip()
739 if cur:
740 lines.append(cur)
741 return lines or [""]
744def _gist(text: str) -> str:
745 for line in text.splitlines():
746 if line.strip():
747 return flatten_inline(line)[:100]
748 return "(no output)"
751def _verdict_headline(text: str) -> str:
752 lines = text.splitlines()
753 for i, line in enumerate(lines):
754 if line.strip().lower().startswith("## verdict"):
755 for nxt in lines[i + 1:]:
756 if nxt.strip():
757 return flatten_inline(nxt)
758 return _gist(text)