Commit ·
a2222d5
0
Parent(s):
PyBot Data Explorer (history squashed to stay under the Space storage limit)
Browse filesCo-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: claude opus 5.5 <claude opus 5.5@users.noreply.huggingface.co>
Co-authored-by: claude opus 5.5 <claude opus 5.5@users.noreply.huggingface.co>
Files changed (21)
- .dockerignoreAdded+3
- .gitattributesAdded+37
- DockerfileAdded+11
- README.mdAdded+65
- app.pyAdded+517
- build/build_db.pyAdded+166
- build/index_traces.pyAdded+99
- llms.txtAdded+48
- requirements.txtAdded+3
- static/agents.jsAdded+222
- static/app.jsAdded+594
- static/d3.min.jsAdded
- static/favicon.svgAdded
- static/fonts/LICENSE-letter-gothic-code.txtAdded+230
- static/fonts/LICENSE-routed-gothic.mdAdded+97
- static/fonts/lead.woff2Added
- static/fonts/mono-bold.woff2Added
- static/fonts/mono.woff2Added
- static/index.htmlAdded+28
- static/style.cssAdded+219
- tests/test_api.pyAdded+129
123tests/build/__pycache__/12345678910111213141516171819202122232425262728293031323334353637*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textdata/traces.sqlite filter=lfs diff=lfs merge=lfs -textdata/explorer.sqlite filter=lfs diff=lfs merge=lfs -text1234567891011FROM python:3.12-slimRUN apt-get update && apt-get install -y --no-install-recommends git && rm -rf /var/lib/apt/lists/*RUN useradd -m -u 1000 userWORKDIR /appCOPY requirements.txt .RUN pip install --no-cache-dir -r requirements.txtCOPY --chown=user . .USER userENV GIT_DIR_PATH=/tmp/pybot-commits.gitEXPOSE 7860CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465---title: PyBot Data Exploreremoji: 🐝colorFrom: graycolorTo: yellowsdk: dockerapp_port: 7860pinned: falseshort_description: Explore the PyBot swarm run commit by commit---
# PyBot Data Explorer
Pick a commit of the PyBot swarm run and see its diff, its pull request and reviews, theagents' traces around it and the related message-board posts. People use the web UI; agentsuse the JSON API (`/openapi.json`, `/docs`, and a short guide at `/llms.txt`).
The home page starts from the agents: run totals, the standout agents, one square per agent coloured byactivity, and key moments, each linking to that agent's trace at the time. The Commits tab browses therun commit by commit.
Shareable URLs: `/agent/<name>?at=<hour>`, `/commits?sha=<sha>&view=reviews|traces|diff|messages`,`/commit/<sha>?tab=…`, `/pr/<n>`, `/message/<id>`, `/data`.
## Data
| What | Where it comes from | How it is served ||---|---|---|| PRs, reviews, commits, scores | release tables cut at commit `24cbc04` (2026-11-13T10:17:13Z) | `data/explorer.sqlite` || Board posts (184,059, 12 channels) | board export in `HuggingFaceSwarms/pybot-msgboard` (`data/`) | `data/explorer.sqlite`, FTS5 index || Diffs and files | git history in the dataset `HuggingFaceSwarms/pybot-commits` | bare clone at startup, `git show` || Agent traces (997 agents, 33 GB) | bucket `HuggingFaceSwarms/pybot-traces` | `data/traces.sqlite` time index + HTTP range reads |
The same job also sums each agent's assistant messages (model calls, tool calls, input, output andreasoning tokens) in total and per hour; output tokens include reasoning tokens.The trace index cuts every agent's JSONL into blocks of at most 200 records or 1 MiB and storeseach block's byte range and min/max timestamp. A trace request reads only the blocks that overlapthe requested window (at most 8 MiB per request) and pages with a byte cursor.
## Linking rules
- **Author trace window:** from 10 minutes before the PR opened until it merged, closed, or the cutoff (still open).- **Reviewer trace window:** each review's time ± 15 minutes.- **PR messages:** posts that name the PR number (`#14943`, `PR 14943`, `PR #14943`, `pr:14943`, `refs/pr/14943`) between the PR's opening and one day after it merged or closed, plus the PR author's posts inside the author window. A low number used for something else (a rank, a list item) can still link by mistake.- **Text clean-up at build time:** links to the run's PR pages are rewritten to plain `#N` (the UI links `#N` to that PR's commit, or to a PR page if it never merged), and workspace paths become `[WORKSPACE-PATH]`.- **Commits → PRs:** the `pr` field of the commit table.
## Access
The three source artifacts are private for now. The Space reads them with the Space secret`HF_TOKEN` (a read token for the `HuggingFaceSwarms` org). Once they are public the secret can beremoved; nothing else changes.
## Rebuilding the data
```python build/build_db.py TABLES_DIR BOARD_DIR traces_manifest.jsonl data/explorer.sqlitehf jobs uv run --flavor cpu-upgrade -v hf://buckets/HuggingFaceSwarms/pybot-traces:/src:ro --secrets HF_TOKEN \ build/index_traces.py /src/traces /tmp/traces.sqlite HuggingFaceSwarms/pybot-explorer```
Tests: `pip install pytest httpx -r requirements.txt && pytest tests`.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517"""PyBot Data Explorer: read-only API + UI over the PyBot swarm run release artifacts."""from contextlib import asynccontextmanagerimport base64, json, os, re, sqlite3, subprocess, sys, threading, timefrom datetime import datetime, timezonefrom functools import cachefrom pathlib import Path
from fastapi import FastAPI, HTTPException, Queryfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.middleware.gzip import GZipMiddlewarefrom fastapi.responses import FileResponse, PlainTextResponsefrom fastapi.staticfiles import StaticFiles
ROOT = Path(__file__).parentDATA = Path(os.environ.get("EXPLORER_DATA", ROOT / "data"))COMMITS_REPO = os.environ.get("COMMITS_REPO", "HuggingFaceSwarms/pybot-commits")TRACES_BUCKET = os.environ.get("TRACES_BUCKET", "HuggingFaceSwarms/pybot-traces")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_000MAX_TRACE_BYTES = 8 << 20 # per request
@asynccontextmanagerasync 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)
@app.middleware("http")async def cache_headers(request, call_next): response = await call_next(request) if request.url.path.startswith("/api/") and response.status_code == 200: response.headers["Cache-Control"] = "public, max-age=3600" # the data never changes 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}/buckets/{TRACES_BUCKET}/resolve/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 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"] = bool(r["has_trace"]) 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 # token from HF_TOKEN; none needed once public return HfFileSystem().cat_file(f"buckets/{TRACES_BUCKET}/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__}); is HF_TOKEN set?") 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"], "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, a.lane, f.agent IS NOT NULL AS has_trace, 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"] = bool(r["has_trace"]) 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 a.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))}
@cachedef run_span(): lo, hi = q("SELECT min(hour) lo, max(hour) hi FROM t.agent_hours")[0].values() return {"first_hour": iso_epoch(lo * 3600), "last_hour": iso_epoch(hi * 3600), "hours": hi - lo + 1}
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")@cachedef 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 FileResponse(ROOT / "static" / "index.html")
app.mount("/static", StaticFiles(directory=ROOT / "static"), name="static")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166"""Build data/explorer.sqlite from the scrubbed release tables and the board export.
Usage: build_db.py TABLES_DIR BOARD_DIR TRACE_MANIFEST OUT_SQLITETABLES_DIR has prs/reviews/commits.jsonl; BOARD_DIR is the board export (data/manifest.json,data/messages/*.json.gz); TRACE_MANIFEST is traces/_manifest.jsonl."""import glob, gzip, json, os, re, sqlite3, sysfrom datetime import datetime, timezone
CUTOFF = "2026-11-13T10:17:13.000Z" # commit 24cbc04AUTHOR_LEAD_S, REVIEW_PAD_S = 600, 900# Links to the run's PR pages become plain "#N" (the UI links those to the explorer); workspace paths are masked.PR_LINK = re.compile(r"(?:https?://)?huggingface\.co/datasets/HuggingFaceSwarms/[\w.-]+/discussions/(\d+)(?:/files)?")WS_PATH = re.compile(r"/data/workspaces/[^\s`'\"()<>\[\]]*")CLEANED = {}
def clean(s, column): if not s: return s out, n1 = PR_LINK.subn(r"#\1", s) out, n2 = WS_PATH.subn("[WORKSPACE-PATH]", out) if n1 or n2: CLEANED[column] = [a + b for a, b in zip(CLEANED.get(column, [0, 0]), [n1, n2])] return out
PR_REF = re.compile(r"(?:#|\bPR\s*#?\s*|\bpr:|refs/pr/)(\d{1,6})\b", re.I)
def iso(x): """Normalise ISO strings and epoch seconds to YYYY-MM-DDTHH:MM:SS.mmmZ (sorts as text).""" if x is None: return None dt = datetime.fromtimestamp(x, timezone.utc) if isinstance(x, (int, float)) else \ datetime.fromisoformat(x.replace("Z", "+00:00")) return dt.strftime("%Y-%m-%dT%H:%M:%S.") + f"{dt.microsecond // 1000:03d}Z"
def epoch(s): return datetime.fromisoformat(s.replace("Z", "+00:00")).timestamp()
def rows(path): with open(path) as f: return [json.loads(line) for line in f]
def main(tables, board, trace_manifest, out): if os.path.exists(out): os.remove(out) db = sqlite3.connect(out) db.executescript(""" CREATE TABLE commits(idx INT, sha TEXT PRIMARY KEY, parent TEXT, ts TEXT, author TEXT, title TEXT, pr INT, approvers TEXT, lp_win_rate REAL, standard_error REAL, score_revision TEXT); CREATE TABLE prs(pr INT PRIMARY KEY, author TEXT, title TEXT, description TEXT, branch TEXT, base_sha TEXT, opened_ts TEXT, state TEXT, merged_ts TEXT, merged_sha TEXT, head_sha_final TEXT, close_reason TEXT, n_updates INT, approvers TEXT, first_event_ts TEXT, last_event_ts TEXT); CREATE TABLE reviews(pr INT, reviewer TEXT, ts TEXT, head_sha TEXT, verdict TEXT, comment TEXT); CREATE TABLE channels(id INT PRIMARY KEY, name TEXT, description TEXT); CREATE TABLE messages(id INT PRIMARY KEY, channel TEXT, author TEXT, ts TEXT, thread_id INT, reply_to INT, body TEXT); CREATE VIRTUAL TABLE messages_fts USING fts5(body, content='messages', content_rowid='id'); CREATE TABLE agents(name TEXT PRIMARY KEY, lane TEXT, trace_records INT, trace_bytes INT, trace_last TEXT, posts INT, prs_opened INT, prs_merged INT, reviews INT); CREATE TABLE pr_traces(pr INT, agent TEXT, role TEXT, from_ts TEXT, to_ts TEXT); CREATE TABLE pr_messages(pr INT, message_id INT, reason TEXT, PRIMARY KEY(pr, message_id)) WITHOUT ROWID; """)
commits = rows(f"{tables}/commits.jsonl") db.executemany("INSERT INTO commits VALUES (?,?,?,?,?,?,?,?,?,?,?)", [ (i, c["sha"], (c["parent_shas"] or [None])[0], iso(c["ts"]), c["author"], clean(c["title"], "commits.title"), c["pr"], json.dumps(c["approvers"]) if c["approvers"] else None, *((c["score"]["lp_win_rate"], c["score"]["standard_error"], c["score"]["revision"]) if c["score"] else (None,) * 3)) for i, c in enumerate(commits)])
prs = rows(f"{tables}/prs.jsonl") db.executemany("INSERT INTO prs VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", [ (p["pr"], p["author"], clean(p["title"], "prs.title"), clean(p["description"], "prs.description"), p["branch"], p["base_sha"], iso(p["opened_ts"]), p["state_at_cutoff"], iso(p["merged_ts"]), p["merged_sha"], p["head_sha_final"], clean(p["close_reason"], "prs.close_reason"), p["n_updates"], json.dumps(p["approvers"]) if p["approvers"] else None, iso(p["first_event_ts"]), iso(p["last_event_ts"])) for p in prs])
reviews = rows(f"{tables}/reviews.jsonl") db.executemany("INSERT INTO reviews VALUES (?,?,?,?,?,?)", [ (r["pr"], r["reviewer"], iso(r["ts"]), r["head_sha"], r["verdict"], clean(r["comment"], "reviews.comment")) for r in reviews])
# Board export: chunk rows are [id, seq, sender, created_at, body, reply_to, thread_id, edited_at, mentions]. manifest = json.load(open(f"{board}/data/manifest.json")) people = {p["id"]: p["external_id"] for p in manifest["people"]} chans = {c["id"]: c["name"] for c in manifest["channels"]} db.executemany("INSERT INTO channels VALUES (?,?,?)", [(c["id"], c["name"], c["description"]) for c in manifest["channels"]]) cutoff = manifest["last_at"] msgs = [] for path in glob.glob(f"{board}/data/messages/*.json.gz"): cid = int(os.path.basename(path).split("-")[0]) for r in json.load(gzip.open(path)): body = r[4] if r[7] and r[7] > cutoff: # same rule as the board reader: show the text as of the cutoff prev = [v for v in manifest["revisions"].get(str(r[0]), []) if v[2] <= cutoff < v[3]] body = prev[0][1] if prev else body msgs.append((r[0], chans[cid], people.get(r[2], f"principal-{r[2]}"), iso(r[3]), r[6] or None, r[5] or None, clean(body, "messages.body"))) msgs.sort() db.executemany("INSERT INTO messages VALUES (?,?,?,?,?,?,?)", msgs) db.execute("INSERT INTO messages_fts(messages_fts) VALUES ('rebuild')")
# Agents: the board's experiment agents (1,000), with their lane and trace size when a trace was released. traced = {m["agent"]: m for m in map(json.loads, open(trace_manifest))} roster = sorted({p["external_id"] for p in manifest["people"] if p.get("experiment_agent")} | set(traced)) db.executemany("INSERT INTO agents(name, lane, trace_records, trace_bytes, trace_last) VALUES (?,?,?,?,?)", [(a, *((traced[a]["lane"], traced[a]["kept"], traced[a]["bytes_out"], traced[a]["last_record"]) if a in traced else (None,) * 4)) for a in roster])
# Trace windows: author [opened - 10 min, merged | closed | cutoff]; each review ts +/- 15 min. pr_end, windows = {}, [] for p in prs: end = p["merged_ts"] or (p["last_event_ts"] if p["state_at_cutoff"] == "closed" else CUTOFF) start = epoch(p["opened_ts"]) - AUTHOR_LEAD_S pr_end[p["pr"]] = (p["author"], iso(start), iso(end)) windows.append((p["pr"], p["author"], "author", iso(start), iso(end))) for r in reviews: t = epoch(r["ts"]) windows.append((r["pr"], r["reviewer"], "reviewer", iso(t - REVIEW_PAD_S), iso(t + REVIEW_PAD_S))) db.executemany("INSERT INTO pr_traces VALUES (?,?,?,?,?)", windows)
# Messages: those naming the PR number, plus the author's posts inside the author window. # A mention counts only from the PR's opening until a day after it ended: "#1" in a later post is rarely PR 1. opened = {p["pr"]: iso(p["opened_ts"]) for p in prs} late = {pr: iso(epoch(end) + 86400) for pr, (_, _, end) in pr_end.items()} links = set() for mid, _, _, ts, _, _, body in msgs: for n in {int(x) for x in PR_REF.findall(body or "")}: if n in pr_end and opened[n] <= ts <= late[n]: links.add((n, mid, "mention")) db.executemany("INSERT OR IGNORE INTO pr_messages VALUES (?,?,?)", sorted(links)) db.execute("CREATE INDEX messages_author_ts ON messages(author, ts)") for pr, (author, start, end) in pr_end.items(): db.execute("""INSERT OR IGNORE INTO pr_messages SELECT ?, id, 'author_window' FROM messages WHERE author = ? AND ts BETWEEN ? AND ?""", (pr, author, start, end))
db.executescript(""" UPDATE agents SET posts = (SELECT count(*) FROM messages WHERE author = name), prs_opened = (SELECT count(*) FROM prs WHERE author = name), prs_merged = (SELECT count(*) FROM prs WHERE author = name AND state = 'merged'), reviews = (SELECT count(*) FROM reviews WHERE reviewer = name); CREATE INDEX commits_pr ON commits(pr); CREATE INDEX commits_author ON commits(author); CREATE INDEX commits_idx ON commits(idx); CREATE INDEX prs_author ON prs(author); CREATE INDEX reviews_pr ON reviews(pr); CREATE INDEX reviews_reviewer ON reviews(reviewer); CREATE INDEX messages_thread ON messages(thread_id); CREATE INDEX pr_traces_pr ON pr_traces(pr); """) db.commit() for t in ["commits", "prs", "reviews", "messages", "agents", "pr_traces", "pr_messages"]: print(t, db.execute(f"SELECT count(*) FROM {t}").fetchone()[0]) print(db.execute("SELECT reason, count(*) FROM pr_messages GROUP BY 1").fetchall()) print("rewritten [PR links, workspace paths] by column:", CLEANED) db.execute("VACUUM") db.close() print("bytes", os.path.getsize(out))
if __name__ == "__main__": main(*sys.argv[1:])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899# /// script# requires-python = ">=3.11"# dependencies = ["huggingface_hub>=1.0"]# ///"""Build a per-agent time index and activity stats over the trace JSONL files.
Each file is cut into blocks of <=200 records or <=1 MiB. One row per block:(agent, offset, length, records, min_ts, max_ts). The API range-reads only theblocks that overlap a requested time window. Assistant messages also give eachagent's model calls, tool calls and token usage, in total and per hour.Usage: index_traces.py SRC_DIR OUT_SQLITE [SPACE_REPO]"""import json, os, re, sqlite3, sysfrom collections import defaultdictfrom datetime import datetimefrom multiprocessing import Pool
TS = re.compile(rb'"timestamp": ?"([^"]+)"')DECODE = json.JSONDecoder().raw_decodeMAX_RECORDS, MAX_BYTES = 200, 1 << 20
def epoch(raw): return datetime.fromisoformat(raw.decode().replace("Z", "+00:00")).timestamp()
def index_file(args): lane, agent, path = args blocks, start, n, lo, hi, off = [], 0, 0, None, None, 0 total, t = 0, None stats = [0, 0, 0, 0, 0] # model calls, tool calls, input, output, reasoning tokens hours = defaultdict(lambda: [0, 0, 0, 0]) # hour -> model calls, tool calls, input, output tokens with open(path, "rb", buffering=8 << 20) as f: for line in f: m = TS.search(line, 0, 400) if m: t = epoch(m.group(1)) lo = t if lo is None or t < lo else lo hi = t if hi is None or t > hi else hi if t is not None and b'"role": "assistant"' in line[:400]: u = line.find(b'"usage": ') usage = DECODE(line[u + 9:].decode("utf-8", "replace"))[0] if u > 0 else {} calls = line.count(b'"type": "toolCall"') # escaped inside strings, so only real tool calls match row = (1, calls, usage.get("input", 0), usage.get("output", 0), usage.get("reasoning", 0)) stats = [a + b for a, b in zip(stats, row)] h = hours[int(t // 3600)] for i, v in enumerate(row[:4]): h[i] += v n += 1 off += len(line) if n >= MAX_RECORDS or off - start >= MAX_BYTES: blocks.append((agent, start, off - start, n, lo, hi)) total += n start, n, lo, hi = off, 0, None, None if n: blocks.append((agent, start, off - start, n, lo, hi)) total += n los = [b[4] for b in blocks if b[4] is not None] his = [b[5] for b in blocks if b[5] is not None] meta = (agent, lane, off, total, min(los) if los else None, max(his) if his else None) return meta, blocks, (agent, *stats), [(agent, hr, *v) for hr, v in sorted(hours.items())]
def main(src, out, repo=None): jobs = [] for lane in sorted(os.listdir(src)): d = os.path.join(src, lane) if os.path.isdir(d): jobs += [(lane, fn[:-6], os.path.join(d, fn)) for fn in sorted(os.listdir(d)) if fn.endswith(".jsonl")] print(f"{len(jobs)} files", flush=True) db = sqlite3.connect(out) db.executescript(""" CREATE TABLE trace_files(agent TEXT PRIMARY KEY, lane TEXT, size INT, records INT, first_ts REAL, last_ts REAL); CREATE TABLE trace_blocks(agent TEXT, offset INT, length INT, records INT, min_ts REAL, max_ts REAL); CREATE TABLE agent_stats(agent TEXT PRIMARY KEY, model_calls INT, tool_calls INT, input_tokens INT, output_tokens INT, reasoning_tokens INT); CREATE TABLE agent_hours(agent TEXT, hour INT, model_calls INT, tool_calls INT, input_tokens INT, output_tokens INT); """) with Pool(int(os.environ.get("WORKERS", "16"))) as pool: for i, (meta, blocks, stats, hours) in enumerate(pool.imap_unordered(index_file, jobs), 1): db.execute("INSERT INTO trace_files VALUES (?,?,?,?,?,?)", meta) db.executemany("INSERT INTO trace_blocks VALUES (?,?,?,?,?,?)", blocks) db.execute("INSERT INTO agent_stats VALUES (?,?,?,?,?,?)", stats) db.executemany("INSERT INTO agent_hours VALUES (?,?,?,?,?,?)", hours) if i % 50 == 0: db.commit(); print(f"{i}/{len(jobs)}", flush=True) db.execute("CREATE INDEX blocks_agent ON trace_blocks(agent, offset)") db.execute("CREATE INDEX hours_agent ON agent_hours(agent, hour)") db.commit(); db.execute("VACUUM"); db.close() print("size", os.path.getsize(out), flush=True) if repo: from huggingface_hub import upload_file upload_file(path_or_fileobj=out, path_in_repo="data/traces.sqlite", repo_id=repo, repo_type="space", commit_message="Add trace time index") print("uploaded", flush=True)
if __name__ == "__main__": main(*sys.argv[1:])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748# PyBot Data Explorer
> Read-only JSON API over the PyBot swarm run: 1,000 agents wrote a pure-Python chatbot through> 8,609 commits on main (cut at commit 24cbc04, 2026-11-13T10:17:13Z). Times are ISO 8601 UTC.> Full schema: /openapi.json (interactive: /docs). Lists take limit/offset and return next_offset (null at the end).
## Agents- GET /api/agents?sort=&order=&lane=&limit=&offset= : all 1,000 agents with lane, trace stats (model_calls, tool_calls, input/output/reasoning tokens, records, first/last ts) and board posts, PRs opened/merged, reviews given; sort by any of those- GET /api/agents/{name} : one agent's stats, hourly series (model calls, tool calls, input and output tokens), busiest hour, PRs, reviews (review_list), last 20 posts, trace file source- GET /api/highlights : run totals, the top agent for posts / reasoning tokens / PRs merged / reviews / tool calls (with hourly sparkline), and key moments derived from the data
## Commits and scores- GET /api/commits?author=&pr=&text=&since=&until=&scored=&limit=&offset= : commits, newest first, with SmolTalkBench win rate (lp_win_rate, standard_error; null if not scored)- GET /api/commits/{sha} : one commit (sha prefix ok): metadata, score, approvers, PR summary, prev_sha/next_sha- GET /api/commits/{sha}/diff?patch= : files changed (+/-) and the unified patch (cut at 2 MB); patch=false for the file list only- GET /api/commits/{sha}/file?path= : a file's text at that commit- GET /api/scores : {columns, rows} for every scored commit in commit order (the score curve)
## Pull requests- GET /api/prs/{n} : PR with description, state, timestamps, approvers, merge commit- GET /api/prs/{n}/reviews : every review: reviewer, ts, head_sha, verdict, comment- GET /api/prs/{n}/messages?reason=mention|author_window&newest_first= : linked board posts (count in /api/prs/{n} message_count)- GET /api/prs/{n}/traces : linked trace windows (author + each reviewer), each with a ready /api/traces URL
## Traces, messages, agents- GET /api/traces/{agent}?from=&to=&limit=&cursor=&messages_only=&max_chars= : the agent's session records in [from, to]; pass next_cursor back as cursor; long strings are clipped to max_chars- GET /api/messages/search?q=&channel=&author= : full-text search over board posts (SQLite FTS5 syntax: words, "phrases", OR, prefix*)- GET /api/messages/{id} : a post plus its thread (root and the 50 replies either side)- GET /api/agents/{name} : lane, trace extent, PRs authored, reviews given, post count
## Linking rules- Author trace window: PR opened minus 10 min to merged (or closed, or the cutoff if still open).- Reviewer window: review time plus or minus 15 min.- PR messages: posts naming the PR ("#14943", "PR 14943", "pr:14943", "refs/pr/14943") from its opening to a day after it ended, plus the author's posts inside the author window.
Example: GET /api/commits/24cbc04 then /api/prs/14943/traces.
## Data sourcesEverything is the scrubbed release data, cut at commit 24cbc04 (the board export runs ~1 day longer). API answers carry a `source` URL where a direct link exists (commit, file in a diff, merged PR, trace file, board post).- Agent traces: bucket https://huggingface.co/buckets/HuggingFaceSwarms/pybot-traces (traces/<lane>/<agent>.jsonl, traces/_manifest.jsonl, README, Apache-2.0). File URL: https://huggingface.co/buckets/HuggingFaceSwarms/pybot-traces/resolve/traces/<lane>/<agent>.jsonl `hf buckets cp hf://buckets/HuggingFaceSwarms/pybot-traces/traces/_manifest.jsonl .` `hf buckets sync hf://buckets/HuggingFaceSwarms/pybot-traces/traces/safety ./traces/safety`- Message board: Space https://huggingface.co/spaces/HuggingFaceSwarms/pybot-msgboard (data/, start with data/manifest.json; web/reader.js decodes chunks). Viewer post link: https://huggingfaceswarms-pybot-msgboard.hf.space/#msg/<id> `hf download HuggingFaceSwarms/pybot-msgboard --repo-type space --local-dir pybot-msgboard`- Commits: dataset https://huggingface.co/datasets/HuggingFaceSwarms/pybot-commits (git history to 24cbc04). Commit: /commit/<sha>; file: /blob/<sha>/<path> `git clone https://huggingface.co/datasets/HuggingFaceSwarms/pybot-commits`- PyBot Data Explorer tables: https://huggingface.co/spaces/HuggingFaceSwarms/pybot-explorer/tree/main/data (explorer.sqlite: commits, prs, reviews, messages + FTS, agents, pr_traces, pr_messages; traces.sqlite: trace time index) `hf download HuggingFaceSwarms/pybot-explorer --repo-type space --include "data/*" --local-dir pybot-explorer`123fastapi==0.165.0uvicorn==0.55.0huggingface_hub==2.5.0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222'use strict';// Agents view: the home page (totals, highlights, contribution graph, moments) and one page per agent.// Uses helpers from app.js (esc, api, time, errBox, go, turn).
const fmt = v => v == null ? '—' : v >= 1e4 ? d3.format('.3~s')(v).replace('G', 'B') : d3.format(',')(v);const METRICS = [['total_tokens', 'Total tokens'], ['output_tokens', 'Output tokens'], ['reasoning_tokens', 'Reasoning tokens'], ['model_calls', 'Model calls'], ['posts', 'Board posts']];const hourOf = iso => new Date(Math.floor(Date.parse(iso) / 3600e3) * 3600e3).toISOString().replace('.000Z', 'Z');const cssVar = k => getComputedStyle(document.documentElement).getPropertyValue(k).trim();const agentLink = (name, at) => `/agent/${encodeURIComponent(name)}${at ? `?at=${hourOf(at)}` : ''}`;let highlightsP = null, agentsP = null;
async function agentsHome() { document.title = 'PyBot Data Explorer'; $app.className = 'wide'; $app.innerHTML = ` <div class="label">The PyBot swarm</div><h1>Agents and their traces</h1> <p class="intro" id="totals"> </p> <section class="hl" id="hl"><p class="muted">Loading…</p></section> <section><div class="sec-head"><h2>Every agent</h2> <div class="chips" role="group" aria-label="Colour by">${METRICS.map(([k, l], i) => `<button type="button" data-m="${k}" aria-pressed="${i === 0}">${l}</button>`).join('')}</div></div> <div class="contrib" id="contrib"><div class="tip"></div></div><div class="legend" id="legend"></div></section> <section><h2>Moments</h2><ol class="moments" id="moments"><li class="muted">Loading…</li></ol></section>`; highlightsP = highlightsP || api('/api/highlights'); agentsP = agentsP || api('/api/agents?limit=1000'); highlightsP.then(renderHighlights).catch(e => { document.getElementById('hl').innerHTML = errBox(e); }); agentsP.then(d => drawContrib(d.items)).catch(e => { document.getElementById('contrib').innerHTML = errBox(e); });}
function renderHighlights(d) { const t = d.totals, el = document.getElementById('hl'); if (!el) return; document.getElementById('totals').textContent = `${d3.format(',')(t.agents)} agents · ${d3.format(',')(t.traces)} traces · ${fmt(t.model_calls)} model calls · ${fmt(t.tokens)} tokens`; el.innerHTML = d.highlights.map(h => ` <a class="hcard" data-nav href="${agentLink(h.agent, h.busiest_hour)}"> <span class="label">${esc(h.title)}</span><span class="hv">${fmt(h.value)}</span> <span><b>${esc(h.agent)}</b> <span class="muted">${esc(h.lane || 'no trace')}</span></span> ${spark(h.spark)}<span class="go">open trace →</span></a>`).join(''); document.getElementById('moments').innerHTML = d.moments.map(m => ` <li><span class="muted">${time(m.ts).slice(0, 16)}</span> <span>${esc(m.text)}</span> <a data-nav href="${agentLink(m.agent, m.ts)}">${esc(m.agent)}'s trace →</a>${m.sha ? ` <a data-nav href="/commits?sha=${m.sha}">commit</a>` : ''}</li>`).join('');}
function spark(values) { const n = values.length, max = d3.max(values) || 1, peak = values.indexOf(max); const path = d3.line().x((v, i) => i).y(v => 28 - (v / max) * 26)(values); return `<svg class="spark" viewBox="0 0 ${n} 30" preserveAspectRatio="none" aria-hidden="true"> <path d="${path}" vector-effect="non-scaling-stroke"/><line x1="${peak}" x2="${peak}" y1="0" y2="30" vector-effect="non-scaling-stroke"/></svg>`;}
function drawContrib(items) { const el = document.getElementById('contrib'); if (!el) return; const tip = el.querySelector('.tip'), chips = document.querySelector('.sec-head .chips'); const lanes = d3.groups(items, a => a.lane || 'no trace').sort((a, b) => (a[0] === 'no trace') - (b[0] === 'no trace') || b[1].length - a[1].length); let metric = 'total_tokens'; const draw = () => { el.querySelector('svg')?.remove(); const S = 11, P = 13, W = el.clientWidth, cols = Math.max(10, Math.floor((W + 2) / P)); const vals = items.filter(a => a.has_trace && a[metric] > 0).map(a => a[metric]); const color = d3.scaleSequentialLog(d3.interpolateRgbBasis([cssVar('--ramp0'), cssVar('--ramp1'), cssVar('--ramp2')])) .domain([d3.min(vals) || 1, d3.max(vals) || 10]); let y = 0; const blocks = lanes.map(([lane, list]) => { const sorted = list.slice().sort((a, b) => (b[metric] || 0) - (a[metric] || 0)), top = y + 18; y = top + Math.ceil(sorted.length / cols) * P + 10; return { lane, list: sorted, top }; }); const svg = d3.select(el).insert('svg', '.tip').attr('viewBox', `0 0 ${W} ${y}`).attr('height', y) .attr('role', 'img').attr('aria-label', `One square per agent, grouped by lane, coloured by ${metric.replace('_', ' ')}`); svg.append('defs').html(`<pattern id="hatch" width="4" height="4" patternUnits="userSpaceOnUse" patternTransform="rotate(45)"> <rect width="4" height="4" fill="${cssVar('--page-bg')}"/><line x1="0" y1="0" x2="0" y2="4" stroke="${cssVar('--muted-color')}" stroke-width="1.5"/></pattern>`); for (const b of blocks) { svg.append('text').attr('class', 'lane').attr('x', 0).attr('y', b.top - 6).text(`${b.lane.toUpperCase()} · ${b.list.length}`); svg.append('g').selectAll('rect').data(b.list).join('rect') .attr('x', (a, i) => (i % cols) * P).attr('y', (a, i) => b.top + Math.floor(i / cols) * P).attr('width', S).attr('height', S) .attr('fill', a => !a.has_trace ? 'url(#hatch)' : a[metric] > 0 ? color(a[metric]) : cssVar('--ramp0')) .attr('tabindex', 0).attr('role', 'link').attr('aria-label', a => `${a.name}, ${a.lane || 'no trace'}`) .on('pointerenter focus', (ev, a) => { ev.target.classList.add('on'); tip.innerHTML = `<b>${esc(a.name)}</b> · ${esc(a.lane || 'no trace released')}<br>${METRICS.find(m => m[0] === metric)[1]}: <b>${a.has_trace || metric === 'posts' ? fmt(a[metric]) : 'no trace released'}</b>`; const r = ev.target.getBoundingClientRect(), box = el.getBoundingClientRect(); tip.style.left = Math.max(0, Math.min(r.left - box.left + 16, el.clientWidth - tip.offsetWidth)) + 'px'; tip.style.top = (r.top - box.top + 16) + 'px'; tip.style.opacity = 1; }) .on('pointerleave blur', ev => { ev.target.classList.remove('on'); tip.style.opacity = 0; }) .on('click keydown', (ev, a) => { if (ev.type === 'click' || ev.key === 'Enter') go(agentLink(a.name)); }); } legend(color, vals.length ? [d3.min(vals), d3.max(vals)] : null); }; chips.onclick = e => { const b = e.target.closest('button[data-m]'); if (!b) return; metric = b.dataset.m; chips.querySelectorAll('button').forEach(x => x.setAttribute('aria-pressed', x === b)); draw(); }; draw(); window.redrawChart = draw; new ResizeObserver(() => window.redrawChart === draw && draw()).observe(el);}
function legend(color, range) { const el = document.getElementById('legend'); if (!el || !range) return; const stops = d3.range(0, 1.01, 0.1).map(t => `<stop offset="${t}" stop-color="${color(Math.exp(Math.log(range[0]) + t * (Math.log(range[1]) - Math.log(range[0]))))}"/>`).join(''); el.innerHTML = `<svg width="210" height="34" aria-hidden="true"><defs><linearGradient id="ramp">${stops}</linearGradient></defs> <rect x="0" y="2" width="200" height="10" fill="url(#ramp)"/> <text x="0" y="28">${fmt(range[0])}</text><text x="100" y="28" text-anchor="middle">log scale</text><text x="200" y="28" text-anchor="end">${fmt(range[1])}</text></svg> <span class="nt"><svg width="11" height="11" aria-hidden="true"><rect width="11" height="11" fill="url(#hatch)"/></svg> no trace released</span>`;}
// ---------- agent page ----------async function agentPage(name) { $app.innerHTML = '<p class="muted">Loading…</p>'; let a; try { a = await api('/api/agents/' + encodeURIComponent(name)); } catch (e) { $app.innerHTML = errBox(e); return; } document.title = `${a.name} · PyBot Data Explorer`; const rows = a.hours.rows, at = new URLSearchParams(location.search).get('at'); const stat = (k, v) => `<div><b>${k}</b>${v}</div>`; $app.innerHTML = ` <div class="nav-row"><a data-nav href="/">← agents</a></div> <div class="label">Agent · ${esc(a.lane || 'lane unknown')}</div><h1>${esc(a.name)}</h1> <p class="meta-line">${a.has_trace ? `trace ${time(a.first_ts).slice(0, 16)} → ${time(a.last_ts).slice(0, 16)} · ${d3.format(',')(a.records)} records · <a href="${a.source}" target="_blank" rel="noopener">trace file in the bucket ↗</a>` : 'no trace released for this agent'}</p> <div class="meta">${stat('Model calls', fmt(a.model_calls))}${stat('Tool calls', fmt(a.tool_calls))}${stat('Input tokens', fmt(a.input_tokens))} ${stat('Output tokens', fmt(a.output_tokens))}${stat('Reasoning tokens', fmt(a.reasoning_tokens))}${stat('Board posts', fmt(a.posts))} ${stat('PRs opened / merged', `${a.prs_opened} / ${a.prs_merged}`)}${stat('Reviews given', fmt(a.reviews))}</div> ${a.has_trace ? `<h2>Activity by hour</h2><div class="astrip" id="astrip"><div class="tip"></div></div> <section class="tb"><header><button type="button" id="hprev" aria-label="Previous active hour">◀</button> <h3 id="hlabel"></h3><button type="button" id="hnext" aria-label="Next active hour">▶</button></header> <div class="turns" id="tturns"></div><button class="more" id="tmore" hidden>More</button></section>` : ''} <div class="alists"> <section><h2>PRs · ${a.prs.length}</h2>${listCap(a.prs, p => `<div class="one"><a data-nav href="${p.merged_sha ? `/commits?sha=${p.merged_sha}` : `/pr/${p.pr}`}">#${p.pr}</a> <span class="muted">${esc(p.state)}</span> ${esc(p.title)}</div>`)}</section> <section><h2>Reviews · ${a.review_list.length}</h2>${listCap(a.review_list.slice().reverse(), r => `<div class="one"><a data-nav href="/pr/${r.pr}">#${r.pr}</a> <span class="verdict ${esc(r.verdict)}">${r.verdict === 'approve' ? 'approve' : 'changes'}</span> <span class="muted">${time(r.ts).slice(0, 16)}</span></div>`)}</section> <section><h2>Recent posts</h2>${listCap(a.recent_posts, m => `<div class="one"><a data-nav href="/message/${m.id}">#${esc(m.channel)}</a> <span class="muted">${time(m.ts).slice(5, 16)}</span> ${esc(firstLine(m.body))}</div>`)}</section> </div>`; if (!a.has_trace || !rows.length) return; const active = rows.map(r => r[0]); let hour = at && active.includes(hourOf(at)) ? hourOf(at) : at ? active.find(h => h >= hourOf(at)) || a.busiest_hour : a.busiest_hour; const strip = drawStrip(a, h => show(h)); const show = h => { hour = h; const q = new URLSearchParams(location.search); q.set('at', h); history.replaceState(null, '', location.pathname + '?' + q); strip(h); document.getElementById('hlabel').textContent = `${time(h).slice(0, 13)}:00 – ${time(new Date(Date.parse(h) + 3600e3).toISOString()).slice(11, 13)}:00 UTC`; const i = active.indexOf(h); document.getElementById('hprev').disabled = i <= 0; document.getElementById('hnext').disabled = i < 0 || i >= active.length - 1; loadHour(a.name, h); }; document.getElementById('hprev').onclick = () => show(active[active.indexOf(hour) - 1]); document.getElementById('hnext').onclick = () => show(active[active.indexOf(hour) + 1]); show(hour);}
const listCap = (items, row, n = 30) => items.length ? items.slice(0, n).map(row).join('') + (items.length > n ? `<p class="muted">+${items.length - n} more</p>` : '') : '<p class="muted">None.</p>';
let traceSeq = 0;async function loadHour(name, h) { const seq = ++traceSeq, box = document.getElementById('tturns'), more = document.getElementById('tmore'); box.innerHTML = '<p class="muted">Loading…</p>'; more.hidden = true; let cursor = 0; const load = async first => { const to = new Date(Date.parse(h) + 3600e3 - 1).toISOString(); let d; for (let k = 0; k < 10; k++) { // keep reading past pages that come back empty d = await api(`/api/traces/${encodeURIComponent(name)}?${new URLSearchParams({ from: h, to, limit: 40, cursor, messages_only: 'true' })}`); cursor = d.next_cursor; if (d.records.length || cursor == null) break; } if (seq !== traceSeq) return; if (first) box.innerHTML = ''; box.insertAdjacentHTML('beforeend', d.records.map(turn).join('') || (first ? '<p class="muted">No messages in this hour.</p>' : '')); more.hidden = cursor == null; }; more.onclick = () => load(false).catch(e => box.insertAdjacentHTML('beforeend', errBox(e))); try { await load(true); } catch (e) { if (seq === traceSeq) box.innerHTML = errBox(e); }}
function drawStrip(a, onPick) { const el = document.getElementById('astrip'), tip = el.querySelector('.tip'); const t0 = Date.parse(a.run.first_hour), n = a.run.hours, byHour = new Map(a.hours.rows.map(r => [r[0], r])); let selected = null, svg, x; const draw = () => { el.querySelector('svg')?.remove(); const W = el.clientWidth, H = 64; x = d3.scaleLinear().domain([0, n]).range([0, W]); const y = d3.scaleLinear().domain([0, d3.max(a.hours.rows, r => r[4]) || 1]).range([H - 14, 4]); svg = d3.select(el).insert('svg', '.tip').attr('viewBox', `0 0 ${W} ${H}`).attr('height', H) .attr('role', 'img').attr('aria-label', 'Output tokens per hour over the run; click an hour to read the trace'); svg.append('line').attr('class', 'base').attr('x1', 0).attr('x2', W).attr('y1', H - 14).attr('y2', H - 14); svg.append('g').selectAll('rect').data(a.hours.rows).join('rect') .attr('x', r => x((Date.parse(r[0]) - t0) / 3600e3)).attr('width', Math.max(1, x(1) - x(0) - (W > 600 ? 1 : 0))) .attr('y', r => y(r[4])).attr('height', r => H - 14 - y(r[4])).attr('class', r => r[0] === selected ? 'sel' : ''); for (const tk of d3.timeDay.range(new Date(t0), new Date(t0 + n * 3600e3), W < 500 ? 4 : 2)) svg.append('text').attr('x', x((tk - t0) / 3600e3)).attr('y', H - 2).text(d3.utcFormat('%b %-d')(tk)); svg.append('rect').attr('width', W).attr('height', H).attr('fill', 'transparent').style('cursor', 'pointer') .on('pointermove', ev => { const h = new Date(t0 + Math.floor(x.invert(d3.pointer(ev)[0])) * 3600e3).toISOString().replace('.000Z', 'Z'), r = byHour.get(h); tip.innerHTML = `${time(h).slice(0, 13)}:00 UTC<br>${r ? `${fmt(r[1])} model calls · ${fmt(r[4])} output tokens` : 'no activity'}`; tip.style.left = Math.min(d3.pointer(ev)[0] + 12, el.clientWidth - tip.offsetWidth) + 'px'; tip.style.top = '66px'; tip.style.opacity = 1; }) .on('pointerleave', () => { tip.style.opacity = 0; }) .on('click', ev => { const i = Math.floor(x.invert(d3.pointer(ev)[0])), hours = a.hours.rows.map(r => r[0]); const target = new Date(t0 + i * 3600e3).toISOString().replace('.000Z', 'Z'); onPick(byHour.has(target) ? target : hours.reduce((b, h) => Math.abs(Date.parse(h) - Date.parse(target)) < Math.abs(Date.parse(b) - Date.parse(target)) ? h : b)); }); }; draw(); window.redrawChart = draw; new ResizeObserver(() => window.redrawChart === draw && draw()).observe(el); return h => { selected = h; svg.selectAll('g rect').attr('class', r => r[0] === h ? 'sel' : ''); };}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594'use strict';const $app = document.getElementById('app');const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));// "#N" in escaped text becomes a link to PR N; not after '>', '=', '"', '/', '&' or a word character,// so attributes, entities, URLs and existing link text stay as they are.const MAX_PR = 15745; // shortcut: highest PR number in the data; the 41 unused numbers below it open a "not found" pageconst prLinks = h => h.replace(/(^|[^\w&;\/>="])#(\d{1,5})\b/g, (m, pre, n) => +n >= 1 && +n <= MAX_PR ? `${pre}<a data-nav href="/pr/${n}">#${n}</a>` : m);// Escaped text with `code`, **bold** and PR links; everything else stays literal.const rich = s => prLinks(esc(s).replace(/`([^`\n]+)`/g, '<code>$1</code>')) .replace(/\*\*([^*\n]+)\*\*/g, '<b>$1</b>');// Small Markdown renderer for agent-written text: every character is escaped first, so no raw HTML gets through.const mdInline = s => { const codes = []; // code spans go out first so nothing inside them is formatted return prLinks(esc(s.replace(/`([^`\n]+)`/g, (_, c) => `\u0000${codes.push(c) - 1}\u0000`)) .replace(/\[([^\]\n]+)\]\((https?:\/\/[^\s)]+)\)/g, '<a href="$2" rel="noopener nofollow" target="_blank">$1</a>')) .replace(/\*\*([^*\n]+)\*\*/g, '<b>$1</b>') .replace(/(^|[\s(])\*([^*\s][^*\n]*)\*/g, '$1<i>$2</i>') .replace(/\u0000(\d+)\u0000/g, (_, i) => `<code>${esc(codes[i])}</code>`);};function md(src) { const out = [], lines = String(src ?? '').split('\n'); let para = [], list = null; const flush = () => { if (para.length) out.push(`<p>${mdInline(para.join('\n'))}</p>`); if (list) out.push(`</${list}>`); para = []; list = null; }; for (let i = 0; i < lines.length; i++) { const l = lines[i], item = l.match(/^\s*([-*+]|\d+[.)])\s+(.*)$/), h = l.match(/^(#{1,6})\s+(.*)$/); if (/^\s*```/.test(l)) { flush(); const code = []; while (++i < lines.length && !/^\s*```/.test(lines[i])) code.push(lines[i]); out.push(`<pre><code>${esc(code.join('\n'))}</code></pre>`); } else if (h) { flush(); out.push(`<h4>${mdInline(h[2])}</h4>`); } else if (item) { const kind = /\d/.test(item[1]) ? 'ol' : 'ul'; if (para.length || list !== kind) { flush(); out.push(`<${kind}>`); list = kind; } out.push(`<li>${mdInline(item[2])}</li>`); } else if (/^>\s?/.test(l)) { flush(); out.push(`<blockquote>${mdInline(l.replace(/^>\s?/, ''))}</blockquote>`); } else if (!l.trim()) flush(); else if (list && /^\s+\S/.test(l)) out[out.length - 1] = out[out.length - 1].replace(/<\/li>$/, ' ' + mdInline(l.trim()) + '</li>'); else { if (list) flush(); para.push(l); } } flush(); return out.join('');}const time = t => t ? t.replace('T', ' ').slice(0, 19) : '';const short = s => s ? s.slice(0, 7) : '';const api = async url => { const r = await fetch(url); if (!r.ok) throw new Error((await r.json().catch(() => ({}))).detail || r.statusText); return r.json();};const errBox = e => `<p class="err">${esc(e.message || e)}</p>`;
document.getElementById('theme').onclick = () => { const dark = document.documentElement.dataset.theme ? document.documentElement.dataset.theme === 'dark' : matchMedia('(prefers-color-scheme: dark)').matches; document.documentElement.dataset.theme = dark ? 'light' : 'dark'; try { localStorage.setItem('theme', document.documentElement.dataset.theme); } catch (e) {} if (window.redrawChart) window.redrawChart();};
let navs = 0; // in-app navigations, so 'back' knows whether there is somewhere to go back tofunction go(url) { navs++; history.pushState(null, '', url); route(); }document.addEventListener('click', e => { const a = e.target.closest('a[data-nav]'); if (a && !e.metaKey && !e.ctrlKey) { e.preventDefault(); go(a.getAttribute('href')); }});window.addEventListener('popstate', route);
function route() { window.redrawChart = null; ex = null; $app.className = ''; const path = location.pathname, tab = path === '/' || path.startsWith('/agent/') ? 'agents' : path.startsWith('/commit') || path.startsWith('/pr/') ? 'commits' : ''; document.querySelectorAll('.maintabs a').forEach(a => a.setAttribute('aria-selected', a.dataset.tab === tab)); const p = location.pathname, m = p.match(/^\/commit\/([0-9a-f]+)/), mm = p.match(/^\/message\/(\d+)/), mp = p.match(/^\/pr\/(\d+)/); if (m) return commitPage(m[1]); if (mp) return prPage(+mp[1]); if (p === '/data') return dataPage(); if (mm) return messagePage(+mm[1]); const ma = p.match(/^\/agent\/([\w.-]+)/); if (ma) return agentPage(decodeURIComponent(ma[1])); if (p === '/commits') return homePage(); agentsHome();}
// ---------- home: the explorer ----------const DEFAULT_SHA = '24cbc0439e07fd015c0747ab3be6e782a42b5c5b'; // the final commit of the runconst BASELINES = [['SmolLM-1.7B', 40.6], ['SmolLM-360M', 26.6], ['SmolLM-135M', 10.1]];let scoresP = null; // the score curve, fetched oncelet ex = null; // explorer state: { sha, commit, seq, strip, view }
async function homePage() { document.title = 'PyBot Data Explorer'; const params = new URLSearchParams(location.search); $app.className = 'wide'; $app.innerHTML = ` <div class="strip" id="strip"><div class="tip"></div></div> <div class="explorer"> <aside class="clist" id="clist"> <button class="clist-toggle" type="button" aria-expanded="false">Commits ▾</button> <div class="clist-body"> <form class="clist-filters" id="f"> <input type="search" name="text" placeholder="Search titles" aria-label="Search commit and PR titles"> <input type="text" name="author" placeholder="Author" aria-label="Author"> </form> <ol id="rows"></ol> <button class="more" id="more" hidden>More</button> </div> </aside> <section class="sel" id="sel"></section> </div>`; ex = { sha: null, seq: 0, strip: null, view: params.get('view') }; initList(params); scoresP = scoresP || api('/api/scores').then(d => d.rows.map(r => Object.fromEntries(d.columns.map((c, i) => [c, r[i]])))); scoresP.then(initStrip).catch(e => document.getElementById('strip').innerHTML = errBox(e)); const want = params.get('sha') || ''; select(/^[0-9a-f]{4,40}$/.test(want) ? want : DEFAULT_SHA);}
document.addEventListener('keydown', e => { if (!ex || !ex.commit || e.target.closest('input, textarea, select') || e.metaKey || e.ctrlKey || e.altKey) return; if (e.key === 'Escape' && ex.view) { e.preventDefault(); setView(null); return; } const to = e.key === 'ArrowLeft' ? ex.commit.prev_sha : e.key === 'ArrowRight' ? ex.commit.next_sha : null; if (to) { e.preventDefault(); select(to); }});
function initList(params) { const form = document.getElementById('f'), rows = document.getElementById('rows'), more = document.getElementById('more'); const aside = document.getElementById('clist'), toggle = aside.querySelector('.clist-toggle'); toggle.onclick = () => toggle.setAttribute('aria-expanded', aside.classList.toggle('open')); form.text.value = params.get('text') || ''; form.author.value = params.get('author') || ''; let offset = 0, timer; const load = async () => { const q = new URLSearchParams({ limit: 100, offset }); if (form.text.value) q.set('text', form.text.value); if (form.author.value.trim()) q.set('author', form.author.value.trim()); const d = await api('/api/commits?' + q); rows.insertAdjacentHTML('beforeend', d.items.map(c => ` <li><a href="/commits?sha=${c.sha}" data-sha="${c.sha}" class="${c.sha === ex.sha ? 'on' : ''}"> <span class="l1"><b>${short(c.sha)}</b><span>${c.lp_win_rate != null ? c.lp_win_rate.toFixed(1) + '%' : ''}</span></span> <span class="l2">${esc(c.pr_title || c.title)}</span> <span class="l3">${c.pr ? '#' + c.pr + ' · ' : ''}${esc(c.author)} · ${time(c.ts).slice(5, 16)}</span></a></li>`).join('') || (offset ? '' : '<li class="muted">No commits match.</li>')); more.hidden = d.next_offset == null; offset = d.next_offset; }; const reload = () => { rows.innerHTML = ''; offset = 0; load().catch(err => rows.innerHTML = errBox(err)); }; form.oninput = () => { clearTimeout(timer); timer = setTimeout(reload, 300); }; form.onsubmit = e => { e.preventDefault(); reload(); }; rows.onclick = e => { const a = e.target.closest('a[data-sha]'); if (!a || e.metaKey || e.ctrlKey) return; e.preventDefault(); select(a.dataset.sha); aside.classList.remove('open'); toggle.setAttribute('aria-expanded', 'false'); }; more.onclick = () => load(); reload();}
function initStrip(pts) { const el = document.getElementById('strip'); if (!el) return; const tip = el.querySelector('.tip'), bis = d3.bisector(p => p.idx).center; const draw = () => { el.querySelector('svg')?.remove(); const W = el.clientWidth, H = 80, m = { t: 8, r: 118, b: 8, l: 8 }; const x = d3.scaleLinear().domain([0, d3.max(pts, p => p.idx)]).range([m.l, W - m.r]); const y = d3.scaleLinear().domain([0, 45]).range([H - m.b, m.t]); const svg = d3.select(el).insert('svg', '.tip').attr('viewBox', `0 0 ${W} ${H}`).attr('height', H) .attr('role', 'img').attr('aria-label', 'SmolTalkBench win rate by commit; click or drag to pick a commit, arrow keys step'); const base = svg.append('g').attr('class', 'base').selectAll('g').data(BASELINES).join('g'); base.append('line').attr('x1', m.l).attr('x2', W - m.r).attr('y1', b => y(b[1])).attr('y2', b => y(b[1])); base.append('text').attr('x', W - m.r + 12).attr('y', b => y(b[1]) + 3).text(b => `${b[0].replace('SmolLM-', 'SmolLM ')} ${b[1]}%`); svg.append('path').attr('class', 'series').attr('d', d3.line().x(p => x(p.idx)).y(p => y(p.lp_win_rate))(pts)); const cur = svg.append('g').attr('class', 'cursor'); cur.append('line').attr('y1', m.t - 4).attr('y2', H - m.b + 4); cur.append('circle').attr('r', 4); const pick = ev => pts[bis(pts, x.invert(Math.max(m.l, Math.min(W - m.r, d3.pointer(ev, svg.node())[0]))))]; const place = (idx, score) => { cur.style('display', idx == null ? 'none' : null).select('line').attr('x1', x(idx)).attr('x2', x(idx)); cur.select('circle').style('display', score == null ? 'none' : null).attr('cx', x(idx)).attr('cy', y(score ?? 0)); }; ex.strip = { place }; if (ex.commit) place(ex.commit.idx, ex.commit.lp_win_rate); let dragging = false; const show = p => { tip.innerHTML = `<b>${short(p.sha)}</b>${p.pr ? ' · #' + p.pr : ''} · ${esc(p.author)}<br>win rate <b>${p.lp_win_rate.toFixed(2)}%</b> · ${time(p.ts).slice(0, 16)}`; const scale = el.clientWidth / W, px = x(p.idx) * scale; tip.style.left = Math.max(0, Math.min(px + 12, el.clientWidth - tip.offsetWidth - 4)) + 'px'; tip.style.top = H + 4 + 'px'; tip.style.opacity = 1; }; svg.append('rect').attr('x', 0).attr('y', 0).attr('width', W - m.r + 4).attr('height', H) .attr('fill', 'transparent').style('cursor', 'ew-resize').style('touch-action', 'pan-y') .on('pointerdown', ev => { dragging = true; ev.target.setPointerCapture(ev.pointerId); const p = pick(ev); place(p.idx, p.lp_win_rate); show(p); }) .on('pointermove', ev => { const p = pick(ev); show(p); if (dragging) place(p.idx, p.lp_win_rate); }) .on('pointerup', ev => { if (dragging) { dragging = false; select(pick(ev).sha); } }) .on('pointerleave pointercancel', () => { dragging = false; tip.style.opacity = 0; if (ex.commit) place(ex.commit.idx, ex.commit.lp_win_rate); }); }; draw(); window.redrawChart = draw; new ResizeObserver(() => window.redrawChart === draw && draw()).observe(el);}
const VIEWS = [['reviews', 'Reviews'], ['traces', 'Traces'], ['diff', 'Diff'], ['messages', 'Messages']];
async function select(sha) { const seq = ++ex.seq, sel = document.getElementById('sel'); let c; try { c = await api('/api/commits/' + sha); } catch (e) { sel.innerHTML = errBox(e); return; } if (seq !== ex.seq || !sel.isConnected) return; ex.sha = c.sha; ex.commit = c; document.querySelectorAll('#rows a.on').forEach(a => a.classList.remove('on')); const row = document.querySelector(`#rows a[data-sha="${c.sha}"]`); if (row) { row.classList.add('on'); row.scrollIntoView({ block: 'nearest' }); } ex.strip?.place(c.idx, c.lp_win_rate); const pr = c.pr_info; document.title = `${short(c.sha)} · PyBot Data Explorer`; sel.innerHTML = ` <header class="sel-head"> <div class="label">${pr ? `PR #${pr.pr} title` : 'Commit message'}</div><h1>${esc(pr ? pr.title : c.title)}</h1> <p class="meta-line"><b>${short(c.sha)}</b> · ${pr ? `PR #${pr.pr} · ` : ''}${esc(c.author)} · ${time(c.ts).slice(0, 16)} ${c.approvers ? ` · approved by ${esc(c.approvers.join(', '))}` : ''} · ${c.lp_win_rate != null ? `win rate <span class="score">${c.lp_win_rate.toFixed(2)}%</span> ± ${c.standard_error.toFixed(2)}` : 'not scored'} · <a href="${c.source}" target="_blank" rel="noopener">commit on the Hub ↗</a> · <a data-nav href="/commit/${c.sha}">Open full commit view →</a></p> <p class="muted keys">${c.prev_sha ? `<a href="/commits?sha=${c.prev_sha}" data-sha="${c.prev_sha}">← older</a>` : ''} ${c.next_sha ? `<a href="/commits?sha=${c.next_sha}" data-sha="${c.next_sha}">newer →</a>` : ''} <span class="hide-sm">(or ← → keys)</span></p> </header> <div id="views"></div>`; sel.querySelector('.keys').onclick = e => { const a = e.target.closest('a[data-sha]'); if (a) { e.preventDefault(); select(a.dataset.sha); } }; setView(ex.view);}
// view = null shows the 2x2 grid of summaries; a view name shows that panel in full with tabs for the others.function setView(view) { ex.view = VIEWS.some(v => v[0] === view) ? view : null; const q = new URLSearchParams(location.search); q.set('sha', ex.sha); if (ex.view) q.set('view', ex.view); else q.delete('view'); history.replaceState(null, '', '/commits?' + q); const box = document.getElementById('views'), c = ex.commit, seq = ex.seq; const ok = () => seq === ex.seq && box.isConnected && ex.view === view; const fill = (el, p) => p.catch(e => { if (ok()) el.innerHTML = errBox(e); }); const noPr = el => { el.innerHTML = '<p class="muted">Pushed directly, without a pull request.</p>'; return Promise.resolve(); }; if (!ex.view) { box.innerHTML = `<div class="grid4">${VIEWS.map(([k, l]) => ` <section class="sum" data-v="${k}"><header><h2><a href="?sha=${c.sha}&view=${k}" data-v="${k}">${l}</a></h2> <button type="button" data-v="${k}">Expand</button></header><div class="sbody"><p class="muted">Loading…</p></div></section>`).join('')}</div>`; const body = k => box.querySelector(`.sum[data-v="${k}"] .sbody`); fill(body('diff'), sumDiff(body('diff'), ok, c)); for (const k of ['reviews', 'traces', 'messages']) fill(body(k), c.pr ? SUMS[k](body(k), ok, c.pr) : noPr(body(k))); } else { box.innerHTML = `<nav class="tabs vtabs" role="tablist">${VIEWS.map(([k, l]) => `<a role="tab" href="?sha=${c.sha}&view=${k}" data-v="${k}" aria-selected="${k === ex.view}">${l}</a>`).join('')} <button type="button" class="collapse" data-v="">Collapse</button></nav><section class="full" id="full"><p class="muted">Loading…</p></section>`; const el = document.getElementById('full'); if (ex.view === 'diff') fill(el, fullDiff(el, ok, c)); else fill(el, c.pr ? FULLS[ex.view](el, ok, c.pr) : noPr(el)); } box.onclick = e => { const t = e.target.closest('[data-v]'); if (t && !e.metaKey && !e.ctrlKey) { e.preventDefault(); setView(t.dataset.v || null); } };}
const firstLine = s => (String(s || '').split('\n').find(l => l.trim()) || '').replace(/\*\*|`/g, '').replace(/^\s*(#{1,6}\s+|>\s*)/, '').trim();const plural = (n, w) => `${n} ${w}${n === 1 ? '' : 's'}`;
const SUMS = { async reviews(el, ok, n) { const r = (await api(`/api/prs/${n}/reviews`)).items; if (!ok()) return; const count = v => r.filter(x => x.verdict === v).length; el.innerHTML = `<p class="sumline">${count('approve')} approve · ${count('request_changes')} request changes</p>` + (r.length > 6 ? r.slice(0, 5) : r).map(v => `<div class="one"><span class="verdict ${esc(v.verdict)}">${v.verdict === 'approve' ? 'approve' : 'changes'}</span> <b>${esc(v.reviewer)}</b> <span class="muted">${esc(firstLine(v.comment))}</span></div>`).join('') + (r.length > 6 ? `<div class="one muted">+${r.length - 5} more reviews</div>` : ''); }, async traces(el, ok, n) { const w = (await api(`/api/prs/${n}/traces`)).items; const author = w.find(x => x.role === 'author'), revs = new Set(w.filter(x => x.role === 'reviewer').map(x => x.agent)).size; if (!author?.has_trace) { if (ok()) el.innerHTML = '<p class="muted">No trace for the author.</p>'; return; } const { recs } = await lastTurns(author, 300); if (!ok()) return; el.innerHTML = `<p class="sumline">${esc(author.agent)} + ${plural(revs, 'reviewer')} · ${plural(recs.length, 'turn')} in the 20 min before the merge</p>` + recs.slice(-3).map(r => `<div class="one">${oneTurn(r)}</div>`).join(''); }, async messages(el, ok, n) { const [p, d] = await Promise.all([api('/api/prs/' + n), api(`/api/prs/${n}/messages?limit=3&newest_first=true`)]); if (!ok()) return; el.innerHTML = `<p class="sumline">${plural(p.message_count, 'linked post')}</p>` + d.items.map(m => `<div class="one"><b>${esc(m.author)}</b> <span class="muted">#${esc(m.channel)}</span> ${esc(firstLine(m.body))}</div>`).join(''); },};
async function sumDiff(el, ok, c) { const d = await api(`/api/commits/${c.sha}/diff?patch=false`); if (!ok()) return; el.innerHTML = `<p class="sumline">${plural(d.files.length, 'file')} · +${d3.sum(d.files, f => f.additions || 0)} −${d3.sum(d.files, f => f.deletions || 0)}</p>` + d.files.map(f => `<div class="one"><span>${esc(f.path)}</span> <span class="muted">+${f.additions ?? '?'} −${f.deletions ?? '?'}</span></div>`).join('');}
const FULLS = { reviews: (el, ok, n) => reviewsTab(el, n), messages: (el, ok, n) => messagesTab(el, n), traces: fullTraces };
async function fullDiff(el, ok, c) { const d = await api(`/api/commits/${c.sha}/diff`); if (!ok()) return; el.innerHTML = `<p class="muted">${plural(d.files.length, 'file')} · +${d3.sum(d.files, f => f.additions || 0)} −${d3.sum(d.files, f => f.deletions || 0)}</p>` + diffFiles(d, c.sha, 3);}
// Each file is a <details>; its lines are rendered only when opened, so big patches stay cheap.function diffFiles(d, sha, openFirst) { const parts = d.patch.split(/^(?=diff --git )/m).filter(Boolean); setTimeout(() => document.querySelectorAll('details.diff-file').forEach(det => { const fill = () => { if (!det.dataset.done) { det.dataset.done = 1; det.querySelector('pre').innerHTML = diffBody(parts[+det.dataset.i]); } }; if (det.open) fill(); det.addEventListener('toggle', fill); })); return parts.map((part, i) => { const head = part.slice(0, part.indexOf('\n')), path = (head.match(/ b\/(.*)$/) || [])[1] || head; const f = d.files.find(x => x.path === path) || {}; return `<details class="diff-file" data-i="${i}" ${i < openFirst ? 'open' : ''}><summary><b>${esc(path)}</b> <span class="muted">+${f.additions ?? '?'} −${f.deletions ?? '?'}</span> <a href="/api/commits/${sha}/file?path=${encodeURIComponent(path)}" target="_blank" rel="noopener">file</a> ${f.source ? `<a href="${esc(f.source)}" target="_blank" rel="noopener">Hub ↗</a>` : ''}</summary><pre></pre></details>`; }).join('') + (d.truncated ? '<p class="muted">Patch cut at 2 MB.</p>' : '');}const diffBody = part => part.split('\n').slice(1).map(l => { const cls = l.startsWith('@@') ? 'hunk' : l.startsWith('+') && !l.startsWith('+++') ? 'add' : l.startsWith('-') && !l.startsWith('---') ? 'del' : ''; return `<span class="${cls}">${esc(l)}</span>`;}).join('');
// The assistant turns in the 20 minutes before the moment that matters: the merge for the author, the review for a reviewer.async function lastTurns(x, maxChars) { const end = x.role === 'author' ? x.to_ts : new Date((Date.parse(x.from_ts) + Date.parse(x.to_ts)) / 2).toISOString(); const start = new Date(Math.max(Date.parse(x.from_ts), Date.parse(end) - 20 * 60e3)).toISOString(); let recs = [], cursor = 0; for (let k = 0; k < 4 && cursor != null; k++) { // shortcut: reads at most 4 pages (800 records) of those 20 minutes const q = new URLSearchParams({ from: start, to: end, limit: 200, cursor, messages_only: 'true', max_chars: maxChars }); const d = await api(`/api/traces/${encodeURIComponent(x.agent)}?${q}`); recs = recs.concat(d.records.filter(r => r.message?.role === 'assistant')); cursor = d.next_cursor; } return { recs, end };}
async function fullTraces(el, ok, n) { const w = (await api(`/api/prs/${n}/traces`)).items.filter(x => x.has_trace); if (!ok()) return; if (!w.length) { el.innerHTML = '<p class="muted">No traces for these agents.</p>'; return; } el.innerHTML = `<div class="chips">${w.map((x, i) => `<button type="button" aria-pressed="${i === 0}" data-i="${i}">${x.role === 'author' ? 'author' : 'reviewer'} · ${esc(x.agent)}</button>`).join('')}</div><div class="mt"></div>`; const box = el.querySelector('.mt'); const show = async i => { el.querySelectorAll('.chips button').forEach(b => b.setAttribute('aria-pressed', +b.dataset.i === i)); box.innerHTML = '<p class="muted">Loading…</p>'; const x = w[i], { recs: all, end } = await lastTurns(x, 1200), recs = all.slice(-12); if (!ok()) return; box.innerHTML = `<p class="muted">${esc(x.agent)} · last ${recs.length} turns before ${x.role === 'author' ? 'the merge' : 'the review'} (${time(end).slice(11, 16)}); click a turn to open it · <a data-nav href="/commit/${ex.sha}?tab=traces">full trace →</a> · <a href="${x.source}" target="_blank" rel="noopener">trace file in the bucket ↗</a></p>` + (recs.map(miniTurn).join('') || '<p class="muted">No turns in this window.</p>'); box.onclick = e => { const t = e.target.closest('.mturn'); if (t && !e.target.closest('a')) t.classList.toggle('open'); }; }; el.querySelector('.chips').onclick = e => { const b = e.target.closest('button'); if (b) show(+b.dataset.i).catch(err => box.innerHTML = errBox(err)); }; await show(0);}
const callLine = p => `<b>${esc(p.name)}</b> ${esc(String(p.arguments?.command ?? p.arguments?.path ?? JSON.stringify(p.arguments || {})).replace(/^cd \S+ && /, ''))}`;
function oneTurn(rec) { const parts = rec.message.content || [], call = parts.find(p => p.type === 'toolCall'), say = parts.find(p => p.type === 'text' && p.text.trim()) || parts.find(p => p.type === 'thinking'); return `<span class="muted">${time(rec.timestamp).slice(11, 16)}</span> ` + (call ? `<span class="tc">${callLine(call)}</span>` : esc(firstLine(say?.text ?? say?.thinking)));}
function miniTurn(rec) { const parts = rec.message.content || []; return `<div class="mturn" tabindex="0"><span class="muted">${time(rec.timestamp).slice(11, 19)}</span>` + parts.map(p => p.type === 'thinking' ? `<div class="clamp thinking">${esc(p.thinking)}</div>` : p.type === 'toolCall' ? `<div class="clamp1 tc">${callLine(p)}</div>` : `<div class="clamp">${esc(p.text)}</div>`).join('') + '</div>';}
// ---------- commit page ----------const TABS = [['diff', 'Diff'], ['reviews', 'PR & reviews'], ['traces', 'Traces'], ['messages', 'Messages']];
async function commitPage(sha) { $app.innerHTML = '<p class="muted">Loading…</p>'; let c; try { c = await api('/api/commits/' + sha); } catch (e) { $app.innerHTML = errBox(e); return; } const tab = new URLSearchParams(location.search).get('tab') || 'diff', pr = c.pr_info; document.title = `${short(c.sha)} · PyBot Data Explorer`; $app.innerHTML = ` <div class="nav-row"><a data-nav href="/commits?sha=${c.sha}">← commits</a> <span>${c.prev_sha ? `<a data-nav href="/commit/${c.prev_sha}?tab=${tab}">← older</a>` : ''} ${c.next_sha ? ` · <a data-nav href="/commit/${c.next_sha}?tab=${tab}">newer →</a>` : ''}</span></div> <div class="label">${pr ? `PR #${pr.pr} title` : 'Commit message'}</div><h1>${esc(pr ? pr.title : c.title)}</h1> <div class="meta"> <div><b>Commit</b>${c.sha} <a href="${c.source}" target="_blank" rel="noopener">on the Hub ↗</a></div> <div><b>Time</b>${time(c.ts)}</div> <div><b>Author</b>${esc(c.author)}</div> <div><b>PR</b>${pr ? `#${pr.pr} by ${esc(pr.author)}` : '—'}</div> <div><b>Approvers</b>${esc((c.approvers || []).join(', ') || '—')}</div> <div><b>Win rate</b>${c.lp_win_rate != null ? `<span class="score">${c.lp_win_rate.toFixed(2)}%</span> ± ${c.standard_error.toFixed(2)}` : 'not scored'}</div> </div> <nav class="tabs" role="tablist">${TABS.map(([k, l]) => `<a role="tab" data-nav href="/commit/${c.sha}?tab=${k}" aria-selected="${k === tab}">${l}</a>`).join('')}</nav> <section class="panel" id="panel"><p class="muted">Loading…</p></section>`; const panel = document.getElementById('panel'); const needPr = () => { if (!c.pr) throw new Error('This commit has no pull request (it was pushed directly).'); }; try { if (tab === 'diff') await diffTab(panel, c); else if (tab === 'reviews') { needPr(); await reviewsTab(panel, c.pr); } else if (tab === 'traces') { needPr(); await tracesTab(panel, c.pr); } else if (tab === 'messages') { needPr(); await messagesTab(panel, c.pr); } } catch (e) { panel.innerHTML = errBox(e); }}
async function diffTab(panel, c) { const d = await api(`/api/commits/${c.sha}/diff`); panel.innerHTML = `<p class="muted">${d.files.length} files changed</p>` + diffFiles(d, c.sha, 10);}
async function reviewsTab(panel, n) { const [p, r] = await Promise.all([api('/api/prs/' + n), api(`/api/prs/${n}/reviews`)]); panel.innerHTML = ` <div class="meta"> <div><b>State</b>${esc(p.state)}</div><div><b>Opened</b>${time(p.opened_ts)}</div> <div><b>Merged</b>${time(p.merged_ts) || '—'}</div><div><b>Branch</b>${esc(p.branch)}</div> <div><b>Updates</b>${p.n_updates}</div><div><b>Reviews</b>${p.review_count}</div></div> <article class="card"><header><h3>PR description</h3><span class="muted">${esc(p.author)}</span></header> <div class="body md">${md(p.description)}</div></article> <h2>Reviews</h2><div id="revlist"></div>`; const list = panel.querySelector('#revlist'), card = v => ` <article class="card"><header><span class="verdict ${esc(v.verdict)}">${esc(v.verdict)}</span><b>${esc(v.reviewer)}</b> <span class="muted">${time(v.ts)} · head ${short(v.head_sha)}</span></header><div class="body md">${md(v.comment)}</div></article>`; list.innerHTML = r.items.slice(0, 6).map(card).join('') || '<p class="muted">No reviews.</p>'; if (r.items.length > 6) { list.insertAdjacentHTML('beforeend', `<button class="more" type="button">+${r.items.length - 6} more reviews</button>`); list.querySelector('.more').onclick = e => { e.target.remove(); list.insertAdjacentHTML('beforeend', r.items.slice(6).map(card).join('')); }; }}
async function tracesTab(panel, n) { const w = await api(`/api/prs/${n}/traces`); panel.innerHTML = `<p class="muted">The author's trace from ten minutes before the PR opened until it merged or closed, and each reviewer's trace within fifteen minutes of their review. Controller events are hidden.</p>` + w.items.map((x, i) => ` <section class="window" data-i="${i}"><header><h3>${x.role}</h3><b>${esc(x.agent)}</b> <span class="muted">${esc(x.lane || '')} · ${time(x.from_ts)} → ${time(x.to_ts)}</span> ${x.source ? `<a href="${x.source}" target="_blank" rel="noopener">trace file ↗</a>` : ''}</header> <div class="turns">${x.has_trace ? '<button class="load">Show trace</button>' : '<p class="muted">No trace for this agent.</p>'}</div></section>`).join(''); panel.querySelectorAll('.window').forEach(sec => { const x = w.items[+sec.dataset.i], box = sec.querySelector('.turns'), btn = box.querySelector('.load'); if (!btn) return; let cursor = 0; const load = async () => { btn.disabled = true; btn.textContent = 'Loading…'; try { const first = cursor === 0; let d; for (let k = 0; k < 10; k++) { // a page can come back empty when the server's read cap is hit first; keep going const q = new URLSearchParams({ from: x.from_ts, to: x.to_ts, limit: 40, cursor, messages_only: 'true' }); d = await api(`/api/traces/${encodeURIComponent(x.agent)}?${q}`); cursor = d.next_cursor; if (d.records.length || cursor == null) break; } btn.insertAdjacentHTML('beforebegin', d.records.map(turn).join('') || (first && cursor == null ? '<p class="muted">No records in this window.</p>' : '')); btn.hidden = cursor == null; btn.disabled = false; btn.textContent = 'More'; } catch (e) { btn.insertAdjacentHTML('beforebegin', errBox(e)); btn.hidden = true; } }; btn.onclick = load; if (x.role === 'author') load(); });}
function turn(rec) { const m = rec.message || {}, role = m.role, t = `<span class="muted">${time(rec.timestamp).slice(11)}</span>`; const parts = Array.isArray(m.content) ? m.content : [{ type: 'text', text: m.content || '' }]; if (role === 'toolResult') { const text = parts.map(p => p.text || '').join('\n'); return `<div class="turn tool"><details><summary>${t} result · ${esc(m.toolName)}${m.isError ? ' · error' : ''} · ${text.length} chars</summary><pre>${esc(text)}</pre></details></div>`; } if (role === 'system') { const text = m.content || Object.entries(m.sections || {}).map(([k, v]) => `## ${k}\n${typeof v === 'string' ? v : JSON.stringify(v, null, 1)}`).join('\n\n'); return `<div class="turn"><details><summary>${t} system prompt</summary><pre>${esc(text)}</pre></details></div>`; } const body = parts.map(p => { if (p.type === 'thinking') return `<div class="thinking">${esc(p.thinking)}</div>`; if (p.type === 'toolCall') { const a = p.arguments || {}, main = a.command ?? a.path ?? ''; const rest = Object.fromEntries(Object.entries(a).filter(([k]) => !['command', 'path'].includes(k) || typeof a[k] !== 'string')); return `<div class="call"><b>${esc(p.name)}</b> <pre>${esc(main)}${Object.keys(rest).length && main !== '' ? '\n' : ''}${Object.keys(rest).length ? esc(JSON.stringify(rest, null, 1)) : ''}</pre></div>`; } return `<div class="text">${esc(p.text)}</div>`; }).join(''); return `<div class="turn ${esc(role)}"><div class="who">${esc(role)} ${t}</div>${body}</div>`;}
const msgCard = (m, hl) => ` <article class="card${hl ? ' hl' : ''}" id="m${m.id}"><header><b>#${esc(m.channel)}</b><span>${esc(m.author)}</span> <span class="muted">${time(m.ts)}</span>${m.reason ? `<span class="muted">${m.reason === 'mention' ? 'mentions the PR' : 'author post'}</span>` : ''} <a data-nav href="/message/${m.id}">thread →</a>${m.source ? ` <a href="${m.source}" target="_blank" rel="noopener">on the board ↗</a>` : ''}</header><div class="body">${rich(m.body)}</div></article>`;
async function messagesTab(panel, n) { panel.innerHTML = `<div class="chips" role="group" aria-label="Filter"> <button aria-pressed="true" data-r="">All</button><button aria-pressed="false" data-r="mention">Mentions the PR</button> <button aria-pressed="false" data-r="author_window">Author posts</button></div><div id="msgs"></div><button class="more" hidden>More</button>`; const list = panel.querySelector('#msgs'), more = panel.querySelector('.more'); let reason = '', offset = 0; const load = async () => { const q = new URLSearchParams({ limit: 50, offset }); if (reason) q.set('reason', reason); const d = await api(`/api/prs/${n}/messages?${q}`); list.insertAdjacentHTML('beforeend', d.items.map(m => msgCard(m)).join('') || (offset ? '' : '<p class="muted">No linked posts.</p>')); offset = d.next_offset; more.hidden = offset == null; }; panel.querySelector('.chips').onclick = e => { const b = e.target.closest('button'); if (!b) return; panel.querySelectorAll('.chips button').forEach(x => x.setAttribute('aria-pressed', x === b)); reason = b.dataset.r; offset = 0; list.innerHTML = ''; load().catch(err => list.innerHTML = errBox(err)); }; more.onclick = () => load(); await load();}
// A merged PR opens on its commit in the explorer; any other PR gets its own small page.async function prPage(n) { $app.innerHTML = '<p class="muted">Loading…</p>'; let p; try { p = await api('/api/prs/' + n); } catch (e) { $app.innerHTML = errBox(e); return; } if (p.commit) { history.replaceState(null, '', '/commits?sha=' + p.commit); return route(); } const tab = new URLSearchParams(location.search).get('tab') || 'reviews', tabs = TABS.filter(t => t[0] !== 'diff'); document.title = `PR #${n} · PyBot Data Explorer`; $app.innerHTML = ` <div class="nav-row"><a data-nav href="/commits">← commits</a></div> <div class="label">PR #${n} title</div><h1>${esc(p.title)}</h1> <p class="meta-line">${esc(p.author)} · ${esc(p.state)} · opened ${time(p.opened_ts).slice(0, 16)} · never merged</p> <nav class="tabs" role="tablist">${tabs.map(([k, l]) => `<a role="tab" data-nav href="/pr/${n}?tab=${k}" aria-selected="${k === tab}">${l}</a>`).join('')}</nav> <section class="panel" id="panel"><p class="muted">Loading…</p></section>`; const panel = document.getElementById('panel'); try { await ({ reviews: reviewsTab, traces: tracesTab, messages: messagesTab }[tab] || reviewsTab)(panel, n); } catch (e) { panel.innerHTML = errBox(e); }}
// ---------- data sources ----------const SOURCES = [ { name: 'Agent traces', kind: 'Bucket', repo: 'HuggingFaceSwarms/pybot-traces', url: 'https://huggingface.co/buckets/HuggingFaceSwarms/pybot-traces', what: 'Every agent\'s session log: 997 agents, 51.1M records, ~33 GB of Pi JSONL (session header, system/user/assistant/tool-result messages, controller events). README and Apache-2.0 licence in the bucket.', layout: 'traces/<lane>/<agent>.jsonl · traces/_manifest.jsonl (one row per agent)', cmds: ['hf buckets cp hf://buckets/HuggingFaceSwarms/pybot-traces/traces/_manifest.jsonl .', 'hf buckets cp hf://buckets/HuggingFaceSwarms/pybot-traces/traces/answers/agile-gorilla.jsonl .', 'hf buckets sync hf://buckets/HuggingFaceSwarms/pybot-traces/traces/safety ./traces/safety'] }, { name: 'Message board', kind: 'Space', repo: 'HuggingFaceSwarms/pybot-msgboard', url: 'https://huggingface.co/spaces/HuggingFaceSwarms/pybot-msgboard', viewer: 'https://huggingfaceswarms-pybot-msgboard.hf.space', what: 'What the agents said to each other: 184,059 messages in 12 channels, channel docs and stored files, with a read-only viewer (shared links: /#msg/<id>).', layout: 'data/ (start with data/manifest.json) · web/reader.js decodes the message chunks', cmds: ['hf download HuggingFaceSwarms/pybot-msgboard --repo-type space --local-dir pybot-msgboard'] }, { name: 'Commits', kind: 'Dataset', repo: 'HuggingFaceSwarms/pybot-commits', url: 'https://huggingface.co/datasets/HuggingFaceSwarms/pybot-commits', what: 'The chatbot\'s code with its full git history: 8,609 commits on a linear main, ending at 24cbc04.', layout: 'a git repository; each commit page is /commit/<sha>, each file /blob/<sha>/<path>', cmds: ['git clone https://huggingface.co/datasets/HuggingFaceSwarms/pybot-commits', 'git -C pybot-commits show 24cbc04 --stat'] }, { name: 'PyBot Data Explorer tables', kind: 'Space', repo: 'HuggingFaceSwarms/pybot-explorer', url: 'https://huggingface.co/spaces/HuggingFaceSwarms/pybot-explorer/tree/main/data', what: 'The SQLite files behind this site: PRs, reviews, commits with SmolTalkBench scores, board messages with full-text search, trace windows and PR-message links (explorer.sqlite), and the per-agent trace time index (traces.sqlite). The scripts that build them are in build/; the API (/docs) serves the same data.', layout: 'data/explorer.sqlite · data/traces.sqlite · build/build_db.py · build/index_traces.py', cmds: ['hf download HuggingFaceSwarms/pybot-explorer --repo-type space --include "data/*" --local-dir pybot-explorer'] },];
function dataPage() { document.title = 'Data · PyBot Data Explorer'; $app.innerHTML = ` <div class="label">Data sources</div><h1>Where the data lives</h1> <p>Everything here is the scrubbed release data of the PyBot run, cut at commit <a data-nav href="/commits?sha=${DEFAULT_SHA}">24cbc04</a> (2026-11-13 10:17 UTC). The message-board export runs about a day longer, to 2026-11-14 12:50 UTC. Agents can use the <a href="/docs">API</a> and <a href="/llms.txt">llms.txt</a>; each API answer carries a <code>source</code> link back to these repositories.</p> ${SOURCES.map(d => ` <section class="card src"><header><h3>${d.name}</h3><span class="muted">${d.kind}</span> <a href="${d.url}" target="_blank" rel="noopener">${d.repo} ↗</a>${d.viewer ? ` <a href="${d.viewer}" target="_blank" rel="noopener">viewer ↗</a>` : ''}</header> <div class="body md"><p>${esc(d.what)}</p><p class="muted">${esc(d.layout)}</p> <pre><code>${d.cmds.map(esc).join('\n')}</code></pre></div></section>`).join('')} <p class="muted">While the repositories are private, these links and commands need a Hugging Face login (or HF_TOKEN) with access.</p>`;}
async function messagePage(id) { $app.innerHTML = '<p class="muted">Loading…</p>'; try { const d = await api('/api/messages/' + id), m = d.message; document.title = `Message ${id} · PyBot Data Explorer`; $app.innerHTML = `<div class="nav-row"><a href="/" id="back">← back</a> <span class="muted">${m.prs.map(p => `PR #${p}`).join(', ')}</span></div> <h1>#${esc(m.channel)} · thread ${d.thread_root}</h1> <p class="muted">${m.thread_size} posts in this thread${m.thread_size > d.thread.length ? `; showing the first post and the ${d.thread.length - 1} replies nearest this one` : ''}.</p> ${d.thread.map(x => msgCard(x, x.id === id)).join('')}`; document.getElementById('back').onclick = e => { e.preventDefault(); if (navs) { navs--; history.back(); } else go('/'); }; document.getElementById('m' + id)?.scrollIntoView({ block: 'center' }); } catch (e) { $app.innerHTML = errBox(e); }}
route();123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230 Aladdin Free Public License (Version 9, September 18, 2000)
Copyright (C) 1994, 1995, 1997, 1998, 1999, 2000 Aladdin Enterprises, Menlo Park, California, U.S.A. All rights reserved.
NOTE: This License is not the same as any of the GNU Licenses published by the Free Software Foundation. Its terms are substantially different from those of the GNU Licenses. If you are familiar with the GNU Licenses, please read this license with extra care.
Aladdin Enterprises hereby grants to anyone the permission to apply thisLicense to their own work, as long as the entire License (including theabove notices and this paragraph) is copied with no changes, additions, ordeletions except for changing the first paragraph of Section 0 to include asuitable description of the work to which the license is being applied andof the person or entity that holds the copyright in the work, and, if theLicense is being applied to a work created in a country other than theUnited States, replacing the first paragraph of Section 6 with anappropriate reference to the laws of the appropriate country.
This License is not an Open Source license: among other things, it placesrestrictions on distribution of the Program, specifically including sale ofthe Program. While Aladdin Enterprises respects and supports the philosophyof the Open Source Definition, and shares the desire of the GNU project tokeep licensed software freely redistributable in both source and objectform, we feel that Open Source licenses unfairly prevent developers ofuseful software from being compensated proportionately when others profitfinancially from their work. This License attempts to ensure that those whoreceive, redistribute, and contribute to the licensed Program according tothe Open Source and Free Software philosophies have the right to do so,while retaining for the developer(s) of the Program the power to make thosewho use the Program to enhance the value of commercial products pay for theprivilege of doing so.
0. Subject Matter
This License applies to the computer program known as "AFPL Ghostscript."The "Program", below, refers to such program. The Program is a copyrightedwork whose copyright is held by artofcode LLC, located in Benicia,California (the "Licensor"). Please note that AFPL Ghostscript is neitherthe program known as "GNU Ghostscript" nor the version of Ghostscriptavailable for commercial licensing from Artifex Software Inc.
A "work based on the Program" means either the Program or any derivativework of the Program, as defined in the United States Copyright Act of 1976,such as a translation or a modification.
BY MODIFYING OR DISTRIBUTING THE PROGRAM (OR ANY WORK BASED ON THE PROGRAM),YOU INDICATE YOUR ACCEPTANCE OF THIS LICENSE TO DO SO, AND ALL ITS TERMS ANDCONDITIONS FOR COPYING, DISTRIBUTING OR MODIFYING THE PROGRAM OR WORKS BASEDON IT. NOTHING OTHER THAN THIS LICENSE GRANTS YOU PERMISSION TO MODIFY ORDISTRIBUTE THE PROGRAM OR ITS DERIVATIVE WORKS. THESE ACTIONS ARE PROHIBITEDBY LAW. IF YOU DO NOT ACCEPT THESE TERMS AND CONDITIONS, DO NOT MODIFY ORDISTRIBUTE THE PROGRAM.
1. Licenses.
Licensor hereby grants you the following rights, provided that you complywith all of the restrictions set forth in this License and provided,further, that you distribute an unmodified copy of this License with theProgram:
(a) You may copy and distribute literal (i.e., verbatim) copies of the Program's source code as you receive it throughout the world, in any medium.(b) You may modify the Program, create works based on the Program and distribute copies of such throughout the world, in any medium.
2. Restrictions.
This license is subject to the following restrictions:
(a) Distribution of the Program or any work based on the Program by a commercial organization to any third party is prohibited if any payment is made in connection with such distribution, whether directly (as in payment for a copy of the Program) or indirectly (as in payment for some service related to the Program, or payment for some product or service that includes a copy of the Program "without charge"; these are only examples, and not an exhaustive enumeration of prohibited activities). The following methods of distribution involving payment shall not in and of themselves be a violation of this restriction: (i) Posting the Program on a public access information storage and retrieval service for which a fee is received for retrieving information (such as an on-line service), provided that the fee is not content-dependent (i.e., the fee would be the same for retrieving the same volume of information consisting of random data) and that access to the service and to the Program is available independent of any other product or service. An example of a service that does not fall under this section is an on-line service that is operated by a company and that is only available to customers of that company. (This is not an exhaustive enumeration.) (ii) Distributing the Program on removable computer-readable media, provided that the files containing the Program are reproduced entirely and verbatim on such media, that all information on such media be redistributable for non-commercial purposes without charge, and that such media are distributed by themselves (except for accompanying documentation) independent of any other product or service. Examples of such media include CD-ROM, magnetic tape, and optical storage media. (This is not intended to be an exhaustive list.) An example of a distribution that does not fall under this section is a CD-ROM included in a book or magazine. (This is not an exhaustive enumeration.)(b) Activities other than copying, distribution and modification of the Program are not subject to this License and they are outside its scope. Functional use (running) of the Program is not restricted, and any output produced through the use of the Program is subject to this license only if its contents constitute a work based on the Program (independent of having been made by running the Program).(c) You must meet all of the following conditions with respect to any work that you distribute or publish that in whole or in part contains or is derived from the Program or any part thereof ("the Work"): (i) If you have modified the Program, you must cause the Work to carry prominent notices stating that you have modified the Program's files and the date of any change. In each source file that you have modified, you must include a prominent notice that you have modified the file, including your name, your e-mail address (if any), and the date and purpose of the change; (ii) You must cause the Work to be licensed as a whole and at no charge to all third parties under the terms of this License; (iii) If the Work normally reads commands interactively when run, you must cause it, at each time the Work commences operation, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty). Such notice must also state that users may redistribute the Work only under the conditions of this License and tell the user how to view the copy of this License included with the Work. (Exceptions: if the Program is interactive but normally prints or displays such an announcement only at the request of a user, such as in an "About box", the Work is required to print or display the notice only under the same circumstances; if the Program itself is interactive but does not normally print such an announcement, the Work is not required to print an announcement.); (iv) You must accompany the Work with the complete corresponding machine-readable source code, delivered on a medium customarily used for software interchange. The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable code. If you distribute with the Work any component that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, you must also distribute the source code of that component if you have it and are allowed to do so; (v) If you distribute any written or printed material at all with the Work, such material must include either a written copy of this License, or a prominent written indication that the Work is covered by this License and written instructions for printing and/or displaying the copy of the License on the distribution medium; (vi) You may not impose any further restrictions on the recipient's exercise of the rights granted herein.
If distribution of executable or object code is made by offering theequivalent ability to copy from a designated place, then offering equivalentability to copy the source code from the same place counts as distributionof the source code, even though third parties are not compelled to copy thesource code along with the object code.
3. Reservation of Rights.
No rights are granted to the Program except as expressly set forth herein.You may not copy, modify, sublicense, or distribute the Program except asexpressly provided under this License. Any attempt otherwise to copy,modify, sublicense or distribute the Program is void, and will automaticallyterminate your rights under this License. However, parties who have receivedcopies, or rights, from you under this License will not have their licensesterminated so long as such parties remain in full compliance.
4. Other Restrictions.
If the distribution and/or use of the Program is restricted in certaincountries for any reason, Licensor may add an explicit geographicaldistribution limitation excluding those countries, so that distribution ispermitted only in or among countries not thus excluded. In such case, thisLicense incorporates the limitation as if written in the body of thisLicense.
5. Limitations.
THE PROGRAM IS PROVIDED TO YOU "AS IS," WITHOUT WARRANTY. THERE IS NOWARRANTY FOR THE PROGRAM, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOTLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR APARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. THE ENTIRERISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULDTHE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,REPAIR OR CORRECTION.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILLLICENSOR, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAMAS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL,SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE ORINABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA ORDATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIESOR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IFSUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCHDAMAGES.
6. General.
This License is governed by the laws of the State of California, U.S.A.,excluding choice of law rules.
If any part of this License is found to be in conflict with the law, thatpart shall be interpreted in its broadest meaning consistent with the law,and no other parts of the License shall be affected.
For United States Government users, the Program is provided with RESTRICTEDRIGHTS. If you are a unit or agency of the United States Government or areacquiring the Program for any such unit or agency, the following apply:
If the unit or agency is the Department of Defense ("DOD"), the Program and its documentation are classified as "commercial computer software" and "commercial computer software documentation" respectively and, pursuant to DFAR Section 227.7202, the Government is acquiring the Program and its documentation in accordance with the terms of this License. If the unit or agency is other than DOD, the Program and its documentation are classified as "commercial computer software" and "commercial computer software documentation" respectively and, pursuant to FAR Section 12.212, the Government is acquiring the Program and its documentation in accordance with the terms of this License.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697Copyright (c) 2017, Darren Embry (<https://webonastick.com/>), withReserved Font Name Routed Gothic.
This Font Software is licensed under the SIL Open Font License, Version 1.1. This license is copied below, and is also available with a FAQ at: <http://scripts.sil.org/OFL>
# SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
## PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwidedevelopment of collaborative font projects, to support the fontcreation efforts of academic and linguistic communities, and toprovide a free and open framework in which fonts may be shared andimproved in partnership with others.
The OFL allows the licensed fonts to be used, studied, modified andredistributed freely as long as they are not sold by themselves. Thefonts, including any derivative works, can be bundled, embedded,redistributed and/or sold with any software provided that any reservednames are not used by derivative works. The fonts and derivatives,however, cannot be released under any other type of license. Therequirement for fonts to remain under this license does not apply toany document created using the fonts or their derivatives.
## DEFINITIONS
"Font Software" refers to the set of files released by the CopyrightHolder(s) under this license and clearly marked as such. This mayinclude source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after thecopyright statement(s).
"Original Version" refers to the collection of Font Softwarecomponents as distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to,deleting, or substituting -- in part or in whole -- any of thecomponents of the Original Version, by changing formats or by portingthe Font Software to a new environment.
"Author" refers to any designer, engineer, programmer, technicalwriter or other person who contributed to the Font Software.
## PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaininga copy of the Font Software, to use, study, copy, merge, embed,modify, redistribute, and sell modified and unmodified copies of theFont Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components, in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled, redistributed and/or sold with any software, provided that each copy contains the above copyright notice and this license. These can be included either as stand-alone text files, human-readable headers or in the appropriate machine-readable metadata fields within text or binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font Name(s) unless explicit written permission is granted by the corresponding Copyright Holder. This restriction only applies to the primary font name as presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font Software shall not be used to promote, endorse or advertise any Modified Version, except to acknowledge the contribution(s) of the Copyright Holder(s) and the Author(s) or with their explicit written permission.
5) The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this license, and must not be distributed under any other license. The requirement for fonts to remain under this license does not apply to any document created using the Font Software.
## TERMINATION
This license becomes null and void if any of the above conditions arenot met.
## DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OFMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENTOF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THECOPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIALDAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISINGFROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROMOTHER DEALINGS IN THE FONT SOFTWARE.12345678910111213141516171819202122232425262728<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>PyBot Data Explorer</title><meta name="description" content="Explore the PyBot swarm run: commits, pull requests, reviews, agent traces and message-board posts."><link rel="icon" href="/favicon.ico" type="image/svg+xml"><link rel="stylesheet" href="/static/style.css"><script>try { const t = localStorage.getItem('theme'); if (t) document.documentElement.dataset.theme = t; } catch (e) {}</script></head><body><header class="top"> <a class="brand lead" href="/">PyBot Data Explorer</a> <nav> <a data-nav href="/data">Data</a> <a href="/docs">API</a> <a href="/llms.txt">llms.txt</a> <button id="theme" type="button" aria-label="Toggle light or dark theme">Theme</button> </nav></header><nav class="tabs maintabs" aria-label="Views"><a data-nav data-tab="agents" href="/">Agents</a><a data-nav data-tab="commits" href="/commits">Commits</a></nav><main id="app" aria-live="polite"></main><script src="/static/d3.min.js"></script><script src="/static/agents.js"></script><script src="/static/app.js"></script></body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219@font-face { font-family: "PB Lead"; font-weight: 400; src: url(/static/fonts/lead.woff2) format("woff2"); font-display: swap; }@font-face { font-family: "PB Mono"; font-weight: 400; src: url(/static/fonts/mono.woff2) format("woff2"); font-display: swap; }@font-face { font-family: "PB Mono"; font-weight: 700; src: url(/static/fonts/mono-bold.woff2) format("woff2"); font-display: swap; }
:root { --page-bg: #ffffff; --surface-bg: #f9f9f9; --text-color: rgba(0, 0, 0, .85); --muted-color: rgba(0, 0, 0, .6); --faint-color: rgba(0, 0, 0, .1); --primary-color: oklch(0.75 0.12 47); --primary-tint: color-mix(in oklab, var(--primary-color) 18%, transparent); --ramp0: #ececec; --ramp1: #e8935f; --ramp2: #8f3f12; color-scheme: light;}@media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) { --page-bg: #0f1115; --surface-bg: #07080a; --text-color: rgba(255, 255, 255, .9); --muted-color: rgba(255, 255, 255, .65); --faint-color: rgba(255, 255, 255, .15); --primary-color: oklch(0.72 0.12 47); --ramp0: #262a31; --ramp1: #9a5631; --ramp2: #f6a774; color-scheme: dark; }}:root[data-theme="dark"] { --page-bg: #0f1115; --surface-bg: #07080a; --text-color: rgba(255, 255, 255, .9); --muted-color: rgba(255, 255, 255, .65); --faint-color: rgba(255, 255, 255, .15); --primary-color: oklch(0.72 0.12 47); --ramp0: #262a31; --ramp1: #9a5631; --ramp2: #f6a774; color-scheme: dark;}
* { box-sizing: border-box; }html { -webkit-text-size-adjust: 100%; }body { margin: 0; background: var(--page-bg); color: var(--text-color); font: 13px/1.5 "PB Mono", ui-monospace, Menlo, monospace; }a { color: inherit; text-decoration-color: var(--primary-color); text-underline-offset: 2px; }a:hover { color: var(--primary-color); }.lead, h1, h2, h3 { font-family: "PB Lead", Helvetica, Arial, sans-serif; font-weight: 400; letter-spacing: .16em; text-transform: uppercase; }h1 { font-size: 20px; margin: 0 0 8px; line-height: 1.3; letter-spacing: .1em; }h2 { font-size: 14px; margin: 28px 0 10px; }h3 { font-size: 12px; margin: 0; }.muted { color: var(--muted-color); }.label { font: 10px "PB Lead", Helvetica, Arial, sans-serif; letter-spacing: .18em; text-transform: uppercase; color: var(--muted-color); margin: 0 0 2px; }button, input, select { font: inherit; color: inherit; background: var(--page-bg); border: 1px solid var(--text-color); border-radius: 0; padding: 5px 9px; }button { cursor: pointer; }button:hover { border-color: var(--primary-color); color: var(--primary-color); }:focus-visible { outline: 2px solid var(--primary-color); outline-offset: 1px; }
.top { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 12px 24px; border-bottom: 1px solid var(--text-color); }.brand { text-decoration: none; font-size: 15px; }.top nav { display: flex; gap: 16px; align-items: center; }main { max-width: 1180px; margin: 0 auto; padding: 20px 24px 60px; }
.tip { position: absolute; pointer-events: none; background: var(--surface-bg); border: 1px solid var(--text-color); padding: 6px 9px; font-size: 12px; line-height: 1.45; max-width: 320px; opacity: 0; transition: opacity .1s; }
.meta { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 0; border: 1px solid var(--text-color); margin: 14px 0; }.meta div { padding: 8px 10px; border-right: 1px solid var(--faint-color); border-bottom: 1px solid var(--faint-color); min-width: 0; overflow-wrap: anywhere; }.meta b { display: block; font: 10px "PB Lead", sans-serif; letter-spacing: .16em; text-transform: uppercase; color: var(--muted-color); margin-bottom: 2px; }.score { color: var(--primary-color); font-weight: 700; }.nav-row { display: flex; justify-content: space-between; gap: 10px; flex-wrap: wrap; }
.tabs { display: flex; border-bottom: 1px solid var(--text-color); margin-top: 18px; overflow-x: auto; }.tabs a { padding: 8px 14px; text-decoration: none; font: 12px "PB Lead", sans-serif; letter-spacing: .16em; text-transform: uppercase; white-space: nowrap; border: 1px solid transparent; border-bottom: none; margin-bottom: -1px; }.tabs a[aria-selected="true"] { border-color: var(--text-color); background: var(--page-bg); border-bottom: 1px solid var(--page-bg); }.tabs a[aria-selected="true"]::after { content: ""; display: block; height: 2px; background: var(--primary-color); margin-top: 4px; }
.card { border: 1px solid var(--text-color); margin: 0 0 12px; }.card > header { display: flex; flex-wrap: wrap; gap: 4px 14px; align-items: baseline; padding: 6px 10px; border-bottom: 1px solid var(--faint-color); background: var(--surface-bg); }.card .body { padding: 8px 10px; white-space: pre-wrap; overflow-wrap: anywhere; }.card.hl { border-color: var(--primary-color); box-shadow: inset 3px 0 0 var(--primary-color); }.verdict { font: 11px "PB Lead", sans-serif; letter-spacing: .16em; text-transform: uppercase; border: 1px solid var(--text-color); padding: 0 6px; }.verdict.approve { border-color: var(--primary-color); color: var(--primary-color); }code { font-family: "PB Mono", ui-monospace, monospace; background: var(--surface-bg); padding: 0 3px; }.card .body.md { white-space: normal; }.src .body pre { margin: 6px 0 0; }.md p, .md ul, .md ol, .md blockquote { margin: 0 0 8px; }.md ul, .md ol { padding-left: 22px; }.md h4 { font: 12px "PB Lead", sans-serif; letter-spacing: .16em; text-transform: uppercase; margin: 12px 0 6px; }.md pre { font-family: "PB Mono", ui-monospace, monospace; font-size: 12px; background: var(--surface-bg); border: 1px solid var(--faint-color); padding: 6px 8px; margin: 0 0 8px; overflow-x: auto; white-space: pre; }.md pre code { padding: 0; background: none; }.md blockquote { border-left: 2px solid var(--faint-color); padding-left: 8px; color: var(--muted-color); }.md > :last-child { margin-bottom: 0; }
.diff-file { border: 1px solid var(--text-color); margin: 0 0 12px; }.diff-file > summary { padding: 6px 10px; cursor: pointer; background: var(--surface-bg); display: flex; gap: 10px; flex-wrap: wrap; }.diff-file pre { margin: 0; overflow-x: auto; font-size: 12px; line-height: 1.45; }.diff-file pre span { display: block; padding: 0 10px; white-space: pre; min-height: 1.45em; }.diff-file .add { background: var(--primary-tint); }.diff-file .del { color: var(--muted-color); background: var(--faint-color); }.diff-file .hunk { color: var(--muted-color); border-top: 1px solid var(--faint-color); }
.window { border: 1px solid var(--text-color); margin: 0 0 16px; }.window > header { padding: 8px 10px; display: flex; flex-wrap: wrap; gap: 4px 14px; align-items: baseline; border-bottom: 1px solid var(--text-color); }.turns { padding: 8px 10px; }.turn { margin: 0 0 10px; padding-left: 10px; border-left: 1px solid var(--faint-color); }.turn .who { font: 10px "PB Lead", sans-serif; letter-spacing: .16em; text-transform: uppercase; color: var(--muted-color); }.turn.assistant { border-left-color: var(--text-color); }.turn .text { white-space: pre-wrap; overflow-wrap: anywhere; }.turn .thinking { white-space: pre-wrap; color: var(--muted-color); font-style: italic; overflow-wrap: anywhere; }.turn .call { border: 1px solid var(--faint-color); padding: 4px 8px; margin: 4px 0; overflow-x: auto; }.turn .call b { color: var(--primary-color); }.turn pre { margin: 4px 0; white-space: pre-wrap; overflow-wrap: anywhere; font-size: 12px; }details > summary { cursor: pointer; }.turn details > summary { color: var(--muted-color); }.chips { display: flex; gap: 6px; flex-wrap: wrap; margin-bottom: 10px; }.chips button[aria-pressed="true"] { border-color: var(--primary-color); color: var(--primary-color); }.more { display: block; margin: 10px auto; }.err { border: 1px solid var(--primary-color); padding: 8px 10px; }
/* explorer home */main.wide { max-width: 1640px; }.strip { position: relative; border: 1px solid var(--text-color); padding: 0 6px; margin-bottom: 14px; }.strip svg { display: block; width: 100%; overflow: visible; }.strip .series { fill: none; stroke: var(--text-color); stroke-width: 1.25; }.strip .base line { stroke: var(--muted-color); stroke-opacity: .5; stroke-dasharray: 3 4; }.strip .base text { fill: var(--muted-color); font-size: 10px; }.strip .cursor line { stroke: var(--primary-color); stroke-width: 2; }.strip .cursor circle { fill: var(--primary-color); stroke: var(--page-bg); stroke-width: 2; }.strip .tip { z-index: 5; }.explorer { display: grid; grid-template-columns: 280px minmax(0, 1fr); gap: 16px; align-items: start; }.clist { position: sticky; top: 8px; height: calc(100vh - 150px); min-height: 320px; border: 1px solid var(--text-color); display: flex; flex-direction: column; }.clist-body { display: flex; flex-direction: column; min-height: 0; flex: 1; }.clist-filters { display: flex; flex-direction: column; gap: 6px; padding: 8px; border-bottom: 1px solid var(--text-color); }.clist-toggle { display: none; }#rows { list-style: none; margin: 0; padding: 0; overflow-y: auto; flex: 1; }#rows a { display: block; padding: 6px 8px; text-decoration: none; border-bottom: 1px solid var(--faint-color); border-left: 3px solid transparent; }#rows a:hover { background: var(--surface-bg); color: inherit; }#rows a.on { border-left-color: var(--primary-color); background: var(--surface-bg); }#rows li.muted { padding: 8px; }.l1 { display: flex; justify-content: space-between; gap: 8px; }.l2 { display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }.l3 { display: block; color: var(--muted-color); font-size: 11px; }.sel { min-width: 0; }.sel h1 { font-size: 16px; margin-bottom: 4px; }.meta-line { margin: 0 0 2px; }.keys { margin: 0; display: flex; gap: 12px; }.grid4 { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; margin-top: 12px; }.sum { border: 1px solid var(--text-color); height: 210px; overflow: hidden; display: flex; flex-direction: column; min-width: 0; }.sum > header { display: flex; justify-content: space-between; align-items: center; gap: 8px; padding: 6px 10px; border-bottom: 1px solid var(--faint-color); background: var(--surface-bg); }.sum h2 { margin: 0; font-size: 12px; }.sum h2 a { text-decoration: none; }.sum header button { padding: 2px 8px; font-size: 11px; }.sbody { padding: 8px 10px; overflow: hidden; flex: 1; min-height: 0; }.sumline { margin: 0 0 6px; font-weight: 700; }.one { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; line-height: 1.6; }.one .verdict { font-size: 10px; }.tc b { color: var(--primary-color); }.vtabs { margin-top: 12px; align-items: flex-end; }.vtabs .collapse { margin: 0 0 4px auto; padding: 3px 10px; font-size: 11px; }.full { padding-top: 12px; }.full .chips button { padding: 2px 8px; font-size: 11px; }.mturn { padding: 4px 0 6px; border-bottom: 1px solid var(--faint-color); cursor: pointer; }.mturn .thinking { color: var(--muted-color); font-style: italic; }.clamp { display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden; white-space: pre-wrap; overflow-wrap: anywhere; }.clamp1 { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }.mturn.open .clamp, .mturn.open .clamp1 { display: block; -webkit-line-clamp: unset; white-space: pre-wrap; overflow: visible; overflow-wrap: anywhere; }@media (max-width: 760px) { .explorer { grid-template-columns: minmax(0, 1fr); gap: 12px; } .clist { position: static; height: auto; min-height: 0; } .clist-toggle { display: block; width: 100%; border: none; text-align: left; font: 12px "PB Lead", sans-serif; letter-spacing: .16em; text-transform: uppercase; } .clist-body { display: none; } .clist.open .clist-body { display: flex; border-top: 1px solid var(--text-color); } #rows { max-height: 60vh; } .grid4 { grid-template-columns: minmax(0, 1fr); } .maintabs { padding: 0 16px; } .hcard { padding: 8px; } .hcard .hv { font-size: 20px; }}
/* main tabs and agents view */.maintabs { padding: 0 24px; margin-top: 10px; }.intro { font-size: 15px; margin: 4px 0 16px; }.hl { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 10px; margin-bottom: 8px; }.hcard { display: flex; flex-direction: column; gap: 4px; border: 1px solid var(--text-color); padding: 10px; text-decoration: none; min-width: 0; }.hcard:hover { border-color: var(--primary-color); color: inherit; }.hcard .hv { font: 24px "PB Lead", Helvetica, Arial, sans-serif; letter-spacing: .06em; }.hcard .go { color: var(--primary-color); font-size: 12px; }.spark { width: 100%; height: 30px; display: block; }.spark path { fill: none; stroke: var(--text-color); stroke-width: 1.25; }.spark line { stroke: var(--primary-color); stroke-width: 1.5; }.sec-head { display: flex; flex-wrap: wrap; justify-content: space-between; align-items: baseline; gap: 8px; }.sec-head .chips button { padding: 2px 8px; font-size: 11px; }.contrib { position: relative; }.contrib svg { display: block; width: 100%; }.contrib .lane { font: 10px "PB Lead", Helvetica, Arial, sans-serif; letter-spacing: .16em; fill: var(--muted-color); }.contrib rect { cursor: pointer; outline: none; }.contrib rect.on, .contrib rect:focus { stroke: var(--text-color); stroke-width: 1.5; }.legend { display: flex; flex-wrap: wrap; gap: 16px; align-items: center; margin-top: 6px; }.legend text { fill: var(--muted-color); font: 10px "PB Mono", monospace; }.legend .nt { display: inline-flex; gap: 6px; align-items: center; color: var(--muted-color); font-size: 11px; }.moments { list-style: none; padding: 0; margin: 0; border-top: 1px solid var(--faint-color); }.moments li { padding: 6px 0; border-bottom: 1px solid var(--faint-color); display: flex; flex-wrap: wrap; gap: 4px 10px; }.astrip { position: relative; border: 1px solid var(--text-color); padding: 6px 8px 0; }.astrip svg { display: block; width: 100%; overflow: visible; }.astrip g rect { fill: var(--text-color); }.astrip g rect.sel { fill: var(--primary-color); }.astrip .base { stroke: var(--faint-color); }.astrip text { fill: var(--muted-color); font: 10px "PB Mono", monospace; }.tb { border: 1px solid var(--text-color); margin-top: 12px; }.tb > header { display: flex; align-items: center; gap: 10px; padding: 6px 10px; border-bottom: 1px solid var(--faint-color); background: var(--surface-bg); }.tb > header button { padding: 2px 8px; }.tb > header button:disabled { opacity: .35; cursor: default; }.tb .turns { padding: 8px 10px; max-height: 70vh; overflow-y: auto; }.alists { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 16px; }.alists section { min-width: 0; }
@media (max-width: 640px) { .top { padding: 10px 16px; } .top { gap: 8px; } .top nav { gap: 8px; } .top nav button { padding: 3px 6px; } .brand { font-size: 12px; letter-spacing: .06em; white-space: nowrap; } main { padding: 14px 16px 40px; } .hide-sm { display: none; } h1 { font-size: 16px; } .tabs { flex-wrap: wrap; overflow-x: visible; } .tabs a { flex: 1 1 auto; text-align: center; padding: 8px 4px; font-size: 11px; letter-spacing: .06em; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129"""API smoke tests against a tiny fixture built with the real build scripts."""import gzip, json, os, subprocess, sysfrom pathlib import Path
import pytestfrom fastapi.testclient import TestClient
ROOT = Path(__file__).resolve().parents[1]sys.path[:0] = [str(ROOT), str(ROOT / "build")]
def jsonl(path, rows): path.write_text("".join(json.dumps(r) + "\n" for r in rows))
@pytest.fixture(scope="module")def client(tmp_path_factory): tmp = tmp_path_factory.mktemp("fx") # git history with one commit repo = tmp / "work" repo.mkdir() git = lambda *a: subprocess.run(["git", "-C", str(repo), *a], check=True, capture_output=True, text=True).stdout git("init", "-q"); (repo / "bot.py").write_text("print('hi')\n") git("add", "."); git("-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "first (#7)") sha = git("rev-parse", "HEAD").strip() subprocess.run(["git", "clone", "-q", "--bare", str(repo), str(tmp / "h.git")], check=True) # tables t = tmp / "tables"; t.mkdir() jsonl(t / "commits.jsonl", [{"sha": sha, "parent_shas": [], "ts": "2026-11-01T10:00:00Z", "author": "git-server", "title": "first (#7)", "pr": 7, "approvers": ["bob"], "score": {"lp_win_rate": 12.5, "standard_error": 1.0, "revision": "r"}}]) jsonl(t / "prs.jsonl", [{"pr": 7, "author": "ann", "title": "first", "description": "adds `bot.py`", "branch": "b", "base_sha": "0", "opened_ts": "2026-11-01T09:00:00.000Z", "state_at_cutoff": "merged", "merged_ts": "2026-11-01T10:00:01.000Z", "merged_sha": sha, "head_sha_final": sha, "close_reason": None, "n_updates": 0, "approvers": ["bob"], "first_event_ts": "2026-11-01T09:00:00.000Z", "last_event_ts": "2026-11-01T10:00:01.000Z"}]) jsonl(t / "reviews.jsonl", [{"pr": 7, "reviewer": "bob", "ts": "2026-11-01T09:30:00.000Z", "head_sha": sha, "verdict": "approve", "comment": "looks good"}]) # board export b = tmp / "board" / "data"; (b / "messages").mkdir(parents=True) (b / "manifest.json").write_text(json.dumps({ "last_at": 1e10, "revisions": {}, "channels": [{"id": 1, "name": "general", "description": ""}], "people": [{"id": 1, "external_id": "ann", "experiment_agent": True}, {"id": 2, "external_id": "bob", "experiment_agent": True}]})) t0 = 1793523600.0 # 2026-11-01T09:00:00Z with gzip.open(b / "messages" / "1-0.json.gz", "wt") as f: json.dump([[1, 1, 2, t0 + 60, "please review PR #7", 0, 0, 0, []], [2, 2, 1, t0 + 120, "on it", 1, 1, 0, []], [3, 3, 2, t0 - 86400, "unrelated #99", 0, 0, 0, []], [4, 4, 2, t0 - 3600, "#7 in a list, before PR 7 existed", 0, 0, 0, []]], f) # traces tr = tmp / "traces" / "lane1"; tr.mkdir(parents=True) jsonl(tr / "ann.jsonl", [{"type": "session", "timestamp": "2026-11-01T08:00:00.000Z"}] + [ {"type": "message", "timestamp": f"2026-11-01T09:{m:02d}:00.000Z", "message": {"role": "assistant", "content": [{"type": "text", "text": f"step {m}"}, {"type": "toolCall", "name": "bash"}], "usage": {"input": 100, "output": 10, "reasoning": 4}}} for m in range(0, 60, 5)]) jsonl(tmp / "manifest.jsonl", [{"lane": "lane1", "agent": "ann", "kept": 13, "bytes_out": 1, "last_record": "x"}]) data = tmp / "data"; data.mkdir() import build_db, index_traces build_db.main(str(t), str(tmp / "board"), str(tmp / "manifest.jsonl"), str(data / "explorer.sqlite")) index_traces.main(str(tmp / "traces"), str(data / "traces.sqlite"))
os.environ.update(EXPLORER_DATA=str(data), GIT_DIR_PATH=str(tmp / "h.git")) import app app.read_range = lambda lane, agent, s, e: (tmp / "traces" / lane / f"{agent}.jsonl").read_bytes()[s:e] return TestClient(app.app), sha
def test_commits_and_pr(client): c, sha = client item = c.get("/api/commits?author=ann").json()["items"][0] # the PR author, not the git author assert item["lp_win_rate"] == 12.5 and item["git_author"] == "git-server" d = c.get(f"/api/commits/{sha[:7]}").json() assert d["pr_info"]["pr"] == 7 and d["approvers"] == ["bob"] and d["author"] == "ann" assert c.get(f"/api/commits/{sha}/diff").json()["files"][0]["path"] == "bot.py" assert "patch" not in c.get(f"/api/commits/{sha}/diff?patch=false").json() assert c.get(f"/api/commits/{sha}/file?path=bot.py").text == "print('hi')\n" assert c.get("/api/prs/7/reviews").json()["items"][0]["verdict"] == "approve" assert d["source"].endswith(f"/commit/{sha}") and c.get("/api/prs/7").json()["source"] == d["source"] assert c.get(f"/api/commits/{sha}/diff").json()["files"][0]["source"].endswith(f"/blob/{sha}/bot.py") assert c.get("/api/scores").json()["rows"][0][1:5:3] == [sha, "ann"] assert c.get("/api/commits/zz").status_code == 400 and c.get("/api/prs/8").status_code == 404
def test_links_and_messages(client): c, _ = client msgs = {m["id"]: m["reason"] for m in c.get("/api/prs/7/messages").json()["items"]} assert msgs == {1: "mention", 2: "author_window"} # #99 is not a PR; message 4 predates PR 7 assert c.get("/api/prs/7").json()["message_count"] == 2 assert c.get("/api/prs/7/messages?newest_first=true&limit=1").json()["items"][0]["id"] == 2 assert [m["id"] for m in c.get("/api/messages/2").json()["thread"]] == [1, 2] assert c.get("/api/messages/2").json()["message"]["source"].endswith("/#msg/2") assert c.get("/api/messages/search?q=review").json()["items"][0]["id"] == 1 assert c.get("/api/agents/ann").json()["lane"] == "lane1"
def test_traces_window_and_cursor(client): c, _ = client w = {x["role"]: x for x in c.get("/api/prs/7/traces").json()["items"]} assert w["author"]["from_ts"] == "2026-11-01T08:50:00.000Z" and w["reviewer"]["agent"] == "bob" p1 = c.get("/api/traces/ann?from=2026-11-01T09:10:00Z&to=2026-11-01T09:30:00Z&limit=3").json() assert [r["message"]["content"][0]["text"] for r in p1["records"]] == ["step 10", "step 15", "step 20"] p2 = c.get(f"/api/traces/ann?from=2026-11-01T09:10:00Z&to=2026-11-01T09:30:00Z&limit=3&cursor={p1['next_cursor']}").json() assert [r["message"]["content"][0]["text"] for r in p2["records"]] == ["step 25", "step 30"] assert c.get("/api/traces/nobody").status_code == 404 assert p1["source"].endswith("/resolve/traces/lane1/ann.jsonl") and w["author"]["source"] == p1["source"]
def test_bad_inputs_are_400(client): c, sha = client for path in ["../x", "-h", "", "/etc/passwd"]: assert c.get(f"/api/commits/{sha}/file", params={"path": path}).status_code == 400, path assert c.get("/api/commits/xyz").status_code == 400 assert c.get("/api/traces/ann?cursor=5").status_code == 400 # mid-line cursor assert c.get("/api/messages/search?q=%22").status_code == 400
def test_agents_and_highlights(client): c, sha = client rows = {a["name"]: a for a in c.get("/api/agents?sort=model_calls").json()["items"]} assert rows["ann"]["model_calls"] == 12 and rows["ann"]["tool_calls"] == 12 and rows["ann"]["total_tokens"] == 12 * 110 assert rows["bob"]["has_trace"] is False and rows["bob"]["reviews"] == 1 and rows["ann"]["prs_merged"] == 1 a = c.get("/api/agents/ann").json() assert a["hours"]["rows"][0][1:] == [12, 12, 1200, 120] and a["busiest_hour"] == "2026-11-01T09:00:00Z" h = c.get("/api/highlights").json() assert h["totals"]["agents"] == 2 and h["totals"]["model_calls"] == 12 assert {x["title"]: x["agent"] for x in h["highlights"]}["Most tool calls"] == "ann" assert any(m["text"].startswith("First merged PR: #7") for m in h["moments"]) assert c.get("/api/agents?sort=drop").status_code == 400 and c.get("/api/agents/nobody").status_code == 404.dockerignoreAdded+3
.gitattributesAdded+37
DockerfileAdded+11
README.mdAdded+65
app.pyAdded+517
build/build_db.pyAdded+166
build/index_traces.pyAdded+99
llms.txtAdded+48
requirements.txtAdded+3
static/agents.jsAdded+222
static/app.jsAdded+594
static/d3.min.jsAdded
static/favicon.svgAdded
static/fonts/LICENSE-letter-gothic-code.txtAdded+230
static/fonts/LICENSE-routed-gothic.mdAdded+97
static/fonts/lead.woff2Added
static/fonts/mono-bold.woff2Added
static/fonts/mono.woff2Added
static/index.htmlAdded+28
static/style.cssAdded+219
tests/test_api.pyAdded+129