File size: 38,811 Bytes
a2222d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c75e65
c0e2e7e
a2222d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c75e65
a2222d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c0e2e7e
 
a2222d5
c0e2e7e
 
a2222d5
 
 
 
 
 
36355f6
a2222d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1510e8b
a2222d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
'use strict';
const $app = document.getElementById('app');
const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[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}<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 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 = `
    <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 = (x.reconstructed ? RECON : '') + `<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 ↗</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.reconstructed ? RECON : ''}
      ${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: '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/<lane>/<agent>.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/<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 up to 24cbc04, plus a few later commits that only change the dataset card.',
    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('')}`;
}

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