File size: 27,555 Bytes
a2222d5
 
91a1a40
a2222d5
 
 
 
 
 
 
91a1a40
a2222d5
 
 
 
 
c0e2e7e
 
 
a2222d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91a1a40
 
 
 
 
 
 
 
a2222d5
 
91a1a40
 
 
a2222d5
91a1a40
 
 
 
a2222d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c0e2e7e
a2222d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c75e65
a2222d5
 
 
8c75e65
a2222d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c0e2e7e
 
a2222d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1510e8b
a2222d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c75e65
a2222d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c75e65
a2222d5
 
 
 
 
 
 
 
8c75e65
a2222d5
 
 
 
 
 
 
 
 
 
 
8c75e65
a2222d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
862967c
 
 
 
a2222d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91a1a40
 
 
 
a2222d5
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
"""PyBot Data Explorer: read-only API + UI over the PyBot swarm run release artifacts."""
from contextlib import asynccontextmanager
import base64, hashlib, json, os, re, sqlite3, subprocess, sys, threading, time
from datetime import datetime, timezone
from functools import cache
from pathlib import Path

from fastapi import FastAPI, HTTPException, Query
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.gzip import GZipMiddleware
from fastapi.responses import FileResponse, HTMLResponse, PlainTextResponse, Response
from fastapi.staticfiles import StaticFiles

ROOT = Path(__file__).parent
DATA = Path(os.environ.get("EXPLORER_DATA", ROOT / "data"))
COMMITS_REPO = os.environ.get("COMMITS_REPO", "HuggingFaceSwarms/pybot-commits")
TRACES_REPO = os.environ.get("TRACES_REPO", "HuggingFaceSwarms/pybot-traces")  # a dataset
# Pinned so the trace index's byte offsets always match the bytes read; bump it if the trace files change.
TRACES_REVISION = os.environ.get("TRACES_REVISION", "00c26ddf3e2afc6eb8bd3800ae66ca7e69a1a5f1")
BOARD_URL = os.environ.get("BOARD_URL", "https://huggingfaceswarms-pybot-msgboard.hf.space")
HUB = "https://huggingface.co"
GIT_DIR = Path(os.environ.get("GIT_DIR_PATH", "/tmp/pybot-commits.git"))
MAX_PATCH = 2_000_000
MAX_TRACE_BYTES = 8 << 20  # per request

@asynccontextmanager
async def lifespan(app):
    threading.Thread(target=git_sync, daemon=True).start()  # clone the history in the background
    yield


app = FastAPI(lifespan=lifespan, title="PyBot Data Explorer API", version="1.0",
              description="Read-only API over the PyBot swarm run: commits, PRs, reviews, agent traces and "
                          "message-board posts. Times are ISO 8601 UTC. See /llms.txt.")
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["GET"])
app.add_middleware(GZipMiddleware, minimum_size=2000)


# One id per deploy, from the code and data that shipped; it versions asset URLs and API ETags,
# so a redeploy shows at once while unchanged answers still revalidate with a cheap 304.
BUILD = hashlib.sha1(b"".join(p.read_bytes() for p in sorted((ROOT / "static").glob("*.*")) + [ROOT / "app.py"])
                     + "".join(f"{p.name}:{p.stat().st_size}:{p.stat().st_mtime_ns}" for p in sorted(DATA.glob("*.sqlite"))).encode()
                     ).hexdigest()[:12]
ETAG = f'"{BUILD}"'


@app.middleware("http")
async def cache_headers(request, call_next):
    path = request.url.path
    if path.startswith("/api/") and request.headers.get("if-none-match") == ETAG:
        return Response(status_code=304, headers={"ETag": ETAG, "Cache-Control": "no-cache"})
    response = await call_next(request)
    if path.startswith("/api/") and response.status_code == 200:
        response.headers["ETag"], response.headers["Cache-Control"] = ETAG, "no-cache"
    elif path.startswith("/static/"):
        response.headers["Cache-Control"] = "public, max-age=31536000, immutable" if request.query_params.get("v") == BUILD else "no-cache"
    return response


_local = threading.local()


def db():
    if not hasattr(_local, "db"):
        con = sqlite3.connect(f"file:{DATA / 'explorer.sqlite'}?immutable=1", uri=True)
        con.execute(f"ATTACH 'file:{DATA / 'traces.sqlite'}?immutable=1' AS t")
        con.row_factory = sqlite3.Row
        _local.db = con
    return _local.db


def q(sql, *args):
    return [dict(r) for r in db().execute(sql, args)]


def one(sql, *args, what="item"):
    rows = q(sql, *args)
    if not rows:
        raise HTTPException(404, f"{what} not found")
    return rows[0]


def unjson(row, *keys):
    for k in keys:
        if row.get(k):
            row[k] = json.loads(row[k])
    return row


def page(items, limit, offset):
    return {"items": items[:limit], "offset": offset, "next_offset": offset + limit if len(items) > limit else None}


# ---------- commits ----------

# The git server committed on the agents' behalf, so a commit's author is its PR's author; git_author keeps the raw one.
AUTHOR = "COALESCE(p.author, c.author) AS author, c.author AS git_author"
COMMIT_COLS = f"c.idx, c.sha, c.parent, c.ts, {AUTHOR}, c.title, c.pr, c.approvers, c.lp_win_rate, c.standard_error, c.score_revision"


# Direct links to the released sources (formats checked on the Hub; they open once the repos are public).
def commit_url(sha):
    return f"{HUB}/datasets/{COMMITS_REPO}/commit/{sha}"


def trace_url(lane, agent):
    return f"{HUB}/datasets/{TRACES_REPO}/blob/main/traces/{lane}/{agent}.jsonl"


def message_url(mid):
    return f"{BOARD_URL}/#msg/{mid}"


def with_sources(msgs):
    for m in msgs:
        m["source"] = message_url(m["id"])
    return msgs


def resolve_sha(sha):
    if not re.fullmatch(r"[0-9a-f]{4,40}", sha):
        raise HTTPException(400, "sha must be 4-40 hex characters")
    rows = q(f"SELECT {COMMIT_COLS} FROM commits c LEFT JOIN prs p ON p.pr = c.pr WHERE c.sha >= ? AND c.sha < ? LIMIT 2",
             sha, sha + "g")
    if len(rows) != 1:
        raise HTTPException(404 if not rows else 400, "commit not found" if not rows else "ambiguous sha prefix")
    return unjson(rows[0], "approvers")


@app.get("/api/commits", summary="List commits on main (newest first)")
def list_commits(author: str | None = None, pr: int | None = None,
                 text: str | None = Query(None, description="substring of the commit or PR title"),
                 since: str | None = Query(None, description="ISO time, inclusive"),
                 until: str | None = Query(None, description="ISO time, inclusive"),
                 scored: bool = False, limit: int = Query(50, ge=1, le=500), offset: int = Query(0, ge=0)):
    where, args = [], []
    if until and len(until) == 10:  # a bare date includes the whole day
        until += "T23:59:59.999Z"
    for cond, val in [("COALESCE(p.author, c.author) = ?", author), ("c.pr = ?", pr), ("c.ts >= ?", since), ("c.ts <= ?", until)]:
        if val is not None:
            where.append(cond); args.append(val)
    if text:
        where.append("(c.title LIKE ? OR p.title LIKE ?)"); args += [f"%{text}%"] * 2
    if scored:
        where.append("c.lp_win_rate IS NOT NULL")
    rows = q(f"""SELECT c.idx, c.sha, c.ts, {AUTHOR}, c.pr, p.title AS pr_title, c.title, c.lp_win_rate, c.standard_error
                 FROM commits c LEFT JOIN prs p ON p.pr = c.pr {"WHERE " + " AND ".join(where) if where else ""}
                 ORDER BY c.idx DESC LIMIT ? OFFSET ?""", *args, limit + 1, offset)
    return page(rows, limit, offset)


@app.get("/api/commits/{sha}", summary="One commit: metadata, score, its PR and neighbours")
def get_commit(sha: str):
    c = resolve_sha(sha)
    c["pr_info"] = pr_summary(c["pr"]) if c["pr"] else None
    nb = {r["idx"]: r["sha"] for r in q("SELECT idx, sha FROM commits WHERE idx IN (?, ?)", c["idx"] - 1, c["idx"] + 1)}
    c["prev_sha"], c["next_sha"] = nb.get(c["idx"] - 1), nb.get(c["idx"] + 1)
    c["source"] = commit_url(c["sha"])
    return c


_fetch_lock, _last_fetch = threading.Lock(), [0.0]


def git_env():
    env = dict(os.environ)
    token = os.environ.get("HF_TOKEN")
    if token:  # passed through env, never argv or the URL
        basic = base64.b64encode(f"hf:{token}".encode()).decode()
        env.update(GIT_CONFIG_COUNT="1", GIT_CONFIG_KEY_0="http.extraHeader",
                   GIT_CONFIG_VALUE_0=f"Authorization: Basic {basic}")
    return env


def git_sync():
    """Clone (or fetch) the commit history; at most once every 5 minutes. False if another thread is at it."""
    if not _fetch_lock.acquire(blocking=False):
        return False
    try:
        if time.time() - _last_fetch[0] < 300:
            return True
        _last_fetch[0] = time.time()
        url = f"https://huggingface.co/datasets/{COMMITS_REPO}"
        cmd = ["git", "-C", str(GIT_DIR), "fetch", "-q", "origin", "+refs/heads/*:refs/heads/*"] if GIT_DIR.exists() \
            else ["git", "clone", "-q", "--bare", url, str(GIT_DIR)]
        r = subprocess.run(cmd, env=git_env(), capture_output=True, timeout=900)
        if r.returncode:  # the token travels in env, so stderr never contains it
            print(f"git {cmd[1] if cmd[1] == 'clone' else 'fetch'} failed: {r.stderr.decode(errors='replace')[-500:]}",
                  file=sys.stderr, flush=True)
        return True
    finally:
        _fetch_lock.release()


def git(*args, sha):
    for attempt in range(2):
        if GIT_DIR.exists():
            r = subprocess.run(["git", "--git-dir", str(GIT_DIR), *args], capture_output=True, timeout=60)
            if r.returncode == 0:
                return r.stdout
        if attempt == 0 and not git_sync():
            raise HTTPException(503, "the commit history is still loading; try again shortly")
    raise HTTPException(503, f"commit {sha[:12]} is not in the history yet; try again later")


@app.get("/api/commits/{sha}/diff", summary="Unified diff of a commit against its parent")
def commit_diff(sha: str, patch: bool = Query(True, description="false returns only the file list")):
    c = resolve_sha(sha)
    stat = git("show", "--format=", "--numstat", "--no-renames", c["sha"], sha=c["sha"]).decode("utf-8", "replace")
    files = [{"path": p, "additions": None if a == "-" else int(a), "deletions": None if d == "-" else int(d),
              "source": f"{HUB}/datasets/{COMMITS_REPO}/blob/{c['sha']}/{p}"}
             for a, d, p in (line.split("\t", 2) for line in stat.splitlines() if line)]
    if not patch:
        return {"sha": c["sha"], "files": files}
    patch = git("show", "--format=", "--patch", "--no-renames", c["sha"], sha=c["sha"])
    return {"sha": c["sha"], "files": files, "truncated": len(patch) > MAX_PATCH,
            "patch": patch[:MAX_PATCH].decode("utf-8", "replace")}


@app.get("/api/commits/{sha}/file", summary="A file's content at a commit", response_class=PlainTextResponse)
def commit_file(sha: str, path: str):
    c = resolve_sha(sha)
    if not path or path.startswith(("-", "/")) or ".." in path.split("/"):
        raise HTTPException(400, "bad path")
    if not git("ls-tree", c["sha"], "--", path, sha=c["sha"]).strip():
        raise HTTPException(404, "file not found at this commit")
    return git("show", f"{c['sha']}:{path}", sha=c["sha"]).decode("utf-8", "replace")


@app.get("/api/scores", summary="SmolTalkBench win rate for every scored commit, in commit order")
def scores():
    rows = q("""SELECT c.idx, c.sha, c.ts, c.pr, COALESCE(p.author, c.author) AS author, c.lp_win_rate, c.standard_error
                FROM commits c LEFT JOIN prs p ON p.pr = c.pr WHERE c.lp_win_rate IS NOT NULL ORDER BY c.idx""")
    return {"columns": list(rows[0]) if rows else [], "rows": [list(r.values()) for r in rows]}


# ---------- PRs ----------

def pr_summary(n):
    rows = q("SELECT pr, author, title, state, opened_ts, merged_ts, merged_sha FROM prs WHERE pr = ?", n)
    return rows[0] if rows else None


@app.get("/api/prs/{n}", summary="A pull request with its description")
def get_pr(n: int):
    p = unjson(one("SELECT * FROM prs WHERE pr = ?", n, what="PR"), "approvers")
    p["commit"] = (q("SELECT sha FROM commits WHERE pr = ?", n) or [{}])[0].get("sha")
    p["review_count"] = q("SELECT count(*) n FROM reviews WHERE pr = ?", n)[0]["n"]
    p["message_count"] = q("SELECT count(*) n FROM pr_messages WHERE pr = ?", n)[0]["n"]
    p["source"] = commit_url(p["commit"]) if p["commit"] else None  # the PR pages themselves are not public
    return p


@app.get("/api/prs/{n}/reviews", summary="All reviews of a PR, oldest first")
def pr_reviews(n: int):
    one("SELECT pr FROM prs WHERE pr = ?", n, what="PR")
    return {"items": q("SELECT reviewer, ts, head_sha, verdict, comment FROM reviews WHERE pr = ? ORDER BY ts", n)}


@app.get("/api/prs/{n}/messages", summary="Board posts linked to a PR (mentions + author posts in the author window)")
def pr_messages(n: int, reason: str | None = Query(None, pattern="^(mention|author_window)$"),
                newest_first: bool = False, limit: int = Query(50, ge=1, le=500), offset: int = Query(0, ge=0)):
    one("SELECT pr FROM prs WHERE pr = ?", n, what="PR")
    rows = q(f"""SELECT m.*, l.reason FROM pr_messages l JOIN messages m ON m.id = l.message_id
                 WHERE l.pr = ? {"AND l.reason = ?" if reason else ""} ORDER BY m.ts {"DESC" if newest_first else ""} LIMIT ? OFFSET ?""",
             *([n, reason] if reason else [n]), limit + 1, offset)
    return page(with_sources(rows), limit, offset)


@app.get("/api/prs/{n}/traces", summary="Trace windows linked to a PR (author and each reviewer)")
def pr_traces(n: int):
    one("SELECT pr FROM prs WHERE pr = ?", n, what="PR")
    rows = q("""SELECT w.agent, w.role, w.from_ts, w.to_ts, a.lane, a.agent IS NOT NULL AS has_trace, a.reconstructed
                FROM pr_traces w LEFT JOIN t.trace_files a ON a.agent = w.agent WHERE w.pr = ?
                ORDER BY w.role, w.from_ts""", n)
    for r in rows:
        r["has_trace"], r["reconstructed"] = bool(r["has_trace"]), bool(r["reconstructed"])
        r["url"] = f"/api/traces/{r['agent']}?from={r['from_ts']}&to={r['to_ts']}"
        r["source"] = trace_url(r["lane"], r["agent"]) if r["has_trace"] else None
    return {"items": rows}


# ---------- traces ----------

def epoch(s):
    try:
        dt = datetime.fromisoformat(s)
    except ValueError:
        raise HTTPException(400, f"bad time: {s}")
    return (dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc)).timestamp()


def clip(x, n):
    if isinstance(x, str):
        return x if len(x) <= n else x[:n] + f"\n… [{len(x) - n} more chars]"
    if isinstance(x, list):
        return [clip(v, n) for v in x]
    if isinstance(x, dict):
        return {k: clip(v, n) for k, v in x.items()}
    return x


def read_range(lane, agent, start, end):
    from huggingface_hub import HfFileSystem  # uses HF_TOKEN if set; the dataset is public
    return HfFileSystem().cat_file(f"datasets/{TRACES_REPO}@{TRACES_REVISION}/traces/{lane}/{agent}.jsonl", start=start, end=end)


@app.get("/api/traces/{agent}", summary="An agent's trace records in a time window (paginated by byte cursor)")
def traces(agent: str, from_: str | None = Query(None, alias="from"), to: str | None = None,
           limit: int = Query(100, ge=1, le=500), cursor: int = Query(0, ge=0),
           messages_only: bool = Query(False, description="skip controller `custom` events"),
           max_chars: int = Query(4000, ge=200, le=200_000, description="clip long strings")):
    f = one("SELECT * FROM t.trace_files WHERE agent = ?", agent, what="agent trace")
    lo, hi = epoch(from_) if from_ else 0, epoch(to) if to else 1e12
    blocks = q("""SELECT offset, length FROM t.trace_blocks WHERE agent = ? AND offset + length > ?
                  AND max_ts >= ? AND min_ts <= ? ORDER BY offset""", agent, cursor, lo, hi)
    out, read, next_cursor = [], 0, None
    for b in blocks:
        start = max(b["offset"], cursor)
        if read >= MAX_TRACE_BYTES:
            next_cursor = start
            break
        try:
            data = read_range(f["lane"], agent, start, b["offset"] + b["length"])
        except Exception as e:  # missing token, network, rate limit
            raise HTTPException(503, f"trace storage unavailable ({type(e).__name__}); try again shortly")
        read += len(data)
        pos = start
        for line in data.splitlines(keepends=True):
            pos += len(line)
            try:
                rec = json.loads(line)
            except ValueError:  # only a cursor that is not a line start lands mid-record
                raise HTTPException(400, "bad cursor")
            ts = rec.get("timestamp")
            if not ts or not lo <= epoch(ts) <= hi or (messages_only and rec.get("type") != "message"):
                continue
            out.append(clip(rec, max_chars))
            if len(out) >= limit:
                next_cursor = pos  # shortcut: may point at the end, so the last page can be empty
                break
        if next_cursor is not None:
            break
    return {"agent": agent, "lane": f["lane"], "reconstructed": bool(f["reconstructed"]), "source": trace_url(f["lane"], agent), "from": from_, "to": to,
            "records": out, "next_cursor": next_cursor}


# ---------- messages & agents ----------

@app.get("/api/messages/search", summary="Full-text search over board posts (SQLite FTS5 syntax)")
def search_messages(q_: str = Query(..., alias="q", min_length=1), channel: str | None = None,
                    author: str | None = None, limit: int = Query(50, ge=1, le=200), offset: int = Query(0, ge=0)):
    extra, args = "", []
    for col, val in [("channel", channel), ("author", author)]:
        if val:
            extra += f" AND m.{col} = ?"; args.append(val)
    deadline = time.monotonic() + 2  # FTS queries like `t* OR a*` can run for seconds
    db().set_progress_handler(lambda: time.monotonic() > deadline, 10_000)
    try:
        rows = q(f"""SELECT m.id, m.channel, m.author, m.ts, m.thread_id,
                     snippet(messages_fts, 0, '[', ']', ' … ', 24) AS snippet
                     FROM messages_fts JOIN messages m ON m.id = messages_fts.rowid
                     WHERE messages_fts MATCH ? {extra} ORDER BY m.ts LIMIT ? OFFSET ?""",
                 q_, *args, limit + 1, offset)
        with_sources(rows)
    except sqlite3.OperationalError as e:
        raise HTTPException(400, "query took too long; make it more specific" if "interrupt" in str(e) else f"bad query: {e}")
    finally:
        db().set_progress_handler(None, 0)
    return page(rows, limit, offset)


@app.get("/api/messages/{mid}", summary="A board post with its whole thread")
def get_message(mid: int):
    m = one("SELECT * FROM messages WHERE id = ?", mid, what="message")
    root = m["thread_id"] or m["id"]
    # Lane threads hold thousands of replies, so return the root plus 50 replies either side of this post.
    near = q("""SELECT * FROM (SELECT * FROM messages WHERE thread_id = ? AND ts < ? ORDER BY ts DESC LIMIT 50)
                UNION ALL SELECT * FROM (SELECT * FROM messages WHERE thread_id = ? AND ts >= ? ORDER BY ts LIMIT 51)
                ORDER BY ts""", root, m["ts"], root, m["ts"])
    thread = q("SELECT * FROM messages WHERE id = ?", root) + [r for r in near if r["id"] != root]
    m["thread_size"] = 1 + q("SELECT count(*) n FROM messages WHERE thread_id = ?", root)[0]["n"]
    m["prs"] = [r["pr"] for r in q("SELECT pr FROM pr_messages WHERE message_id = ? AND reason = 'mention'", mid)]
    m["source"] = message_url(mid)
    return {"message": m, "thread_root": root, "thread": with_sources(thread)}


def iso_epoch(x):
    return datetime.fromtimestamp(x, timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") if x is not None else None


AGENT_COLS = """a.name, COALESCE(a.lane, f.lane) AS lane, f.agent IS NOT NULL AS has_trace, f.reconstructed, a.posts, a.prs_opened, a.prs_merged, a.reviews,
    s.model_calls, s.tool_calls, s.input_tokens, s.output_tokens, s.reasoning_tokens,
    s.input_tokens + s.output_tokens AS total_tokens, f.records, f.first_ts, f.last_ts"""
AGENT_FROM = "agents a LEFT JOIN t.trace_files f ON f.agent = a.name LEFT JOIN t.agent_stats s ON s.agent = a.name"
AGENT_SORTS = {"name", "lane", "posts", "prs_opened", "prs_merged", "reviews", "model_calls", "tool_calls",
               "input_tokens", "output_tokens", "reasoning_tokens", "total_tokens", "records"}


def agent_row(r):
    r["has_trace"], r["reconstructed"] = bool(r["has_trace"]), bool(r["reconstructed"])
    r["first_ts"], r["last_ts"] = iso_epoch(r["first_ts"]), iso_epoch(r["last_ts"])
    r["source"] = trace_url(r["lane"], r["name"]) if r["has_trace"] else None
    return r


@app.get("/api/agents", summary="All 1,000 agents with their activity: trace tokens and calls, posts, PRs, reviews")
def list_agents(sort: str = Query("total_tokens", description=f"one of {sorted(AGENT_SORTS)}"),
                order: str = Query("desc", pattern="^(asc|desc)$"), lane: str | None = None,
                limit: int = Query(1000, ge=1, le=1000), offset: int = Query(0, ge=0)):
    if sort not in AGENT_SORTS:
        raise HTTPException(400, f"sort must be one of {sorted(AGENT_SORTS)}")
    rows = q(f"""SELECT {AGENT_COLS} FROM {AGENT_FROM} {"WHERE COALESCE(a.lane, f.lane) = ?" if lane else ""}
                 ORDER BY {sort} IS NULL, {sort} {order}, a.name LIMIT ? OFFSET ?""", *([lane] if lane else []), limit + 1, offset)
    return page([agent_row(r) for r in rows], limit, offset)


def hours_of(name):
    return q("SELECT hour, model_calls, tool_calls, input_tokens, output_tokens FROM t.agent_hours WHERE agent = ? ORDER BY hour", name)


@app.get("/api/agents/{name}", summary="An agent: lane, activity stats, hourly series, PRs, reviews, recent posts")
def get_agent(name: str):
    rows = q(f"SELECT {AGENT_COLS} FROM {AGENT_FROM} WHERE a.name = ?", name)
    if not rows:
        raise HTTPException(404, "agent not found")
    info, hours = agent_row(rows[0]), hours_of(name)
    busiest = max(hours, key=lambda h: h["output_tokens"], default=None)
    return {**info, "run": run_span(), "busiest_hour": iso_epoch(busiest["hour"] * 3600) if busiest else None,
            "hours": {"columns": ["hour", "model_calls", "tool_calls", "input_tokens", "output_tokens"],
                      "rows": [[iso_epoch(h["hour"] * 3600), h["model_calls"], h["tool_calls"], h["input_tokens"],
                                h["output_tokens"]] for h in hours]},
            "prs": q("SELECT pr, title, state, opened_ts, merged_ts, merged_sha FROM prs WHERE author = ? ORDER BY pr", name),
            "review_list": q("SELECT pr, ts, verdict FROM reviews WHERE reviewer = ? ORDER BY ts", name),
            "recent_posts": with_sources(q("SELECT * FROM messages WHERE author = ? ORDER BY ts DESC LIMIT 20", name))}


@cache
def run_span():
    lo, hi = q("SELECT min(hour) lo, max(hour) hi FROM t.agent_hours")[0].values()
    busy = [r["hour"] for r in q("SELECT DISTINCT hour FROM t.agent_hours WHERE model_calls > 0 ORDER BY hour")]
    # Stretches of 6+ hours when no agent ran (the run was paused); charts cut them out of the time axis.
    gaps = [{"from": iso_epoch((a + 1) * 3600), "to": iso_epoch(b * 3600)} for a, b in zip(busy, busy[1:]) if b - a > 6]
    return {"first_hour": iso_epoch(lo * 3600), "last_hour": iso_epoch(hi * 3600), "hours": hi - lo + 1, "gaps": gaps}


HIGHLIGHTS = [("posts", "Most board posts"), ("reasoning_tokens", "Most reasoning tokens"),
              ("prs_merged", "Most PRs merged"), ("reviews", "Most reviews given"), ("tool_calls", "Most tool calls")]


@app.get("/api/highlights", summary="Run totals, the standout agents and key moments, all derived from the data")
@cache
def highlights():
    tot = q("""SELECT (SELECT count(*) FROM agents) agents, (SELECT count(*) FROM t.trace_files) traces,
               sum(model_calls) model_calls, sum(tool_calls) tool_calls, sum(input_tokens + output_tokens) tokens,
               sum(output_tokens) output_tokens, sum(reasoning_tokens) reasoning_tokens FROM t.agent_stats""")[0]
    lo = q("SELECT min(hour) h FROM t.agent_hours")[0]["h"]
    span = run_span()["hours"]

    def series(name):
        out = [0] * span
        for h in hours_of(name):
            out[h["hour"] - lo] = h["output_tokens"]
        return out

    cards = []
    for metric, title in HIGHLIGHTS:
        r = agent_row(q(f"SELECT {AGENT_COLS} FROM {AGENT_FROM} ORDER BY {metric} DESC LIMIT 1")[0])
        sp = series(r["name"])
        cards.append({"title": title, "metric": metric, "value": r[metric], "agent": r["name"], "lane": r["lane"],
                      "busiest_hour": iso_epoch((lo + sp.index(max(sp))) * 3600) if any(sp) else None, "spark": sp})
    return {"totals": tot, "run": run_span(), "highlights": cards, "moments": moments()}


def moments():
    out = []
    for first in q("SELECT pr, author, title, merged_ts, merged_sha FROM prs WHERE state = 'merged' ORDER BY merged_ts LIMIT 1"):
            out.append({"ts": first["merged_ts"], "agent": first["author"], "sha": first["merged_sha"],
                    "text": f"First merged PR: #{first['pr']} by {first['author']}, \u201c{first['title']}\u201d"})
    # Swarm size: agents that made at least one model call in an hour.
    active = q("""SELECT hour, count(*) n, (SELECT agent FROM t.agent_hours b WHERE b.hour = a.hour
                  ORDER BY model_calls DESC LIMIT 1) top FROM t.agent_hours a WHERE model_calls > 0 GROUP BY hour ORDER BY hour""")
    peak = max(active, key=lambda r: r["n"])
    for k in (250, 500):
        r = next((r for r in active if r["n"] >= k), None)
        if r and r["n"] < peak["n"]:
            out.append({"ts": iso_epoch(r["hour"] * 3600), "agent": r["top"],
                        "text": f"Over {k} agents active in one hour for the first time: {r['n']} (busiest that hour: {r['top']})"})
    out.append({"ts": iso_epoch(peak["hour"] * 3600), "agent": peak["top"],
                "text": f"Peak: {peak['n']} agents active in one hour (busiest that hour: {peak['top']})"})
    # The largest score drop between consecutive scored commits, and the first commit that recovers it.
    sc = q("""SELECT c.idx, c.sha, c.ts, c.pr, COALESCE(p.author, c.author) author, c.lp_win_rate s, c.title
              FROM commits c LEFT JOIN prs p ON p.pr = c.pr WHERE c.lp_win_rate IS NOT NULL ORDER BY c.idx""")
    if len(sc) < 2:
        return sorted(out, key=lambda m: m["ts"])
    i = max(range(1, len(sc)), key=lambda i: sc[i - 1]["s"] - sc[i]["s"])
    brk, before = sc[i], sc[i - 1]["s"]
    fix = next((r for r in sc[i + 1:] if r["s"] >= before - 2), None)
    out.append({"ts": brk["ts"], "agent": brk["author"], "sha": brk["sha"],
                "text": f"Commit {brk['idx']:,} (scored commit {i + 1:,}; PR #{brk['pr']} by {brk['author']}) drops the win rate "
                        f"from {before:.1f}% to {brk['s']:.1f}%"})
    if fix:
        out.append({"ts": fix["ts"], "agent": fix["author"], "sha": fix["sha"],
                    "text": f"Commit {fix['idx']:,} (PR #{fix['pr']} by {fix['author']}) brings it back to {fix['s']:.1f}%, "
                            f"{fix['idx'] - brk['idx']} commits later: \u201c{re.sub(r' [(]#[0-9]+[)]$', '', fix['title'])}\u201d"})
    last = sc[-1]
    out.append({"ts": last["ts"], "agent": last["author"], "sha": last["sha"],
                "text": f"Final commit {last['sha'][:7]} (PR #{last['pr']} by {last['author']}): {last['s']:.1f}%"})
    return sorted(out, key=lambda m: m["ts"])


# ---------- UI and docs ----------

@app.get("/llms.txt", include_in_schema=False, response_class=PlainTextResponse)
def llms():
    return (ROOT / "llms.txt").read_text()


@app.get("/favicon.ico", include_in_schema=False)
def favicon():
    return FileResponse(ROOT / "static" / "favicon.svg", media_type="image/svg+xml")


@app.get("/", include_in_schema=False)
@app.get("/commit/{sha}", include_in_schema=False)
@app.get("/message/{mid}", include_in_schema=False)
@app.get("/pr/{n}", include_in_schema=False)
@app.get("/data", include_in_schema=False)
@app.get("/commits", include_in_schema=False)
@app.get("/agent/{name}", include_in_schema=False)
def ui():
    return HTMLResponse(INDEX, headers={"Cache-Control": "no-cache"})


INDEX = re.sub(r'(/static/[\w.]+\.(?:js|css))"', rf'\1?v={BUILD}"', (ROOT / "static" / "index.html").read_text())


app.mount("/static", StaticFiles(directory=ROOT / "static"), name="static")