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