'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" page const prLinks = h => h.replace(/(^|[^\w&;\/>="])#(\d{1,5})\b/g, (m, pre, n) => +n >= 1 && +n <= MAX_PR ? `${pre}#${n}` : m); // Escaped text with `code`, **bold** and PR links; everything else stays literal. const rich = s => prLinks(esc(s).replace(/`([^`\n]+)`/g, '$1')) .replace(/\*\*([^*\n]+)\*\*/g, '$1'); // 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, '$1')) .replace(/\*\*([^*\n]+)\*\*/g, '$1') .replace(/(^|[\s(])\*([^*\s][^*\n]*)\*/g, '$1$2') .replace(/\u0000(\d+)\u0000/g, (_, i) => `${esc(codes[i])}`); }; function md(src) { const out = [], lines = String(src ?? '').split('\n'); let para = [], list = null; const flush = () => { if (para.length) out.push(`

${mdInline(para.join('\n'))}

`); if (list) out.push(``); 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(`
${esc(code.join('\n'))}
`); } else if (h) { flush(); out.push(`

${mdInline(h[2])}

`); } else if (item) { const kind = /\d/.test(item[1]) ? 'ol' : 'ul'; if (para.length || list !== kind) { flush(); out.push(`<${kind}>`); list = kind; } out.push(`
  • ${mdInline(item[2])}
  • `); } else if (/^>\s?/.test(l)) { flush(); out.push(`
    ${mdInline(l.replace(/^>\s?/, ''))}
    `); } 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()) + ''); 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 => `

    ${esc(e.message || e)}

    `; 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 to function 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 run const BASELINES = [['SmolLM-1.7B', 40.6], ['SmolLM-360M', 26.6], ['SmolLM-135M', 10.1]]; let scoresP = null; // the score curve, fetched once let 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 = `
    `; 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 => `
  • ${short(c.sha)}${c.lp_win_rate != null ? c.lp_win_rate.toFixed(1) + '%' : ''} ${esc(c.pr_title || c.title)} ${c.pr ? '#' + c.pr + ' · ' : ''}${esc(c.author)} · ${time(c.ts).slice(5, 16)}
  • `).join('') || (offset ? '' : '
  • No commits match.
  • ')); 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 = `${short(p.sha)}${p.pr ? ' · #' + p.pr : ''} · ${esc(p.author)}
    win rate ${p.lp_win_rate.toFixed(2)}% · ${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 = `
    ${pr ? `PR #${pr.pr} title` : 'Commit message'}

    ${esc(pr ? pr.title : c.title)}

    ${short(c.sha)} · ${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 ${c.lp_win_rate.toFixed(2)}% ± ${c.standard_error.toFixed(2)}` : 'not scored'} · commit on the Hub ↗ · Open full commit view →

    ${c.prev_sha ? `← older` : ''} ${c.next_sha ? `newer →` : ''} (or ← → keys)

    `; 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 = '

    Pushed directly, without a pull request.

    '; return Promise.resolve(); }; if (!ex.view) { box.innerHTML = `
    ${VIEWS.map(([k, l]) => `

    ${l}

    Loading…

    `).join('')}
    `; 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 = `

    Loading…

    `; 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 = `

    ${count('approve')} approve · ${count('request_changes')} request changes

    ` + (r.length > 6 ? r.slice(0, 5) : r).map(v => `
    ${v.verdict === 'approve' ? 'approve' : 'changes'} ${esc(v.reviewer)} ${esc(firstLine(v.comment))}
    `).join('') + (r.length > 6 ? `
    +${r.length - 5} more reviews
    ` : ''); }, 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 = '

    No trace for the author.

    '; return; } const { recs } = await lastTurns(author, 300); if (!ok()) return; el.innerHTML = `

    ${esc(author.agent)} + ${plural(revs, 'reviewer')} · ${plural(recs.length, 'turn')} in the 20 min before the merge

    ` + recs.slice(-3).map(r => `
    ${oneTurn(r)}
    `).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 = `

    ${plural(p.message_count, 'linked post')}

    ` + d.items.map(m => `
    ${esc(m.author)} #${esc(m.channel)} ${esc(firstLine(m.body))}
    `).join(''); }, }; async function sumDiff(el, ok, c) { const d = await api(`/api/commits/${c.sha}/diff?patch=false`); if (!ok()) return; el.innerHTML = `

    ${plural(d.files.length, 'file')} · +${d3.sum(d.files, f => f.additions || 0)} −${d3.sum(d.files, f => f.deletions || 0)}

    ` + d.files.map(f => `
    ${esc(f.path)} +${f.additions ?? '?'} −${f.deletions ?? '?'}
    `).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 = `

    ${plural(d.files.length, 'file')} · +${d3.sum(d.files, f => f.additions || 0)} −${d3.sum(d.files, f => f.deletions || 0)}

    ` + diffFiles(d, c.sha, 3); } // Each file is a
    ; 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 `
    ${esc(path)} +${f.additions ?? '?'} −${f.deletions ?? '?'} file ${f.source ? `Hub ↗` : ''}
    `; }).join('') + (d.truncated ? '

    Patch cut at 2 MB.

    ' : ''); } 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 `${esc(l)}`; }).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 = '

    No traces for these agents.

    '; return; } el.innerHTML = `
    ${w.map((x, i) => ``).join('')}
    `; 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 = '

    Loading…

    '; const x = w[i], { recs: all, end } = await lastTurns(x, 1200), recs = all.slice(-12); if (!ok()) return; box.innerHTML = (x.reconstructed ? RECON : '') + `

    ${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 · full trace → · trace file ↗

    ` + (recs.map(miniTurn).join('') || '

    No turns in this window.

    '); 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 => `${esc(p.name)} ${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 `${time(rec.timestamp).slice(11, 16)} ` + (call ? `${callLine(call)}` : esc(firstLine(say?.text ?? say?.thinking))); } function miniTurn(rec) { const parts = rec.message.content || []; return `
    ${time(rec.timestamp).slice(11, 19)}` + parts.map(p => p.type === 'thinking' ? `
    ${esc(p.thinking)}
    ` : p.type === 'toolCall' ? `
    ${callLine(p)}
    ` : `
    ${esc(p.text)}
    `).join('') + '
    '; } // ---------- commit page ---------- const TABS = [['diff', 'Diff'], ['reviews', 'PR & reviews'], ['traces', 'Traces'], ['messages', 'Messages']]; async function commitPage(sha) { $app.innerHTML = '

    Loading…

    '; 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 = `
    ${pr ? `PR #${pr.pr} title` : 'Commit message'}

    ${esc(pr ? pr.title : c.title)}

    Commit${c.sha} on the Hub ↗
    Time${time(c.ts)}
    Author${esc(c.author)}
    PR${pr ? `#${pr.pr} by ${esc(pr.author)}` : '—'}
    Approvers${esc((c.approvers || []).join(', ') || '—')}
    Win rate${c.lp_win_rate != null ? `${c.lp_win_rate.toFixed(2)}% ± ${c.standard_error.toFixed(2)}` : 'not scored'}

    Loading…

    `; 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 = `

    ${d.files.length} files changed

    ` + 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 = `
    State${esc(p.state)}
    Opened${time(p.opened_ts)}
    Merged${time(p.merged_ts) || '—'}
    Branch${esc(p.branch)}
    Updates${p.n_updates}
    Reviews${p.review_count}

    PR description

    ${esc(p.author)}
    ${md(p.description)}

    Reviews

    `; const list = panel.querySelector('#revlist'), card = v => `
    ${esc(v.verdict)}${esc(v.reviewer)} ${time(v.ts)} · head ${short(v.head_sha)}
    ${md(v.comment)}
    `; list.innerHTML = r.items.slice(0, 6).map(card).join('') || '

    No reviews.

    '; if (r.items.length > 6) { list.insertAdjacentHTML('beforeend', ``); 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 = `

    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.

    ` + w.items.map((x, i) => `

    ${x.role}

    ${esc(x.agent)} ${esc(x.lane || '')} · ${time(x.from_ts)} → ${time(x.to_ts)}${x.reconstructed ? RECON : ''} ${x.source ? `trace file ↗` : ''}
    ${x.has_trace ? '' : '

    No trace for this agent.

    '}
    `).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 ? '

    No records in this window.

    ' : '')); 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 = `${time(rec.timestamp).slice(11)}`; 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 `
    ${t} result · ${esc(m.toolName)}${m.isError ? ' · error' : ''} · ${text.length} chars
    ${esc(text)}
    `; } 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 `
    ${t} system prompt
    ${esc(text)}
    `; } const body = parts.map(p => { if (p.type === 'thinking') return `
    ${esc(p.thinking)}
    `; 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 `
    ${esc(p.name)}
    ${esc(main)}${Object.keys(rest).length && main !== '' ? '\n' : ''}${Object.keys(rest).length ? esc(JSON.stringify(rest, null, 1)) : ''}
    `; } return `
    ${esc(p.text)}
    `; }).join(''); return `
    ${esc(role)} ${t}
    ${body}
    `; } const msgCard = (m, hl) => `
    #${esc(m.channel)}${esc(m.author)} ${time(m.ts)}${m.reason ? `${m.reason === 'mention' ? 'mentions the PR' : 'author post'}` : ''} thread →${m.source ? ` on the board ↗` : ''}
    ${rich(m.body)}
    `; async function messagesTab(panel, n) { panel.innerHTML = `
    `; 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 ? '' : '

    No linked posts.

    ')); 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 = '

    Loading…

    '; 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 = `
    PR #${n} title

    ${esc(p.title)}

    ${esc(p.author)} · ${esc(p.state)} · opened ${time(p.opened_ts).slice(0, 16)} · never merged

    Loading…

    `; 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: 'Dataset', repo: 'HuggingFaceSwarms/pybot-traces', url: 'https://huggingface.co/datasets/HuggingFaceSwarms/pybot-traces', what: 'Every agent\'s session log: 1,000 agents (3 rebuilt from the controller\'s event log, which may have gaps), 51.3M records, ~33 GB of Pi JSONL (session header, system/user/assistant/tool-result messages, controller events). README and Apache-2.0 licence in the dataset.', layout: 'traces//.jsonl · traces/_manifest.jsonl (one row per agent)', cmds: ['hf download HuggingFaceSwarms/pybot-traces --repo-type dataset --include "traces/_manifest.jsonl" --local-dir pybot-traces', 'hf download HuggingFaceSwarms/pybot-traces --repo-type dataset --include "traces/answers/*" --local-dir pybot-traces'] }, { 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/).', 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 up to 24cbc04, plus a few later commits that only change the dataset card.', layout: 'a git repository; each commit page is /commit/, each file /blob//', 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 = `
    Data sources

    Where the data lives

    Everything here is the scrubbed release data of the PyBot run, cut at commit 24cbc04 (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 API and llms.txt; each API answer carries a source link back to these repositories.

    ${SOURCES.map(d => `

    ${d.name}

    ${d.kind} ${d.repo} ↗${d.viewer ? ` viewer ↗` : ''}

    ${esc(d.what)}

    ${esc(d.layout)}

    ${d.cmds.map(esc).join('\n')}
    `).join('')}`; } async function messagePage(id) { $app.innerHTML = '

    Loading…

    '; try { const d = await api('/api/messages/' + id), m = d.message; document.title = `Message ${id} · PyBot Data Explorer`; $app.innerHTML = `

    #${esc(m.channel)} · thread ${d.thread_root}

    ${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` : ''}.

    ${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();