Coverage for src/ai_jury/report.py: 99%

389 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-10-20 18:15 +0000

1"""Render the jury run into a single markdown report.""" 

2 

3from __future__ import annotations 

4 

5import re 

6 

7from . import classification as _classification 

8from . import panel as panel_mod 

9from .adapters import AgentResult 

10from .findings import SEVERITY_ORDER, Finding, flatten_inline 

11from .voting import is_abstention 

12 

13#: A fenced ``suggestion`` block opener (``` ```suggestion ``` or a longer run, tildes too). 

14#: ``jury apply`` parses ``` ```suggestion ``` blocks out of a report's prose to build a patch, 

15#: and a reviewer's raw output is rendered into the transcript verbatim (#831 F3). A space 

16#: between the fence and ``suggestion`` breaks the apply parser's exact match while the block 

17#: still renders as a labelled code block, so a reviewer cannot smuggle in an applicable patch. 

18#: 

19#: NOT anchored to the line start: the apply parser (``patches.parse_patch_suggestions``) is 

20#: itself unanchored, so it matches ``` ```suggestion ``` after a blockquote (``> ``) or list 

21#: (``- ``) marker too, and the defuser has to reach the same spellings (agy round 1). 

22_SUGGESTION_FENCE = re.compile(r"(?m)(`{3,}|~{3,})(suggestion)(?=\s*$)") 

23 

24 

25def _defuse_patch_syntax(text: str) -> str: 

26 """Neutralise a ``suggestion`` code fence in untrusted agent output (#831 F3).""" 

27 return _SUGGESTION_FENCE.sub(r"\1 \2", text) 

28 

29 

30def _block(title: str, body: str) -> str: 

31 return f"### {title}\n\n{_defuse_patch_syntax(body).strip() or '_(no output)_'}\n" 

32 

33 

34def _excluded_block(excluded_files) -> list[str]: 

35 """The "Not shown to reviewers" line for binary files (#978); ``[]`` when none. 

36 

37 Only binary exclusions are named: they are the ones a reader cannot infer 

38 from the config, and a changed golden image was invisible to the panel. 

39 Paths come from the diff, so they are flattened to one line and have their 

40 backticks removed before being placed in code spans. 

41 """ 

42 from .largediff import EXCLUDE_BINARY 

43 from .prompts import BINARY_LIST_CAP, clean_paths 

44 

45 paths = clean_paths([p for p, why in (excluded_files or []) if why == EXCLUDE_BINARY]) 

46 if not paths: 

47 return [] 

48 names = [f"`{p.replace('`', chr(39))}`" for p in paths[:BINARY_LIST_CAP]] 

49 more = len(paths) - len(names) 

50 tail = f", +{more} more" if more > 0 else "" 

51 return [f"> Not shown to reviewers: {len(paths)} binary file(s): {', '.join(names)}{tail}\n"] 

52 

53 

54def _seat_list(reviews) -> str: 

55 """The seats that RETURNED a review, deduplicated, in seat order (issue #911). 

56 

57 A seat that failed did not sit, so it is not claimed; nor is one that 

58 abstained — answered with nothing, or refused (``voting.is_abstention``, 

59 docs audit 2026-09-29) — because it returned no review either, and naming it 

60 credited it with one. Chunked reviews carry one result per chunk per seat, 

61 hence the dedupe: a seat that reviewed any chunk is named. The name comes 

62 from the operator's config, not from an agent, but the footer is posted as 

63 raw HTML, so it is flattened and escaped anyway. 

64 """ 

65 import html 

66 

67 seats: list[str] = [] 

68 for r in reviews: 

69 name = html.escape(flatten_inline(r.agent or "")) 

70 if r.ok and not is_abstention(getattr(r, "output", "")) and name and name not in seats: 

71 seats.append(name) 

72 return ", ".join(seats) 

73 

74 

75def render_footer(reviews, *, transcript: bool = False) -> str: 

76 """The attribution footer a markdown report ends with (pure, issue #911). 

77 

78 One ``<sub>`` line naming the tool and the seats that returned a review, so a 

79 reader of a posted verdict can tell what produced it and where to get it. 

80 With no seat that returned a review the seat list is left out rather than 

81 claiming an empty panel. Returned with its ``---`` rule, ready to append. 

82 ``[jury.output] attribution = false`` / ``--no-attribution`` leave it off. 

83 """ 

84 seats = _seat_list(reviews) 

85 by = f" · {seats}" if seats else "" 

86 if transcript: 

87 body = ( 

88 f"<sub>Generated by [ai-jury](https://github.com/berkayturanci/ai-jury){by}" 

89 " — a cross-vendor multi-agent PR review jury.</sub>" 

90 ) 

91 else: 

92 body = ( 

93 f"<sub>🏛️ Synthesized by [ai-jury](https://github.com/berkayturanci/ai-jury){by}" 

94 " — Cross-vendor multi-agent code review · " 

95 "[⭐ Star on GitHub](https://github.com/berkayturanci/ai-jury) · " 

96 "[Add to your repo](https://ai-jury.dev/)</sub>" 

97 ) 

98 return f"---\n\n{body}" 

99 

100 

101def _fail_status(r: AgentResult) -> str: 

102 """Failed-agent status line with a concise typed-error-code prefix.""" 

103 prefix = f"[{r.error_code}] " if getattr(r, "error_code", None) else "" 

104 # The error snippet quotes the agent CLI's stderr (attacker-influenced) and 

105 # is posted to the PR, so flatten it like every other untrusted field so it 

106 # can't forge a heading/fence in the comment (audit 2026-06-13 r4). 

107 return f"⚠️ {prefix}{flatten_inline(r.error)}" 

108 

109 

110def _origin_tag(origin: str) -> str: 

111 if origin in ("introduced", "pre_existing"): 

112 return f" [{origin.replace('_', '-')}]" 

113 return "" 

114 

115 

116def _finding_line(f: Finding) -> str: 

117 loc = flatten_inline(f.file) or "?" 

118 if f.line is not None: 

119 loc = f"{loc}:{f.line}" 

120 claim = flatten_inline(f.claim) 

121 tag = _origin_tag(getattr(f, "origin", "")) 

122 return f"- [{f.severity}]{tag} {loc} — {claim} ({f.confidence}, by {f.reviewer})" 

123 

124 

125_BUCKET_LABELS = { 

126 "consensus": "Consensus (all reviewers)", 

127 "majority": "Majority", 

128 "single_reviewer": "Single reviewer", 

129 "disputed": "Disputed (needs human decision)", 

130 "rejected": "Rejected (unsupported by verifier)", 

131} 

132_BUCKET_ORDER = ["consensus", "majority", "single_reviewer", "disputed", "rejected"] 

133 

134_STATUS_LABELS = { 

135 "verified": "verified", 

136 "unsupported": "unsupported", 

137 "needs_human_decision": "needs human decision", 

138} 

139 

140 

141def _group_line(g) -> str: 

142 f = g.representative 

143 loc = flatten_inline(f.file) or "?" 

144 if f.line is not None: 

145 loc = f"{loc}:{f.line}" 

146 reviewers = ", ".join(g.reviewers) if g.reviewers else "(unknown)" 

147 tag = _origin_tag(getattr(g, "origin", "")) 

148 

149 # Attacker-influenced fields (claim/evidence/fix) are flattened to one line 

150 # so they cannot forge a heading or open a code fence in the posted report 

151 # (audit 2026-06-13 r3). 

152 parts = [f"- [{g.severity}]{tag} {loc} — {flatten_inline(f.claim)} (reviewers: {reviewers})"] 

153 

154 # Surface the reviewer's supporting evidence — the "why" behind the claim — 

155 # so the verdict is auditable, not just asserted (issue: evidence surfacing). 

156 if getattr(f, "evidence", ""): 

157 parts.append(f"\n - _evidence:_ {flatten_inline(f.evidence)}") 

158 

159 status = getattr(g, "status", "") 

160 if status: 

161 reasoning = flatten_inline(getattr(g, "status_reasoning", "")) 

162 if reasoning: 

163 parts.append( 

164 f"\n - _verification:_ {_STATUS_LABELS.get(status, status)} — {reasoning}" 

165 ) 

166 else: 

167 parts.append(f"\n - _verification:_ {_STATUS_LABELS.get(status, status)}") 

168 

169 if f.suggested_fix: 

170 parts.append(f"\n - _fix:_ {flatten_inline(f.suggested_fix)}") 

171 

172 return "".join(parts) if len(parts) > 1 else parts[0] 

173 

174 

175def _metadata_block(metadata: dict) -> list[str]: 

176 """Render the deterministic run-metadata section. 

177 

178 Intentionally omits non-deterministic fields (e.g. ``generated_at``) so the 

179 Markdown report stays stable for snapshot tests. Per-agent durations are 

180 deterministic under mock (0s) and scrubbed by the golden test's duration 

181 normalizer otherwise. Wall-clock is labelled a cost proxy, not a dollar cost. 

182 """ 

183 lines = ["## Run metadata\n"] 

184 lines.append(f"- rounds executed: {metadata['rounds_executed']}") 

185 # Adaptive-rounds explanation (issue #40): only shown when the orchestrator 

186 # recorded a reason, so a plain fixed-N run stays unchanged. 

187 if metadata.get("from_cache"): 

188 lines.append("- ♻️ served from local cache (not re-computed)") 

189 stop_reason = metadata.get("stop_reason") 

190 if stop_reason: 

191 # flatten metadata strings too (defense-in-depth, audit r6/L): these are 

192 # config/internal-controlled today, but keeping them single-line means a 

193 # name/reason can never break the table or forge structure if a future 

194 # source carries agent/diff text. 

195 lines.append(f"- rounds decision: {flatten_inline(stop_reason)}") 

196 routing_meta = metadata.get("routing") or {} 

197 if routing_meta.get("mode") == "tiered": 

198 # Tiered routing (#714): the cost decision is part of the run record. 

199 line = f"- routing: tiered — {flatten_inline(routing_meta.get('reason', ''))}" 

200 if routing_meta.get("escalated"): 

201 line += f"; escalated: {flatten_inline(routing_meta.get('escalation_reason', ''))}" 

202 lines.append(line) 

203 lines.append(f"- verify: {'on' if metadata['verify_enabled'] else 'off'}") 

204 lines.append(f"- context mode: {metadata['context_mode']}") 

205 # Partial-result signals (issue #30): only rendered when relevant so a 

206 # complete, unbudgeted run is unaffected. 

207 if metadata.get("budget_exhausted"): 

208 lines.append("- ⚠️ run budget exhausted: some phases were skipped") 

209 skipped = metadata.get("skipped") or [] 

210 if skipped: 

211 # bolt: CPython optimization — list comprehension inside join avoids generator overhead 

212 names = ", ".join( 

213 [f"{flatten_inline(s['name'])} ({flatten_inline(s['reason'])})" for s in skipped] 

214 ) 

215 lines.append(f"- skipped agents (never ran): {names}") 

216 # The zero-config fallback (#863): said in the report, since `--quiet` drops 

217 # the stderr line and the exit code alone does not say why this run passed. 

218 if (metadata.get("panel") or {}).get("zero_config_fallback"): 

219 lines.append( 

220 "- single local seat (zero-config fallback: no jury.toml and no agent CLI): " 

221 "a single-vendor panel, so the default cross-vendor guard does not fail it; " 

222 "a `--min-vendors N` named on the command line is still enforced" 

223 ) 

224 retried = metadata.get("retried") or [] 

225 if retried: 

226 lines.append(f"- retried agents: {', '.join(retried)}") 

227 # A short panel is stated, not left to be inferred from the agent table (#501). 

228 # Silence is the failure mode: a run with two non-reviewing slots described 

229 # itself as a full panel, and only the chair's prose said otherwise. 

230 panel = metadata.get("panel") or {} 

231 if panel.get("short"): 

232 lines.append( 

233 f"- ⚠️ **effective panel: {panel.get('effective', 0)} of " 

234 f"{panel.get('configured', 0)} reviewer(s)** " 

235 f"({panel.get('abstained', 0)} returned no review, " 

236 f"{panel.get('failed', 0)} failed) — " 

237 f"{panel.get('vendors', 0)} vendor(s) contributed " 

238 "(counted by vendor identity; the table below shows each seat's " 

239 "configured vendor). An abstention is not " 

240 "an approval; treat cross-vendor consensus accordingly." 

241 ) 

242 # What a downstream consumer will actually be handed, and the chair's role in 

243 # it (#699). Stated on every run, not only a short one: the number that got a 

244 # tier-3 review refused was produced by a panel nothing had flagged as short. 

245 # Presence, not truth: an all-silent panel supplies 0 reviews, and 0 is 

246 # falsy, so a truthiness guard deleted the line in the one run where a 

247 # reader most needs the number — while the run's own log still announced the 

248 # seats it had. Zero is a count, and it is printed as one. 

249 if panel.get("reviews_supplied") is not None: 

250 chair_name = panel.get("chair") or "" 

251 if panel.get("chair_ballot"): 

252 role = f"chair `{chair_name}` also sat on the panel — its review is one of them" 

253 elif chair_name: 

254 role = f"chair `{chair_name}` supplied no review of its own — synthesis only" 

255 else: # pragma: no cover - a run always resolves a chair 

256 role = "no chair was resolved" 

257 # The four ways a seat that ran supplies no review, named separately — 

258 # they ask for different fixes, and a single "N did not review" would 

259 # send a reader to the CLI logs for a reviewer that answered fine and 

260 # simply reviewed nothing (#700, round 2). The phrases come from 

261 # `panel.CAUSE_PHRASES`, the same table the shortfall message renders 

262 # from, so this line and that one describe the same seat the same way; 

263 # writing them apart is how "named nothing checkable and abstained" came 

264 # to be printed over a ballot that had named a file and then refused 

265 # (#700, round 5). 

266 missing = [ 

267 f"{panel[panel_mod.PANEL_METADATA_KEYS[cause]]} {panel_mod.CAUSE_PHRASES[cause]}" 

268 for cause in panel_mod.ABSTENTION_CAUSES 

269 if panel.get(panel_mod.PANEL_METADATA_KEYS[cause]) 

270 ] 

271 tail = f"; {', '.join(missing)}" if missing else "" 

272 lines.append( 

273 f"- reviews for a downstream consumer: {panel['reviews_supplied']} of " 

274 f"{panel.get('ballots', 0)} ballot(s) (a ballot counts only when it names " 

275 f"what it read and votes; the chair's synthesis record is carried alongside " 

276 f"them and is not a review); {role}{tail}" 

277 ) 

278 total = metadata["total_wall_clock_s"] 

279 lines.append(f"- total wall-clock (cost proxy, not $): {total:.0f}s") 

280 lines.append("") 

281 # The `vendor` column is PROVENANCE: the string the operator configured, 

282 # verbatim, even when the gate counts the seat as `cli` (#701). The count in 

283 # the short-panel line above is the gate's arithmetic, and says so. 

284 lines.append("| agent | vendor | status | duration |") 

285 lines.append("| --- | --- | --- | --- |") 

286 for a in metadata["agents"]: 

287 code = a.get("error_code") 

288 status = a["status"] if not code else f"{a['status']} ({code})" 

289 # "ok" alone hid a slot that returned nothing reviewable (#501). 

290 review = a.get("review_status") 

291 if review and review != "findings": 

292 status = f"{status}, {review}" 

293 # Note a retried agent inline; attempts == 1 leaves the row unchanged. 

294 attempts = a.get("attempts", 1) 

295 if attempts and attempts > 1: 

296 status += f", {attempts} attempts" 

297 lines.append( 

298 f"| {flatten_inline(a['name'])} | {flatten_inline(a['vendor'])} " 

299 f"| {status} | {a['duration_s']:.0f}s |" 

300 ) 

301 lines.append("") 

302 economics = metadata.get("economics") 

303 if economics and economics.get("breakdown"): 

304 lines.append("### 💰 Run Economics (estimated)\n") 

305 lines.append( 

306 f"- total tokens (est): ~{economics['total_tokens_est']:,} · " 

307 f"cost (est): ~${economics['total_cost_usd_est']:.4f} USD" 

308 ) 

309 if economics.get("local_free_slots"): 

310 lines.append( 

311 f"- ⚡ {economics['local_free_slots']} slot(s) powered by local models ($0.00 free offline)" 

312 ) 

313 lines.append("") 

314 lines.append( 

315 "_Wall-clock seconds and token counts are approximate cost proxies (no direct billing " 

316 "telemetry is extracted from CLIs), not guaranteed dollar costs._\n" 

317 ) 

318 return lines 

319 

320 

321def _classification_block(classification: dict) -> list[str]: 

322 """Render the compact PR-level classification summary. 

323 

324 Deterministic: ``classification`` is produced by the pure 

325 :mod:`ai_jury.classification` module, so the rendered section is 

326 stable for a deterministic run (and golden-tested under mock). 

327 """ 

328 return [ 

329 "## Classification\n", 

330 _classification.summary_line(classification), 

331 "", 

332 ] 

333 

334 

335def _consensus_block(groups) -> list[str]: 

336 lines = ["## Consensus\n"] 

337 by_bucket: dict[str, list] = {b: [] for b in _BUCKET_ORDER} 

338 for g in groups: 

339 by_bucket.setdefault(g.bucket, []).append(g) 

340 for bucket in _BUCKET_ORDER: 

341 bg = by_bucket.get(bucket) or [] 

342 if not bg: 

343 continue 

344 lines.append(f"### {_BUCKET_LABELS.get(bucket, bucket)}\n") 

345 for g in bg: 

346 lines.append(_group_line(g)) 

347 lines.append("") 

348 return lines 

349 

350 

351def _vote_block(vote) -> list[str]: 

352 """Render the panel-vote verdict + tally + per-reviewer ballots (issue #220). 

353 

354 Vocabulary-agnostic: the tally renders whatever stances the vote carries 

355 (code: REQUEST CHANGES/COMMENT/APPROVE; issue: NEEDS-INFO/UNCLEAR/READY). 

356 """ 

357 lines = ["## Verdict — panel vote\n"] 

358 # bolt: CPython optimization — list comprehension avoids generator expression overhead 

359 tally = " · ".join([f"{n} {label.lower()}" for label, n in vote.tally.items()]) 

360 lines.append(f"**{vote.verdict}** — {tally}\n") 

361 for b in vote.ballots: 

362 lines.append(f"- `{b.reviewer}`: **{b.vote}** ({b.reason})") 

363 lines.append("") 

364 return lines 

365 

366 

367def _verdict_headline(synthesis, vote) -> str | None: 

368 """One-line verdict for the report's TL;DR callout (pure, deterministic). 

369 

370 Prefers the panel vote's verdict when voting; otherwise lifts the opening 

371 ``## Verdict`` line out of the chair's synthesis prose — both the code and 

372 issue synthesis prompts mandate a ``## Verdict\\n<LABEL> — <one sentence>`` 

373 first section, so the lift is reliable. The verdict sentence may wrap across 

374 lines; they are joined into one. Returns ``None`` when neither source is 

375 available (failed/absent synthesis, deviating output) so the caller simply 

376 omits the callout — it is purely additive, never replacing a section. 

377 """ 

378 if vote is not None and getattr(vote, "verdict", None): 

379 return vote.verdict 

380 if synthesis is None or not getattr(synthesis, "ok", False): 

381 return None 

382 rows = (synthesis.output or "").splitlines() 

383 for i, row in enumerate(rows): 

384 if row.strip().lower().lstrip("#").strip() == "verdict": 

385 collected: list[str] = [] 

386 for nxt in rows[i + 1 :]: 

387 if nxt.strip().startswith("#"): 

388 break 

389 if not nxt.strip(): 

390 if collected: 

391 break 

392 continue 

393 collected.append(nxt.strip()) 

394 return " ".join(collected) or None 

395 return None 

396 

397 

398def render( 

399 reviews: list[AgentResult], 

400 debate: list[AgentResult], 

401 synthesis: AgentResult | None, 

402 *, 

403 chair: str, 

404 findings: list[Finding] | None = None, 

405 warnings: list[str] | None = None, 

406 groups: list | None = None, 

407 verify: AgentResult | None = None, 

408 context_mode: str | None = None, 

409 redact_secrets: bool | None = None, 

410 redaction_count: int = 0, 

411 metadata: dict | None = None, 

412 classification: dict | None = None, 

413 review_scope: str | None = None, 

414 vote=None, 

415 footer: bool = True, 

416 excluded_files=None, 

417) -> str: 

418 findings = findings or [] 

419 warnings = warnings or [] 

420 groups = groups or [] 

421 lines: list[str] = [] 

422 lines.append("# 🏛️ AI Jury\n") 

423 

424 # TL;DR callout (issue: scannable headline): hoist the verdict to the very 

425 # top so the outcome is the first thing a reader sees, before the panel and 

426 # the full report. Purely additive — omitted when no verdict is available. 

427 headline = _verdict_headline(synthesis, vote) 

428 if headline: 

429 lines.append(f"> ⚡ **TL;DR · {headline}**\n") 

430 

431 # bolt: Explicit list materialization lets join evaluate iteratively in C 

432 panel = ", ".join([f"`{r.agent}` ({r.vendor})" for r in reviews]) 

433 lines.append(f"**Panel:** {panel}\n") 

434 

435 # Review-scope note (issue #9): only rendered when the caller supplies it 

436 # (incremental mode), so the default report is unchanged. 

437 if review_scope: 

438 lines.append(f"{review_scope}\n") 

439 

440 # Compact, deterministic PR-level classification (issue #7). Derived from the 

441 # structured findings/groups when not supplied explicitly so the section 

442 # always renders for a normal run. 

443 if classification is None: 

444 classification = _classification.classify(findings=findings, groups=groups) 

445 lines.extend(_classification_block(classification)) 

446 

447 if context_mode is not None or redact_secrets is not None: 

448 lines.append("## Context policy\n") 

449 if context_mode is not None: 

450 lines.append(f"- context mode: {context_mode}") 

451 if redact_secrets is not None: 

452 state = "on" if redact_secrets else "off" 

453 extra = f" ({redaction_count} redacted)" if redact_secrets else "" 

454 lines.append(f"- secret redaction: {state}{extra}") 

455 lines.append("") 

456 

457 lines.extend(_excluded_block(excluded_files)) 

458 

459 if groups: 

460 lines.extend(_consensus_block(groups)) 

461 lines.append("---\n") 

462 

463 # Panel-vote verdict (issue #220): when voting, the tally is the headline 

464 # verdict and the chair's synthesis becomes supporting reasoning. 

465 if vote is not None: 

466 lines.extend(_vote_block(vote)) 

467 lines.append("---\n") 

468 

469 if verify is not None: 

470 lines.append("## Verification\n") 

471 lines.append(f"> Verified by `{chair}`\n") 

472 if verify.ok: 

473 lines.append(_defuse_patch_syntax(verify.output).strip() + "\n") 

474 else: 

475 lines.append(f"_Verification failed: {flatten_inline(verify.error)}_\n") 

476 lines.append("---\n") 

477 

478 chair_heading = "Chair's reasoning" if vote is not None else "Chair verdict" 

479 if synthesis and synthesis.ok: 

480 lines.append(f"## {chair_heading}\n") 

481 lines.append(f"> Synthesized by `{chair}`\n") 

482 lines.append(_defuse_patch_syntax(synthesis.output).strip() + "\n") 

483 elif synthesis and not synthesis.ok: 

484 lines.append(f"## {chair_heading}\n") 

485 lines.append(f"_Synthesis failed: {flatten_inline(synthesis.error)}_\n") 

486 

487 lines.append("---\n") 

488 lines.append("## Structured findings\n") 

489 if findings: 

490 # ``f.file``/``f.line`` may be None (a finding need not be located), so 

491 # coerce in the sort key — comparing None against str/int raises TypeError. 

492 ranked = sorted( 

493 findings, 

494 key=lambda f: (SEVERITY_ORDER.get(f.severity, 99), f.file or "", f.line or 0), 

495 ) 

496 for f in ranked: 

497 lines.append(_finding_line(f)) 

498 lines.append("") 

499 else: 

500 lines.append("_(no structured findings parsed)_\n") 

501 

502 if warnings: 

503 lines.append("> ⚠️ agent output warnings\n") 

504 for w in warnings: 

505 lines.append(f"- {w}") 

506 lines.append("") 

507 

508 lines.append("## Round 1 — independent reviews\n") 

509 for r in reviews: 

510 status = f"{r.duration_s:.0f}s" if r.ok else _fail_status(r) 

511 lines.append(_block(f"`{r.agent}` ({r.vendor}) — {status}", r.output if r.ok else "")) 

512 

513 if debate: 

514 lines.append("## Round 2 — cross-examination\n") 

515 for r in debate: 

516 status = f"{r.duration_s:.0f}s" if r.ok else _fail_status(r) 

517 lines.append(_block(f"`{r.agent}` — {status}", r.output if r.ok else "")) 

518 

519 if metadata is not None: 

520 lines.append("---\n") 

521 lines.extend(_metadata_block(metadata)) 

522 

523 if footer: 

524 lines.append(render_footer(reviews)) 

525 return "\n".join(lines) 

526 

527 

528_LIVE_LABELS = { 

529 "review": "Round 1 review", 

530 "debate": "Cross-examination", 

531 "verify": "Verification", 

532 "synthesis": "Decision — verdict & reasoning", 

533} 

534 

535 

536def render_live_step( 

537 kind: str, result: AgentResult, round_no: int | None = None 

538) -> tuple[str, str]: 

539 """Format one streamed step as ``(title, body)`` for live output (issue #210). 

540 

541 Pure — no I/O. The CLI ``--live`` handler prints this to stdout and (with 

542 ``--pr``) posts it as its own comment, as each step completes. ``kind`` is one 

543 of review / debate / verify / synthesis.""" 

544 label = _LIVE_LABELS.get(kind, kind) 

545 if kind == "debate" and round_no: 

546 label = f"Cross-examination · round {round_no}" 

547 if kind in ("verify", "synthesis"): 

548 who = f"chair `{result.agent}`" 

549 else: 

550 who = f"`{result.agent}` ({result.vendor})" 

551 status = f"{result.duration_s:.0f}s" if result.ok else _fail_status(result) 

552 title = f"🏛️ AI Jury — {label}: {who} — {status}" 

553 body = _defuse_patch_syntax(result.output).strip() if result.ok else "" 

554 return title, (body or "_(no output)_") 

555 

556 

557def _conversation_blocks( 

558 reviews: list[AgentResult], 

559 debate: list[AgentResult], 

560 synthesis: AgentResult | None, 

561 verify: AgentResult | None, 

562 *, 

563 chair: str, 

564) -> list[str]: 

565 """The chronological deliberation, foregrounded: each reviewer's raw output, 

566 then the debate exchanges in order, then verification, then the chair's 

567 decision *and its reasoning* — so a reader can follow who said what and why 

568 the chair ruled as it did (issue: full transcript).""" 

569 lines: list[str] = ["## Round 1 — independent reviews\n"] 

570 for r in reviews: 

571 status = f"{r.duration_s:.0f}s" if r.ok else _fail_status(r) 

572 lines.append(_block(f"`{r.agent}` ({r.vendor}) — {status}", r.output if r.ok else "")) 

573 if debate: 

574 lines.append("## Round 2 — cross-examination (debate)\n") 

575 for r in debate: 

576 status = f"{r.duration_s:.0f}s" if r.ok else _fail_status(r) 

577 lines.append(_block(f"`{r.agent}` — {status}", r.output if r.ok else "")) 

578 if verify is not None: 

579 lines.append("## Verification\n") 

580 lines.append(f"> Verified by `{chair}`\n") 

581 lines.append( 

582 _defuse_patch_syntax(verify.output).strip() + "\n" 

583 if verify.ok 

584 else f"_Verification failed: {flatten_inline(verify.error)}_\n" 

585 ) 

586 lines.append("## Decision — verdict & reasoning\n") 

587 if synthesis and synthesis.ok: 

588 lines.append(f"> Decided by `{chair}`\n") 

589 lines.append(_defuse_patch_syntax(synthesis.output).strip() + "\n") 

590 elif synthesis and not synthesis.ok: 

591 lines.append(f"_Synthesis failed: {flatten_inline(synthesis.error)}_\n") 

592 else: 

593 lines.append("_(no synthesis produced)_\n") 

594 return lines 

595 

596 

597def _summary_blocks( 

598 findings: list[Finding], 

599 warnings: list[str], 

600 groups: list, 

601 classification: dict, 

602 vote=None, 

603) -> list[str]: 

604 """Consensus + structured-findings recap (the auditable at-a-glance summary).""" 

605 lines = list(_classification_block(classification)) 

606 if vote is not None: 

607 lines.extend(_vote_block(vote)) 

608 if groups: 

609 lines.extend(_consensus_block(groups)) 

610 lines.append("## Structured findings\n") 

611 if findings: 

612 ranked = sorted( 

613 findings, 

614 key=lambda f: (SEVERITY_ORDER.get(f.severity, 99), f.file or "", f.line or 0), 

615 ) 

616 # bolt: CPython optimization — list comprehension instead of generator expressions in extend() 

617 lines.extend([_finding_line(f) for f in ranked]) 

618 lines.append("") 

619 else: 

620 lines.append("_(no structured findings parsed)_\n") 

621 if warnings: 621 ↛ 622line 621 didn't jump to line 622 because the condition on line 621 was never true

622 lines.append("> ⚠️ agent output warnings\n") 

623 lines.extend([f"- {w}" for w in warnings]) 

624 lines.append("") 

625 return lines 

626 

627 

628def render_transcript( 

629 reviews: list[AgentResult], 

630 debate: list[AgentResult], 

631 synthesis: AgentResult | None, 

632 *, 

633 chair: str, 

634 findings: list[Finding] | None = None, 

635 warnings: list[str] | None = None, 

636 groups: list | None = None, 

637 verify: AgentResult | None = None, 

638 context_mode: str | None = None, 

639 redact_secrets: bool | None = None, 

640 redaction_count: int = 0, 

641 metadata: dict | None = None, 

642 classification: dict | None = None, 

643 review_scope: str | None = None, 

644 lead_with_summary: bool = False, 

645 vote=None, 

646 footer: bool = True, 

647 excluded_files=None, 

648) -> str: 

649 """Render the full play-by-play transcript (issue: full transcript / --verbose). 

650 

651 Two layouts from one function: 

652 

653 * ``lead_with_summary=False`` (``--transcript``) — a dedicated, conversation-first 

654 document: Round 1 → debate → verification → the chair's decision & reasoning, 

655 then a compact consensus/findings recap for auditability. 

656 * ``lead_with_summary=True`` (``--verbose``) — the consensus/verdict summary first, 

657 then the same full transcript below it, in one document. 

658 

659 The default :func:`render` (consensus-first summary with a raw appendix) is 

660 unchanged, so existing reports/goldens are unaffected. 

661 """ 

662 findings = findings or [] 

663 warnings = warnings or [] 

664 groups = groups or [] 

665 if classification is None: 

666 classification = _classification.classify(findings=findings, groups=groups) 

667 

668 lines: list[str] = [] 

669 lines.append( 

670 "# 🏛️ AI Jury — verbose report\n" if lead_with_summary else "# 🏛️ AI Jury — full transcript\n" 

671 ) 

672 # TL;DR callout (parity with render()): the verdict headline leads the 

673 # verbose/transcript report too, so every renderer surfaces the outcome first. 

674 headline = _verdict_headline(synthesis, vote) 

675 if headline: 

676 lines.append(f"> ⚡ **TL;DR · {headline}**\n") 

677 # bolt: explicit list enables optimized string join bypassing generator loop overhead 

678 panel = ", ".join([f"`{r.agent}` ({r.vendor})" for r in reviews]) 

679 lines.append(f"**Panel:** {panel}\n") 

680 if review_scope: 

681 lines.append(f"{review_scope}\n") 

682 

683 # Disclose the context/redaction policy (parity with render()): whoever reads 

684 # the shared transcript should see whether secrets were redacted before the 

685 # diff reached the agents. 

686 if context_mode is not None or redact_secrets is not None: 

687 lines.append("## Context policy\n") 

688 if context_mode is not None: 

689 lines.append(f"- context mode: {context_mode}") 

690 if redact_secrets is not None: 

691 state = "on" if redact_secrets else "off" 

692 extra = f" ({redaction_count} redacted)" if redact_secrets else "" 

693 lines.append(f"- secret redaction: {state}{extra}") 

694 lines.append("") 

695 

696 lines.extend(_excluded_block(excluded_files)) 

697 

698 if lead_with_summary: 

699 lines.extend(_summary_blocks(findings, warnings, groups, classification, vote=vote)) 

700 lines.append("---\n") 

701 lines.append("# Full transcript\n") 

702 lines.extend(_conversation_blocks(reviews, debate, synthesis, verify, chair=chair)) 

703 else: 

704 lines.extend(_conversation_blocks(reviews, debate, synthesis, verify, chair=chair)) 

705 lines.append("---\n") 

706 lines.extend(_summary_blocks(findings, warnings, groups, classification, vote=vote)) 

707 

708 if metadata is not None: 

709 lines.append("---\n") 

710 lines.extend(_metadata_block(metadata)) 

711 

712 if footer: 

713 lines.append(render_footer(reviews, transcript=True)) 

714 return "\n".join(lines) 

715 

716 

717def render_sections( 

718 reviews: list[AgentResult], 

719 debate: list[AgentResult], 

720 synthesis: AgentResult | None, 

721 *, 

722 chair: str, 

723 findings: list[Finding] | None = None, 

724 warnings: list[str] | None = None, 

725 groups: list | None = None, 

726 verify: AgentResult | None = None, 

727 classification: dict | None = None, 

728 vote=None, 

729) -> list[tuple[str, str]]: 

730 """Split the report into ordered ``(title, body)`` sections for phased posting. 

731 

732 Returns up to three sections — **Round 1** (independent reviews), **Round 2** 

733 (debate, omitted when there was none), and **Decision** (verification + chair 

734 verdict + consensus + structured findings) — so a PR can show the flow as 

735 separate, readable comments (issue #127). ``render()`` (the single-blob 

736 report) is unchanged. Empty sections are skipped. 

737 """ 

738 findings = findings or [] 

739 warnings = warnings or [] 

740 groups = groups or [] 

741 sections: list[tuple[str, str]] = [] 

742 

743 # Round 1 — independent reviews. 

744 # bolt: Explicitly evaluating as a list allows C-level optimizations in join 

745 r1 = [f"**Panel:** {', '.join([f'`{r.agent}` ({r.vendor})' for r in reviews])}\n"] 

746 for r in reviews: 

747 status = f"{r.duration_s:.0f}s" if r.ok else _fail_status(r) 

748 r1.append(_block(f"`{r.agent}` ({r.vendor}) — {status}", r.output if r.ok else "")) 

749 sections.append(("🏛️ AI Jury — Round 1: independent reviews", "\n".join(r1).strip())) 

750 

751 # Round 2 — cross-examination (only if a debate ran). 

752 if debate: 

753 r2 = [] 

754 for r in debate: 

755 status = f"{r.duration_s:.0f}s" if r.ok else _fail_status(r) 

756 r2.append(_block(f"`{r.agent}` — {status}", r.output if r.ok else "")) 

757 sections.append(("🏛️ AI Jury — Round 2: cross-examination (debate)", "\n".join(r2).strip())) 

758 

759 # Decision — verification + chair verdict + consensus + findings. 

760 dec: list[str] = [] 

761 if classification is None: 

762 classification = _classification.classify(findings=findings, groups=groups) 

763 dec.extend(_classification_block(classification)) 

764 if vote is not None: 

765 dec.extend(_vote_block(vote)) 

766 if groups: 

767 dec.extend(_consensus_block(groups)) 

768 if verify is not None: 

769 dec.append("## Verification\n") 

770 dec.append(f"> Verified by `{chair}`\n") 

771 dec.append( 

772 _defuse_patch_syntax(verify.output).strip() + "\n" 

773 if verify.ok 

774 else f"_Verification failed: {flatten_inline(verify.error)}_\n" 

775 ) 

776 chair_heading = "Chair's reasoning" if vote is not None else "Chair verdict" 

777 if synthesis and synthesis.ok: 

778 dec.append(f"## {chair_heading}\n") 

779 dec.append(f"> Synthesized by `{chair}`\n") 

780 dec.append(_defuse_patch_syntax(synthesis.output).strip() + "\n") 

781 elif synthesis and not synthesis.ok: 

782 dec.append(f"## {chair_heading}\n\n_Synthesis failed: {flatten_inline(synthesis.error)}_\n") 

783 if findings: 

784 dec.append("## Structured findings\n") 

785 ranked = sorted( 

786 findings, 

787 key=lambda f: (SEVERITY_ORDER.get(f.severity, 99), f.file or "", f.line or 0), 

788 ) 

789 # bolt: Optimizes speed by allowing Python C implementations of extend() 

790 dec.extend([_finding_line(f) for f in ranked]) 

791 if warnings: 

792 dec.append("\n> ⚠️ agent output warnings\n") 

793 dec.extend([f"- {w}" for w in warnings]) 

794 sections.append(("🏛️ AI Jury — Decision: verdict & consensus", "\n".join(dec).strip())) 

795 

796 return sections