agent-blackbox-cli 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. agent_blackbox_cli-0.3.0.dist-info/METADATA +623 -0
  2. agent_blackbox_cli-0.3.0.dist-info/RECORD +43 -0
  3. agent_blackbox_cli-0.3.0.dist-info/WHEEL +5 -0
  4. agent_blackbox_cli-0.3.0.dist-info/entry_points.txt +2 -0
  5. agent_blackbox_cli-0.3.0.dist-info/licenses/LICENSE +21 -0
  6. agent_blackbox_cli-0.3.0.dist-info/top_level.txt +1 -0
  7. blackbox/__init__.py +61 -0
  8. blackbox/__main__.py +6 -0
  9. blackbox/adapters/__init__.py +0 -0
  10. blackbox/adapters/_linking.py +31 -0
  11. blackbox/adapters/base.py +38 -0
  12. blackbox/adapters/claude_code.py +341 -0
  13. blackbox/adapters/codex.py +318 -0
  14. blackbox/adapters/labelled_turns.py +371 -0
  15. blackbox/adapters/registry.py +30 -0
  16. blackbox/aggregate.py +119 -0
  17. blackbox/analysis.py +325 -0
  18. blackbox/bench.py +466 -0
  19. blackbox/cli.py +405 -0
  20. blackbox/cost.py +138 -0
  21. blackbox/describe.py +116 -0
  22. blackbox/detectors/__init__.py +32 -0
  23. blackbox/detectors/base.py +83 -0
  24. blackbox/detectors/context_bloat.py +137 -0
  25. blackbox/detectors/contradictions.py +180 -0
  26. blackbox/detectors/error_clusters.py +114 -0
  27. blackbox/detectors/retry_loops.py +98 -0
  28. blackbox/detectors/stalls.py +117 -0
  29. blackbox/detectors/thrash.py +86 -0
  30. blackbox/diff.py +123 -0
  31. blackbox/discover.py +189 -0
  32. blackbox/events.py +163 -0
  33. blackbox/graph.py +150 -0
  34. blackbox/guard.py +528 -0
  35. blackbox/guard_cli.py +349 -0
  36. blackbox/pricing.py +137 -0
  37. blackbox/py.typed +0 -0
  38. blackbox/replay.py +65 -0
  39. blackbox/report/__init__.py +0 -0
  40. blackbox/report/html.py +375 -0
  41. blackbox/report/text.py +287 -0
  42. blackbox/store.py +215 -0
  43. blackbox/toolinfo.py +336 -0
@@ -0,0 +1,375 @@
1
+ """Self-contained HTML report.
2
+
3
+ One file, no dependencies, no network requests -- so it can be committed to a
4
+ repo, attached to a ticket, or opened from a USB stick in five years and still
5
+ render. Every number on the page comes from the canonical payload, so the page
6
+ and the JSON output can never disagree.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import html
12
+ import json
13
+
14
+ from blackbox.analysis import Analysis
15
+ from blackbox.describe import describe
16
+ from blackbox.detectors.base import HIGH, LOW, MEDIUM
17
+
18
+ _CSS = """
19
+ :root {
20
+ color-scheme: light dark;
21
+ --bg: #fbfbfa;
22
+ --panel: #ffffff;
23
+ --border: #e4e2dd;
24
+ --ink: #1b1a18;
25
+ --muted: #6c6862;
26
+ --accent: #2f6f4f;
27
+ --high: #b4452f;
28
+ --med: #b07d26;
29
+ --low: #5a7a8c;
30
+ --bar: #cfd8d2;
31
+ --mono: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
32
+ }
33
+ @media (prefers-color-scheme: dark) {
34
+ :root:not([data-theme="light"]) {
35
+ --bg: #17181a;
36
+ --panel: #1e2023;
37
+ --border: #32353a;
38
+ --ink: #e8e6e3;
39
+ --muted: #9b968e;
40
+ --accent: #7fc4a0;
41
+ --high: #e8836a;
42
+ --med: #e0b457;
43
+ --low: #92b4c8;
44
+ --bar: #3a4047;
45
+ }
46
+ }
47
+ :root[data-theme="dark"] {
48
+ --bg: #17181a;
49
+ --panel: #1e2023;
50
+ --border: #32353a;
51
+ --ink: #e8e6e3;
52
+ --muted: #9b968e;
53
+ --accent: #7fc4a0;
54
+ --high: #e8836a;
55
+ --med: #e0b457;
56
+ --low: #92b4c8;
57
+ --bar: #3a4047;
58
+ }
59
+ * { box-sizing: border-box; }
60
+ body {
61
+ margin: 0; padding: 0 16px 72px;
62
+ background: var(--bg); color: var(--ink);
63
+ font: 15px/1.6 ui-sans-serif, -apple-system, "Segoe UI", Roboto, sans-serif;
64
+ }
65
+ .wrap { max-width: 980px; margin: 0 auto; }
66
+ header { padding: 40px 0 24px; border-bottom: 1px solid var(--border); }
67
+ h1 { margin: 0 0 6px; font-size: 25px; letter-spacing: -0.015em; font-weight: 650; }
68
+ .sub { color: var(--muted); font-family: var(--mono); font-size: 12.5px; word-break: break-all; }
69
+ h2 {
70
+ margin: 40px 0 14px; font-size: 12px; font-weight: 650;
71
+ text-transform: uppercase; letter-spacing: 0.1em; color: var(--muted);
72
+ }
73
+ .tiles { display: flex; flex-wrap: wrap; gap: 10px; margin-top: 22px; }
74
+ .tile {
75
+ flex: 1 1 128px; background: var(--panel); border: 1px solid var(--border);
76
+ border-radius: 9px; padding: 13px 15px;
77
+ }
78
+ .tile .v { font-size: 22px; font-weight: 640; font-family: var(--mono); letter-spacing: -0.02em; }
79
+ .tile .k { font-size: 11px; color: var(--muted); text-transform: uppercase; letter-spacing: 0.07em; margin-top: 3px; }
80
+ .panel {
81
+ background: var(--panel); border: 1px solid var(--border);
82
+ border-radius: 9px; padding: 4px 16px; margin-bottom: 12px;
83
+ }
84
+ table { width: 100%; border-collapse: collapse; font-family: var(--mono); font-size: 12.5px; }
85
+ th {
86
+ text-align: right; padding: 11px 7px; color: var(--muted); font-weight: 500;
87
+ border-bottom: 1px solid var(--border); font-size: 11px;
88
+ text-transform: uppercase; letter-spacing: 0.05em; white-space: nowrap;
89
+ }
90
+ th:first-child, td:first-child { text-align: left; }
91
+ td { padding: 9px 7px; text-align: right; border-bottom: 1px solid var(--border); }
92
+ tr:last-child td { border-bottom: none; }
93
+ .tag {
94
+ display: inline-block; font-size: 10px; padding: 1px 6px; border-radius: 4px;
95
+ border: 1px solid var(--border); color: var(--muted); margin-left: 6px;
96
+ font-family: var(--mono); text-transform: uppercase; letter-spacing: 0.04em;
97
+ }
98
+ .split { display: flex; height: 9px; border-radius: 5px; overflow: hidden; margin: 6px 0 2px; background: var(--bar); }
99
+ .split span { display: block; height: 100%; }
100
+ .legend { display: flex; flex-wrap: wrap; gap: 14px; font-size: 11.5px; color: var(--muted); font-family: var(--mono); margin-bottom: 14px; }
101
+ .legend i { display: inline-block; width: 9px; height: 9px; border-radius: 2px; margin-right: 5px; vertical-align: -1px; }
102
+ .bars { font-family: var(--mono); font-size: 12.5px; }
103
+ .bars .row { display: flex; align-items: center; gap: 10px; padding: 4px 0; }
104
+ .bars .lbl { flex: 0 0 180px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
105
+ .bars .track { flex: 1; background: var(--bar); border-radius: 4px; height: 11px; }
106
+ .bars .fill { background: var(--accent); height: 100%; border-radius: 4px; }
107
+ .bars .num { flex: 0 0 52px; text-align: right; color: var(--muted); }
108
+ .finding { border-left: 3px solid var(--border); padding: 12px 0 12px 14px; margin: 0 0 4px; border-bottom: 1px solid var(--border); }
109
+ .finding:last-child { border-bottom: none; }
110
+ .finding.high { border-left-color: var(--high); }
111
+ .finding.medium { border-left-color: var(--med); }
112
+ .finding.low { border-left-color: var(--low); }
113
+ .finding .ttl { font-weight: 600; font-size: 14px; }
114
+ .finding .meta { font-family: var(--mono); font-size: 11px; color: var(--muted); margin-top: 3px; }
115
+ .finding .det { color: var(--muted); font-size: 13.5px; margin-top: 7px; }
116
+ .sev { font-family: var(--mono); font-size: 10px; text-transform: uppercase; letter-spacing: 0.08em; font-weight: 700; }
117
+ .sev.high { color: var(--high); } .sev.medium { color: var(--med); } .sev.low { color: var(--low); }
118
+ details.ev { margin-top: 8px; }
119
+ details.ev summary { cursor: pointer; font-family: var(--mono); font-size: 11px; color: var(--muted); }
120
+ details.ev pre {
121
+ margin: 8px 0 0; padding: 10px; background: var(--bg); border: 1px solid var(--border);
122
+ border-radius: 6px; font-size: 11px; overflow-x: auto; color: var(--muted);
123
+ }
124
+ .note { color: var(--muted); font-size: 12.5px; margin: 10px 0 0; }
125
+ .ok { color: var(--accent); }
126
+ footer {
127
+ margin-top: 48px; padding-top: 18px; border-top: 1px solid var(--border);
128
+ color: var(--muted); font-family: var(--mono); font-size: 11.5px; line-height: 1.8;
129
+ }
130
+ @media (max-width: 620px) {
131
+ .bars .lbl { flex-basis: 108px; }
132
+ th, td { padding: 8px 4px; font-size: 11.5px; }
133
+ .tile { flex-basis: 100%; }
134
+ }
135
+ """
136
+
137
+ _TIER_COLORS = {
138
+ "output": "var(--high)",
139
+ "cache writes": "var(--med)",
140
+ "fresh input": "var(--accent)",
141
+ "cache reads": "var(--low)",
142
+ }
143
+
144
+
145
+ def _esc(value) -> str:
146
+ return html.escape(str(value), quote=True)
147
+
148
+
149
+ def _n(value: int) -> str:
150
+ return f"{value:,}"
151
+
152
+
153
+ def _usd(value: float) -> str:
154
+ """Never render real spend as $0.00."""
155
+ if value and abs(value) < 0.01:
156
+ return f"{value:.4f}"
157
+ return f"{value:,.2f}"
158
+
159
+
160
+ def _dur(seconds: float) -> str:
161
+ if seconds < 90:
162
+ return f"{seconds:.0f}s"
163
+ if seconds < 5400:
164
+ return f"{seconds / 60:.0f}min"
165
+ return f"{seconds / 3600:.1f}h"
166
+
167
+
168
+ def _spend_by_tier(analysis: Analysis) -> list[tuple[str, float]]:
169
+ c = analysis.cost
170
+ fresh = sum(mc.input_usd for mc in c.by_model)
171
+ out = sum(mc.output_usd for mc in c.by_model)
172
+ reads = sum(mc.cache_read_usd for mc in c.by_model)
173
+ writes = sum(mc.cache_write_usd for mc in c.by_model)
174
+ return [
175
+ ("output", out),
176
+ ("cache writes", writes),
177
+ ("fresh input", fresh),
178
+ ("cache reads", reads),
179
+ ]
180
+
181
+
182
+ def render(analysis: Analysis) -> str:
183
+ s = analysis.summary()
184
+ c = analysis.cost
185
+ p = analysis.payload()
186
+
187
+ counts = {HIGH: 0, MEDIUM: 0, LOW: 0}
188
+ for f in analysis.findings:
189
+ counts[f.severity] = counts.get(f.severity, 0) + 1
190
+
191
+ parts: list[str] = []
192
+ add = parts.append
193
+
194
+ add("<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\">")
195
+ add('<meta name="viewport" content="width=device-width, initial-scale=1">')
196
+ add(f"<title>Black Box — {_esc(p['source'])}</title>")
197
+ add(f"<style>{_CSS}</style></head><body><div class=\"wrap\">")
198
+
199
+ # --- header -----------------------------------------------------------
200
+ add("<header>")
201
+ add("<h1>Agent Black Box</h1>")
202
+ add(
203
+ f'<div class="sub">{_esc(p["source"])} · adapter {_esc(analysis.trace.adapter)}'
204
+ + (f' · {_esc(analysis.trace.meta.get("git_branch"))}' if analysis.trace.meta.get("git_branch") else "")
205
+ + "</div>"
206
+ )
207
+ cost_label = f"${c.total_usd:,.2f}" + ("" if c.is_complete else "+")
208
+ add('<div class="tiles">')
209
+ for value, key in (
210
+ (cost_label, "cost"),
211
+ (_n(s["tool_calls"]), "tool calls"),
212
+ (_n(s["tool_failures"]), "failed"),
213
+ (_dur(s["active_seconds"]), "active time"),
214
+ (str(len(analysis.findings)), "findings"),
215
+ ):
216
+ add(f'<div class="tile"><div class="v">{_esc(value)}</div><div class="k">{_esc(key)}</div></div>')
217
+ add("</div></header>")
218
+
219
+ # --- cost -------------------------------------------------------------
220
+ add("<h2>Cost</h2><div class=\"panel\">")
221
+ tiers = [(name, usd) for name, usd in _spend_by_tier(analysis) if usd > 0]
222
+ tier_total = sum(usd for _, usd in tiers)
223
+ if tier_total > 0:
224
+ add('<div class="split">')
225
+ for name, usd in tiers:
226
+ pct = usd / tier_total * 100
227
+ add(f'<span style="width:{pct:.3f}%;background:{_TIER_COLORS[name]}" title="{_esc(name)}"></span>')
228
+ add("</div>")
229
+ add('<div class="legend">')
230
+ for name, usd in tiers:
231
+ add(
232
+ f'<span><i style="background:{_TIER_COLORS[name]}"></i>{_esc(name)} '
233
+ f"${usd:,.2f} ({usd / tier_total * 100:.0f}%)</span>"
234
+ )
235
+ add("</div>")
236
+
237
+ add("<table><thead><tr><th>model</th><th>msgs</th><th>output</th>")
238
+ add("<th>cache read</th><th>5m writes</th><th>1h writes</th><th>usd</th></tr></thead><tbody>")
239
+ for mc in c.by_model:
240
+ tag = "" if mc.priced else '<span class="tag">unpriced</span>'
241
+ add(
242
+ f"<tr><td>{_esc(mc.model)}{tag}</td><td>{_n(mc.calls)}</td>"
243
+ f"<td>{_n(mc.usage.output_tokens)}</td><td>{_n(mc.usage.cache_read_tokens)}</td>"
244
+ f"<td>{_n(mc.usage.cache_write_5m_tokens)}</td>"
245
+ f"<td>{_n(mc.usage.cache_write_1h_tokens)}</td>"
246
+ f"<td>{_usd(mc.total_usd)}</td></tr>"
247
+ )
248
+ add("</tbody></table>")
249
+
250
+ share = c.cache_write_1h_usd_share
251
+ if share > 0:
252
+ tail = (
253
+ " Rebuilding a long 1-hour-cached prefix is the most common way a run "
254
+ "costs more than its token count suggests."
255
+ if share >= 0.25
256
+ else ""
257
+ )
258
+ add(f'<p class="note"><strong>{share * 100:.1f}%</strong> of spend was 1-hour cache writes.{tail}</p>')
259
+ if not c.is_complete:
260
+ add(
261
+ f'<p class="note">{_n(c.unpriced_tokens)} tokens ran on models missing from the '
262
+ f"price table ({_esc(', '.join(c.unpriced_models))}), so the total is a floor, "
263
+ f"not a figure.</p>"
264
+ )
265
+
266
+ waste = analysis.wasted()
267
+ if waste["usd"] > 0:
268
+ add(
269
+ f'<p class="note"><strong>At least ${waste["usd"]:,.2f} '
270
+ f'({waste["share_of_run"] * 100:.1f}%)</strong> of this run went to work that did '
271
+ f"not advance the task — "
272
+ + _esc(
273
+ ", ".join(
274
+ f"{name.replace('_', ' ')} ${value:,.2f}"
275
+ for name, value in sorted(waste["by_detector"].items(), key=lambda kv: -kv[1])
276
+ )
277
+ )
278
+ + ". This is a floor: it counts the turns that issued these calls, not the "
279
+ "cost of carrying their results in context afterwards.</p>"
280
+ )
281
+ add("</div>")
282
+
283
+ # --- branches ---------------------------------------------------------
284
+ if len(s["branches"]) > 1:
285
+ add("<h2>Branches</h2><div class=\"panel\"><table><thead><tr>")
286
+ add("<th>branch</th><th>events</th><th>tool calls</th><th>usd</th></tr></thead><tbody>")
287
+ for b in s["branches"]:
288
+ usd = c.by_branch.get(b["name"], 0.0)
289
+ add(
290
+ f'<tr><td>{_esc(b["name"])}</td><td>{_n(b["events"])}</td>'
291
+ f'<td>{_n(b["tool_calls"])}</td><td>{_usd(usd)}</td></tr>'
292
+ )
293
+ add("</tbody></table>")
294
+ add(
295
+ '<p class="note">Subagent work is attributed to its own branch, so the main '
296
+ "thread's cost is the main thread's alone.</p></div>"
297
+ )
298
+
299
+ # --- tools ------------------------------------------------------------
300
+ if s["tools"]:
301
+ top = s["tools"][:12]
302
+ peak = max(e["calls"] for e in top)
303
+ add('<h2>Tools</h2><div class="panel"><div class="bars">')
304
+ for entry in top:
305
+ pct = entry["calls"] / peak * 100
306
+ add(
307
+ f'<div class="row"><div class="lbl">{_esc(entry["tool"])}</div>'
308
+ f'<div class="track"><div class="fill" style="width:{pct:.2f}%"></div></div>'
309
+ f'<div class="num">{entry["calls"]}</div></div>'
310
+ )
311
+ add("</div></div>")
312
+
313
+ # --- findings ---------------------------------------------------------
314
+ add(
315
+ f"<h2>Findings — {len(analysis.findings)} "
316
+ f"({counts[HIGH]} high, {counts[MEDIUM]} medium, {counts[LOW]} low)</h2>"
317
+ )
318
+ add('<div class="panel">')
319
+ if not analysis.findings:
320
+ add('<p class="note ok">Nothing tripped a detector.</p>')
321
+ for f in analysis.findings:
322
+ branch = "" if f.branch == "main" else f'<span class="tag">{_esc(f.branch)}</span>'
323
+ add(f'<div class="finding {_esc(f.severity)}">')
324
+ add(f'<div class="ttl">{_esc(f.title)}{branch}</div>')
325
+ usd = analysis.finding_usd(f)
326
+ price = f" · ${_usd(usd)}" if usd > 0 else ""
327
+ add(
328
+ f'<div class="meta"><span class="sev {_esc(f.severity)}">{_esc(f.severity)}</span>'
329
+ f" · {_esc(f.detector)}{_esc(price)}</div>"
330
+ )
331
+ add(f'<div class="det">{_esc(f.detail)}</div>')
332
+
333
+ lines = []
334
+ for uid in f.evidence[:12]:
335
+ event = analysis.graph.by_uid.get(uid)
336
+ if event is None:
337
+ continue
338
+ lines.append(f"step {event.seq:>5} line {event.source_line:>6} {describe(event)}")
339
+ more = len(f.evidence) - len(lines)
340
+ if more > 0:
341
+ lines.append(f"... and {more} more")
342
+ metrics = json.dumps({k: f.metrics[k] for k in sorted(f.metrics)}, indent=2, default=str)
343
+ add(
344
+ '<details class="ev"><summary>evidence &amp; metrics</summary><pre>'
345
+ + _esc("\n".join(lines))
346
+ + "\n\n"
347
+ + _esc(metrics)
348
+ + "</pre></details>"
349
+ )
350
+ add("</div>")
351
+ add("</div>")
352
+
353
+ # --- footer -----------------------------------------------------------
354
+ cfg = analysis.config
355
+ add("<footer>")
356
+ add(f"payload digest {_esc(analysis.digest())}<br>")
357
+ add(
358
+ f"thresholds: stall &ge; {cfg.stall_seconds:.0f}s · idle &ge; {cfg.idle_seconds:.0f}s · "
359
+ f"retry &ge; {cfg.retry_min_repeats} in {cfg.retry_window} calls · "
360
+ f"thrash &ge; {cfg.thrash_min_edits} writes<br>"
361
+ )
362
+ add(f"prices as of {_esc(c.pricing_as_of)} · last event {_esc(s['last_ts'] or 'unknown')}<br>")
363
+ add(
364
+ "every number above was derived without a model call, and replays byte-identical "
365
+ "from the stored events"
366
+ )
367
+ if s["orphan_events"]:
368
+ add(
369
+ f"<br>{_n(s['orphan_events'])} events reference a parent outside this file "
370
+ f"(resumed or forked session)"
371
+ )
372
+ add("</footer>")
373
+
374
+ add("</div></body></html>")
375
+ return "".join(parts)
@@ -0,0 +1,287 @@
1
+ """Terminal report."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from blackbox.analysis import Analysis
6
+ from blackbox.describe import describe
7
+ from blackbox.detectors.base import HIGH, LOW, MEDIUM
8
+
9
+ _BADGE = {HIGH: "HIGH", MEDIUM: "MED ", LOW: "LOW "}
10
+
11
+
12
+ def _n(value: int) -> str:
13
+ return f"{value:,}"
14
+
15
+
16
+ def _tail(text: str, width: int) -> str:
17
+ """Keep the end of a long path, marking what was dropped."""
18
+ return text if len(text) <= width else "…" + text[-(width - 1):]
19
+
20
+
21
+ def _usd(value: float) -> str:
22
+ """Never render real spend as $0.00 -- a cost tool that hides cost is useless."""
23
+ if value and abs(value) < 0.01:
24
+ return f"{value:.4f}"
25
+ return f"{value:,.2f}"
26
+
27
+
28
+ def _dur(seconds: float) -> str:
29
+ if seconds < 90:
30
+ return f"{seconds:.0f}s"
31
+ if seconds < 5400:
32
+ return f"{seconds / 60:.1f}min"
33
+ return f"{seconds / 3600:.1f}h"
34
+
35
+
36
+ def render(analysis: Analysis, max_findings: int | None = 25) -> str:
37
+ s = analysis.summary()
38
+ c = analysis.cost
39
+ out: list[str] = []
40
+ add = out.append
41
+
42
+ add("")
43
+ add(f"AGENT BLACK BOX {s['events']} events from {analysis.trace.source.split('/')[-1]}")
44
+ add(
45
+ f" adapter {analysis.trace.adapter} · {_n(s['tool_calls'])} tool calls · "
46
+ f"{s['tool_failures']} failed · {_dur(s['active_seconds'])} active "
47
+ f"over {_dur(s['span_seconds'])}"
48
+ )
49
+ extra = []
50
+ if s.get("human_wait_seconds"):
51
+ extra.append(f"{_dur(s['human_wait_seconds'])} waiting on you")
52
+ if s.get("declined_calls"):
53
+ extra.append(f"{s['declined_calls']} call(s) you declined")
54
+ if extra:
55
+ add(" " + " · ".join(extra))
56
+ if s["subagent_branches"]:
57
+ add(f" {s['subagent_branches']} subagent branch(es) separated from the main thread")
58
+ if s["orphan_events"]:
59
+ add(
60
+ f" note: {s['orphan_events']} events reference a parent outside this file "
61
+ f"(resumed or forked session)"
62
+ )
63
+ if analysis.trace.skipped_lines:
64
+ add(f" note: {analysis.trace.skipped_lines} unparseable line(s) skipped")
65
+ add("")
66
+
67
+ # --- cost -------------------------------------------------------------
68
+ marker = "" if c.is_complete else " (at least — some tokens unpriced)"
69
+ add(f"COST ${c.total_usd:,.2f}{marker} rates as of {c.pricing_as_of}")
70
+ add(
71
+ f" {'model':<22}{'msgs':>7}{'output':>11}{'cache read':>13}"
72
+ f"{'1h writes':>12}{'usd':>11}"
73
+ )
74
+ for mc in c.by_model:
75
+ flag = "" if mc.priced else " [unpriced]"
76
+ add(
77
+ f" {mc.model:<22}{mc.calls:>7}{_n(mc.usage.output_tokens):>11}"
78
+ f"{_n(mc.usage.cache_read_tokens):>13}{_n(mc.usage.cache_write_1h_tokens):>12}"
79
+ f"{_usd(mc.total_usd):>11}{flag}"
80
+ )
81
+ share = c.cache_write_1h_usd_share
82
+ if share > 0:
83
+ note = " <- rebuilding a long cached prefix is where this run's money went" if share >= 0.25 else ""
84
+ add(f" {share * 100:.1f}% of spend was 1-hour cache writes{note}")
85
+ if not c.is_complete:
86
+ add(
87
+ f" unpriced: {', '.join(c.unpriced_models)} "
88
+ f"({_n(c.unpriced_tokens)} tokens not in the price table)"
89
+ )
90
+
91
+ waste = analysis.wasted()
92
+ if waste["usd"] > 0:
93
+ parts = ", ".join(
94
+ f"{name.replace('_', ' ')} ${value:,.2f}"
95
+ for name, value in sorted(waste["by_detector"].items(), key=lambda kv: -kv[1])
96
+ )
97
+ add(
98
+ f" at least ${waste['usd']:,.2f} ({waste['share_of_run'] * 100:.1f}%) went to work "
99
+ f"that did not advance the task"
100
+ )
101
+ add(f" {parts}")
102
+ add(" a floor: it counts the turns that issued these calls, not the context they left behind")
103
+ add("")
104
+
105
+ if len(c.by_branch) > 1:
106
+ add("SPEND BY BRANCH")
107
+ for name, usd in sorted(c.by_branch.items(), key=lambda kv: (-kv[1], kv[0])):
108
+ branch = analysis.graph.branch_named(name)
109
+ calls = branch.tool_calls if branch else 0
110
+ add(f" {name:<16}${_usd(usd):>10} {calls} tool calls")
111
+ add("")
112
+
113
+ if s["tools"]:
114
+ add("TOOLS")
115
+ line = " "
116
+ for entry in s["tools"][:14]:
117
+ chunk = f"{entry['tool']} {entry['calls']} "
118
+ if len(line) + len(chunk) > 96:
119
+ add(line.rstrip())
120
+ line = " "
121
+ line += chunk
122
+ add(line.rstrip())
123
+ add("")
124
+
125
+ # --- findings ---------------------------------------------------------
126
+ counts = {HIGH: 0, MEDIUM: 0, LOW: 0}
127
+ for f in analysis.findings:
128
+ counts[f.severity] = counts.get(f.severity, 0) + 1
129
+ add(
130
+ f"FINDINGS {len(analysis.findings)} total "
131
+ f"({counts[HIGH]} high, {counts[MEDIUM]} medium, {counts[LOW]} low)"
132
+ )
133
+ if not analysis.findings:
134
+ add(" nothing tripped a detector.")
135
+ shown = analysis.findings if max_findings is None else analysis.findings[:max_findings]
136
+ for f in shown:
137
+ branch = "" if f.branch == "main" else f" [{f.branch}]"
138
+ usd = analysis.finding_usd(f)
139
+ price = f" ${_usd(usd)}" if usd > 0 else ""
140
+ add(f" [{_BADGE.get(f.severity, '?')}] {f.detector:<14} {f.title}{branch}{price}")
141
+ add(f" {f.detail}")
142
+ for ev_uid in f.evidence[:2]:
143
+ event = analysis.graph.by_uid.get(ev_uid)
144
+ if event is not None:
145
+ add(f" · step {event.seq} line {event.source_line} {describe(event)}")
146
+ remaining = len(analysis.findings) - len(shown)
147
+ if remaining > 0:
148
+ add(f" ... {remaining} more (use --max-findings all)")
149
+ add("")
150
+ add(f" payload digest {analysis.digest()[:16]} · detectors ran with no model calls")
151
+ add("")
152
+ return "\n".join(out)
153
+
154
+
155
+ # --- corpus ---------------------------------------------------------------
156
+
157
+
158
+ def render_corpus(corpus, title: str = "ACROSS ALL RUNS") -> str:
159
+ """Summary across many traces."""
160
+ s = corpus.summary()
161
+ out: list[str] = []
162
+ add = out.append
163
+
164
+ add("")
165
+ add(f"AGENT BLACK BOX {title}")
166
+ add(
167
+ f" {s['runs']} run(s) · {_n(s['tool_calls'])} tool calls · "
168
+ f"{_n(s['findings'])} findings · {_dur(s['active_seconds'])} active"
169
+ )
170
+ if s["unreadable"]:
171
+ add(f" note: {s['unreadable']} file(s) could not be read")
172
+ add("")
173
+
174
+ add(f"SPEND ${s['total_usd']:,.2f} across {s['runs']} run(s)")
175
+ if s["wasted_usd"] > 0:
176
+ add(
177
+ f" at least ${s['wasted_usd']:,.2f} ({s['wasted_share'] * 100:.1f}%) on work "
178
+ f"that did not advance the task"
179
+ )
180
+ add(
181
+ f" cache hit rate {s['cache_hit_rate'] * 100:.1f}% of billed input · "
182
+ f"{_n(s['cache_write_1h_tokens'])} tokens of 1-hour cache writes"
183
+ )
184
+ add(f" tool failure rate {s['failure_rate'] * 100:.1f}% ({_n(s['tool_failures'])} failed)")
185
+ add("")
186
+
187
+ if s["by_detector"]:
188
+ add("FINDINGS BY TYPE")
189
+ for name in sorted(s["by_detector"], key=lambda k: -s["by_detector"][k]):
190
+ usd = s["usd_by_detector"].get(name, 0.0)
191
+ money = f" ${_usd(usd)}" if usd > 0 else ""
192
+ add(f" {name:<16}{s['by_detector'][name]:>5}{money}")
193
+ add("")
194
+
195
+ if s["top_thrashed"]:
196
+ add("MOST REWRITTEN FILES")
197
+ for entry in s["top_thrashed"][:6]:
198
+ add(f" {entry['writes']:>3}x {_tail(entry['path'], 72)}")
199
+ add("")
200
+
201
+ if s["worst_loops"]:
202
+ add("WORST RETRY LOOPS")
203
+ for entry in s["worst_loops"][:5]:
204
+ add(f" {entry['repeats']:>3}x {entry['tool'][:40]:<40} {entry['run'][:20]}")
205
+ add("")
206
+
207
+ if s["worst_bloat"]:
208
+ add("MOST EXPENSIVE CONTEXT ADDITIONS (estimated)")
209
+ for entry in s["worst_bloat"][:5]:
210
+ add(
211
+ f" ~${entry['est_usd']:>8,.2f} {_n(entry['est_tokens']):>9} tok "
212
+ f"{entry['tool'][:30]:<30} {entry['run'][:18]}"
213
+ )
214
+ add("")
215
+
216
+ return "\n".join(out)
217
+
218
+
219
+ # --- diff -----------------------------------------------------------------
220
+
221
+
222
+ def _fmt(value: float, unit: str) -> str:
223
+ if unit == "usd":
224
+ return f"${_usd(value)}"
225
+ if unit == "rate":
226
+ return f"{value * 100:.1f}%"
227
+ if unit == "duration":
228
+ return _dur(value)
229
+ return f"{value:,.0f}" if abs(value - round(value)) < 0.05 else f"{value:,.1f}"
230
+
231
+
232
+ def _delta(value: float, unit: str) -> str:
233
+ sign = "+" if value > 0 else ""
234
+ if unit == "rate":
235
+ return f"{sign}{value * 100:.1f}pp"
236
+ if unit == "usd":
237
+ return f"{sign}${_usd(abs(value))}" if value >= 0 else f"-${_usd(abs(value))}"
238
+ if unit == "duration":
239
+ return f"{sign}{_dur(abs(value))}"
240
+ return f"{sign}{value:,.0f}" if abs(value - round(value)) < 0.05 else f"{sign}{value:,.1f}"
241
+
242
+
243
+ def render_diff(result: dict, before_label: str, after_label: str) -> str:
244
+ out: list[str] = []
245
+ add = out.append
246
+
247
+ add("")
248
+ add("AGENT BLACK BOX diff")
249
+ add(f" before {before_label} ({result['runs']['before']} run(s))")
250
+ add(f" after {after_label} ({result['runs']['after']} run(s))")
251
+ if result["uneven"]:
252
+ add(" run counts differ, so totals are also shown per run and the verdict follows those")
253
+ add("")
254
+
255
+ header = f" {'':<20}{'before':>12}{'after':>12}{'change':>12} "
256
+ add(header)
257
+ for row in result["metrics"]:
258
+ before = _fmt(row["before"], row["unit"])
259
+ after = _fmt(row["after"], row["unit"])
260
+ change = _delta(row["delta"], row["unit"])
261
+ verdict = f" {row['verdict']}" if row["verdict"] else ""
262
+ add(f" {row['label']:<20}{before:>12}{after:>12}{change:>12}{verdict}")
263
+ if result["uneven"] and "before_per_run" in row:
264
+ per = (
265
+ f"{_fmt(row['before_per_run'], row['unit'])} -> "
266
+ f"{_fmt(row['after_per_run'], row['unit'])} per run"
267
+ )
268
+ add(f" {'':<20}{per:>36}")
269
+ add("")
270
+
271
+ if result["by_detector"]:
272
+ add("FINDINGS BY TYPE")
273
+ add(f" {'':<20}{'before':>12}{'after':>12}{'change':>12}")
274
+ for row in result["by_detector"]:
275
+ verdict = f" {row['verdict']}" if row["verdict"] else ""
276
+ add(
277
+ f" {row['detector']:<20}{row['before']:>12,}{row['after']:>12,}"
278
+ f"{_delta(row['delta'], 'count'):>12}{verdict}"
279
+ )
280
+ add("")
281
+
282
+ if result["unpriced"]["before"] or result["unpriced"]["after"]:
283
+ add(" note: one or both sides ran on models with no price available,")
284
+ add(" so cost comparisons are incomplete. Supply rates with --prices.")
285
+ add("")
286
+
287
+ return "\n".join(out)