Spaces:
Running

File size: 30,601 Bytes
3de9c7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aaf21d0
3de9c7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/* Cooperation Bench Space: logos drawn with the even-odd fill rule (their holes are cut-outs); code lines marked so
   phones can indent a wrapped command under its first line (the newlines stay, so Copy copies the same text). */
(() => {
  const mark = () => { const pre = document.getElementById("codePre"); if (!pre || pre.classList.contains("lines")) return;
    pre.innerHTML = pre.innerHTML.split("\n").map(l => `<span class="ln">${l}</span>`).join("\n"); pre.classList.add("lines"); };
  new MutationObserver(() => { const pre = document.getElementById("codePre"); if (pre && !pre.querySelector(".ln")) { pre.classList.remove("lines"); mark(); } })
    .observe(document.body, { childList: true, subtree: true, characterData: false });
  mark();
})();
/* Cooperation Bench Space: logos drawn with the even-odd fill rule (their holes are cut-outs). */
(() => {
  const D = new Set((window.LOGO_EVENODD || []).map(m => MODEL_LOGO[m]).filter(Boolean));
  const fix = root => root.querySelectorAll && root.querySelectorAll("svg path").forEach(p => { if (D.has(p.getAttribute("d"))) p.setAttribute("fill-rule", "evenodd"); });
  fix(document); new MutationObserver(ms => ms.forEach(m => m.addedNodes.forEach(n => n.nodeType === 1 && fix(n)))).observe(document.body, { childList: true, subtree: true });
})();
/* Page title per route, so a tab or a shared link says what it shows. */
(() => {
  const base = "Cooperation Bench Explorer";
  const set = () => { const h = location.hash.slice(1); let m, t = base;
    if ((m = h.match(/^run-(.+)--(.+)$/)) && TASKS[m[1]]) { const r = (TASKS[m[1]].runs || {})[m[2]], M = r && MODELS[r.model]; t = `${TASKS[m[1]].title}: ${M ? M.name + " run" : "run " + m[2]} · ${base}`; }
    else if ((m = h.match(/^res-(.+)--(.+)$/)) && TASKS[m[1]]) { const r = ((window.SUMS || {})[m[1]] || {})[m[2]], M = r && MODELS[r.m]; t = `${TASKS[m[1]].title}: ${M ? M.name + " run summary" : "run summary"} · ${base}`; }
    else if ((m = h.match(/^task-(.+)$/)) && TASKS[m[1]]) t = `${TASKS[m[1]].title} · ${base}`;
    else if (h === "tasks") t = `Tasks · ${base}`;
    document.title = t; };
  addEventListener("hashchange", set); addEventListener("cb:loaded", set); set();
})();
/* A run without a replay (#res-<task>--<run>): the judge's record of it, from data/sum/<task>.js, loaded when it opens. */
(() => {
  const esc = s => String(s ?? "").replace(/[&<>"']/g, c => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
  const tone = { bad: "bad", ok: "ok", pen: "bad pen" };
  const load = id => new Promise((ok, no) => { const s = document.createElement("script"); s.src = `data/sum/${id}.js?v=${TASKS[id].sumv || ""}`;
    s.onload = () => { ok(); dispatchEvent(new Event("cb:loaded")); }; s.onerror = no; document.head.appendChild(s); });
  const name = x => /^[onr]\d+$/.test(x) ? x.slice(1) : x;
  const row = (t, [k, v, ag, why]) => {
    const R = (t.rubric || []).find(x => x[0] === k), pts = R ? R[2] : null, neg = pts != null ? pts < 0 : k[0] === "n", P = Math.abs(pts || 0);
    const [cls, st, got] = v == null ? ["skip", "Not graded", ""]
      : neg ? (v === 1 ? ["lost", "Penalty applied", `−${P}`] : ["ok", "Avoided", "0"])
      : v >= 1 ? ["ok", "Earned", `+${P}`] : v <= 0 ? ["lost", "Missed", `0 / ${P}`] : ["part", "Partly earned", `${Math.round(v * P)} / ${P}`];
    return `<li class="sm-row ${cls}"><div class="sm-rh"><span class="sm-k mono">${neg ? "Penalty" : "Credit"} ${esc(name(k))}</span><span class="sm-st">${st}</span><b class="sm-pts mono">${got}</b></div>
      <p class="sm-crit">${esc(R ? R[1] : "This row is not in the task's final rubric.")}</p>
      ${why ? `<p class="sm-why"><span class="lab">The judge</span>${esc(why)}</p>` : ""}${ag ? `<span class="sm-ag mono">${ag[0]} of ${ag[1]} judge samples agree</span>` : ""}</li>`; };
  window.CBRES = (id, rid, header) => {
    const app = document.getElementById("app"), t = TASKS[id];
    const page = body => { app.innerHTML = header() + `<main class="wrap rsum"><nav class="crumb"><a class="bk" href="#task-${id}"><span class="btn-t"><i aria-hidden="true">←</i>Back to task</span></a><a href="#home">Cooperation Bench</a><span>/</span><a href="#task-${id}">${esc(t.title)}</a><span>/</span><span>run ${esc(rid)}</span></nav>${body}
      <footer class="foot">${LOGO}<span>${window.LAUNCHED ? "Cooperation Bench" : "Cooperation Bench · internal preview"}</span><span class="sp">Every person shown is simulated.</span></footer></main>`; };
    if (!(window.SUMS || {})[id]) { page(`<p class="sm-wait">Loading the run…</p>`);
      load(id).then(() => { if (location.hash === `#res-${id}--${rid}`) window.CBRES(id, rid, header); }, () => page(`<p class="sm-wait">This run did not load. Check the connection and reload the page.</p>`)); return; }
    const r = SUMS[id][rid];
    if (!r) return page(`<p class="sm-wait">This task has no run ${esc(rid)}.</p>`);
    const M = MODELS[r.m] || { name: r.m }, cat = ((t.stats || {}).cats || []).find(c => c.k === r.c) || { label: "", tone: "mute" };
    page(`<header class="sm-head"><div class="sm-top"><span class="c-mod" data-m="${esc(r.m)}"><svg class="mlogo" viewBox="0 0 24 24" aria-hidden="true"><path d="${MODEL_LOGO[r.m] || ""}"/></svg>${esc(M.name)}</span><span class="chip big ${r.v === "pass" ? "ok" : "bad"}">${r.v === "pass" ? "Pass" : "Fail"}</span><b class="sm-score mono">${r.s != null ? Math.round(r.s * 100) : "–"}<small>/100</small></b></div>
      <h1 class="sm-ttl">${esc(t.title)}</h1><p class="sm-cat"><i class="sq ${tone[cat.tone] || "mute"}" aria-hidden="true"></i>${!r.rows.length && r.to ? "Failed: the run hit its time limit before it was graded" : esc(cat.label) + (r.to ? " · the run hit its time limit" : "")}</p>
      <p class="sm-note">This run has no step-by-step replay. This is the judge's record of it: every rubric row, what the run got on it, and the judge's reason. The judge reads only the end state of the company's systems, not the run's steps. The full transcript is below.</p></header>
      ${r.rows.length ? `<ol class="sm-rows">${r.rows.map(x => row(t, x)).join("")}</ol>` : `<p class="sm-none">${r.to ? "The run hit its time limit, so it ended before the judge graded it. It has no rubric rows and scores 0." : "The judge's record has no rubric rows for this run."}</p>`}
      ${window.CBTX ? CBTX.section(id, rid, true) : ""}
      <section class="sm-cmd"><h2 class="belowh">Reproduce this run</h2><div class="sm-code"><pre class="mono">${esc(r.cmd)}</pre><button class="sm-copy" type="button">Copy</button></div>
      <p class="sm-meta mono">Task version ${esc(r.ver)}${r.tc != null ? ` · ${r.tc} tool calls` : ""} · ${esc(r.rid)}</p></section>`);
    window.CBTX && CBTX.wire(app.querySelector("#bTx"));
    const b = app.querySelector(".sm-copy"); b.addEventListener("click", () => { const done = () => { b.textContent = "Copied"; setTimeout(() => b.textContent = "Copy", 1500); };
      try { navigator.clipboard.writeText(app.querySelector(".sm-code pre").textContent).then(done, () => {}); } catch { } });
  };
})();
/* Copy link (task, run and summary pages). On huggingface.co the Space runs in an iframe and the address bar stays on the
   Space's home, so copying the address shares the home page. This copies the page being viewed: on huggingface.co, the
   Space's address with the page's #route (HF hands it to the Space on load); on the Space's own site, the task's preview
   page (t/<task>.html) or the page's own address. Never the private-access query. Syncing HF's address bar instead (its
   postMessage) would add a history entry per page and break Back, so the Space doesn't. */
(() => {
  const HF = "https://huggingface.co/spaces/ScaleAI/cooperation-bench";
  const onHF = (() => { try { const a = location.ancestorOrigins; if (a && a.length) return [...a].includes("https://huggingface.co"); return window.parent !== window && /^https:\/\/huggingface\.co\//.test(document.referrer); } catch { return false; } })();
  const link = (hf = onHF) => { const h = location.hash, m = h.match(/^#task-(rz-[\w-]+)$/);
    if (hf) return HF + h;
    return m && TASKS[m[1]] ? `${location.origin}/t/${m[1]}.html` : location.origin + location.pathname + h; };
  window.CBLINK = link;
  const copy = async text => { try { await navigator.clipboard.writeText(text); return true; } catch { }
    try { const ta = Object.assign(document.createElement("textarea"), { value: text }); ta.setAttribute("readonly", ""); ta.style.cssText = "position:fixed;top:0;opacity:0";
      document.body.appendChild(ta); ta.select(); const ok = document.execCommand("copy"); ta.remove(); return ok; } catch { return false; } };
  const ICON = '<svg class="cl-i" viewBox="0 0 16 16" width="14" height="14" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"><path d="M6.6 9.4a2.6 2.6 0 0 0 3.7 0l2.2-2.2a2.6 2.6 0 0 0-3.7-3.7l-.9.9"/><path d="M9.4 6.6a2.6 2.6 0 0 0-3.7 0L3.5 8.8a2.6 2.6 0 0 0 3.7 3.7l.9-.9"/></svg>';
  const DONE = '<svg class="cl-i" viewBox="0 0 16 16" width="14" height="14" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="m3.5 8.5 3 3 6-7"/></svg>';
  let live;
  const add = () => { if (!["task", "run", "res"].includes(document.body.dataset.view)) return;
    const c = document.querySelector("main .crumb"); if (!c || c.querySelector(".cl") || !c.lastElementChild) return;
    if (!live) { live = Object.assign(document.createElement("span"), { className: "cl-sr" }); live.setAttribute("aria-live", "polite"); document.body.appendChild(live); }
    const b = document.createElement("button"); b.type = "button"; b.className = "bk cl"; b.title = "Copy a link to this page";
    const idle = () => { b.classList.remove("done"); b.innerHTML = `<span class="btn-t">${ICON}<span class="cl-t">Copy link</span></span>`; };
    idle(); b.setAttribute("aria-label", "Copy a link to this page");
    b.addEventListener("click", async () => { const ok = await copy(link()); clearTimeout(b._t);
      b.classList.add("done"); b.innerHTML = `<span class="btn-t">${ok ? DONE : ICON}<span class="cl-t">${ok ? "Link copied" : "Copy failed"}</span></span>`;
      live.textContent = ok ? "Link copied" : "The link could not be copied"; b._t = setTimeout(() => { idle(); live.textContent = ""; }, 1800); });
    c.insertBefore(b, c.lastElementChild);  /* before the last crumb, which phones keep showing; CSS order puts the button last */ };
  new MutationObserver(add).observe(document.getElementById("app"), { childList: true }); addEventListener("hashchange", () => setTimeout(add, 0)); add();
})();

/* The leaderboard's cost chart: each model's solver cost per task (list prices, log scale) against pass³ or pass@1, with
   the cost frontier, in the models' logos and colours from the leaderboard. On wide screens it sits beside the leaderboard,
   pinned, and fills as the leaderboard scrolls: each row's logo lifts off and lands on its point, then the frontier draws.
   Narrower, it builds itself once it comes into view; with reduced motion it is simply there. */
(() => {
  const X0 = 0.2, X1 = 50, $ = (q, r = document) => r.querySelector(q), $$ = (q, r = document) => [...r.querySelectorAll(q)];
  const esc = s => String(s ?? "").replace(/[&<>"']/g, c => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
  const clamp = (v, a, b) => Math.max(a, Math.min(b, v)), ease = t => t < .5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2;
  const usd = v => "$" + v.toFixed(2), pct = v => (v * 100).toFixed(1) + "%";
  const Y = { pass3: "pass³", pass1: "pass@1" };
  const logo = m => `<svg class="mlogo" viewBox="0 0 24 24" aria-hidden="true" data-m="${m}" style="fill:var(--mcol)"><path d="${MODEL_LOGO[m]}"/></svg>`;
  const el = (tag, cls, html) => { const e = document.createElement(tag); if (cls) e.className = cls; if (html != null) e.innerHTML = html; return e; };
  const frontier = (list, k) => new Set(list.filter(a => !list.some(b => b !== a && b.cost <= a.cost && b[k] >= a[k] && (b.cost < a.cost || b[k] > a[k]))).map(a => a.m));

  window.CBPARETO = () => {
    const pane = document.getElementById("lbPareto"), D = window.LB;
    if (!pane || !D || !D.models.length) return;
    window.__ppOff && window.__ppOff();
    const still = new URLSearchParams(location.search).has("still") || matchMedia("(prefers-reduced-motion:reduce)").matches;
    const wideQ = matchMedia("(min-width:1101px) and (min-height:640px)"), wide = () => wideQ.matches && !still;
    const ms = D.models, by = Object.fromEntries(ms.map(x => [x.m, x])), priced = ms.filter(x => x.cost != null), unpriced = ms.filter(x => x.cost == null);
    const name = m => MODELS[m].name;
    let metric = "pass3", front = frontier(priced, metric), W = 0, H = 0, R = 12, pos = {}, ymax = .4, entered = false;
    const M = { l: 44, r: 16, t: 14, b: 34 };

    pane.setAttribute("aria-label", "Solver cost per task against the leaderboard's pass rates");
    pane.innerHTML = `<div class="panehead ph2"><span class="lab">Cost against <span class="pp-ym">pass³</span></span>
      <div class="seg pp-seg" role="group" aria-label="Measure on the vertical axis"><button type="button" aria-pressed="true" data-y="pass3">pass³</button><button type="button" aria-pressed="false" data-y="pass1">pass@1</button></div></div>
      <p class="pp-sub">Each model's solver cost per task, at list prices, on a log scale. ${matchMedia("(hover:none)").matches ? "Tap" : "Hover"} a logo for its numbers.</p>
      <div class="pp-plot"><svg class="pp-svg" aria-hidden="true"></svg><div class="pp-pts"></div><p class="pp-hint">Scroll the leaderboard: each model lands at its cost.</p></div>
      <div class="pp-foot"><span class="pp-key"><i></i>Cost frontier: no model passes more for less</span>${unpriced.length ? '<span class="pp-tray"><span class="pp-tl">No per-token list price</span></span>' : ""}</div>
      <div class="pp-tip" hidden></div>`;
    const plot = pane.querySelector(".pp-plot"), svg = pane.querySelector(".pp-svg"), layer = pane.querySelector(".pp-pts"), tip = pane.querySelector(".pp-tip"),
      hint = pane.querySelector(".pp-hint"), tray = pane.querySelector(".pp-tray");
    const label = m => { const x = by[m]; return `${name(m)}, ${x.h}, effort ${x.e}: ${x.cost == null ? "no per-token list price" : usd(x.cost) + " per task"}, pass³ ${pct(x.pass3)}, pass@1 ${pct(x.pass1)}`; };
    const mkChip = m => { const b = el("button", "pp-pt", logo(m)); b.type = "button"; b.dataset.m = m; b.setAttribute("aria-label", label(m)); return b; };
    const chips = {}, labels = {};
    priced.forEach(x => { chips[x.m] = layer.appendChild(mkChip(x.m)); labels[x.m] = layer.appendChild(el("span", "pp-lb", esc(name(x.m)))); });
    unpriced.forEach(x => { chips[x.m] = tray.appendChild(mkChip(x.m)); chips[x.m].classList.add("tr"); });

    const sx = c => M.l + Math.log10(c / X0) / Math.log10(X1 / X0) * (W - M.l - M.r);
    const zeroY = () => H - M.b - R - 3, sy = v => zeroY() - v / ymax * (zeroY() - M.t - R);

    function layout() {
      W = plot.clientWidth; if (!W) return;
      const small = W < 520;
      H = wide() ? clamp(innerHeight - 340, 300, 500) : clamp(Math.round(W * .72), 260, 420);
      plot.style.height = H + "px"; R = small ? 10 : 12; pane.style.setProperty("--r", R + "px");
      ymax = Math.max(.1, Math.ceil(Math.max(...ms.map(x => x[metric])) * 10 - 1e-9) / 10);
      front = frontier(priced, metric);
      // each chip at its point; chips that would overlap move apart a little (a leader line keeps the exact point)
      const P = priced.map(x => ({ m: x.m, x0: sx(x.cost), y0: sy(x[metric]) })); P.forEach(p => { p.x = p.x0; p.y = p.y0; });
      const gap = 2 * R + 3;
      for (let it = 0; it < 160; it++) {
        let moved = false;
        for (let i = 0; i < P.length; i++) for (let j = i + 1; j < P.length; j++) {
          const a = P[i], b = P[j]; let dx = b.x - a.x, dy = b.y - a.y, d = Math.hypot(dx, dy);
          if (d >= gap) continue;
          if (d < .01) { dx = 0; dy = -1; d = 1; }
          const k = (gap - d) / 2 / d; a.x -= dx * k; a.y -= dy * k; b.x += dx * k; b.y += dy * k; moved = true;
        }
        P.forEach(p => { p.x += (p.x0 - p.x) * .03; p.y += (p.y0 - p.y) * .03; p.x = clamp(p.x, M.l + R, W - M.r - R); p.y = clamp(p.y, M.t + R, zeroY() + 4); });
        if (!moved) break;
      }
      const cap = small ? 6 : 14;  // a chip never strays far from its point: past this, chips overlap instead of misleading
      P.forEach(p => { const dx = p.x - p.x0, dy = p.y - p.y0, d = Math.hypot(dx, dy); if (d > cap) { p.x = p.x0 + dx / d * cap; p.y = p.y0 + dy / d * cap; } });
      P.sort((a, b) => by[a.m][metric] - by[b.m][metric]).forEach((p, i) => { chips[p.m].style.zIndex = 1 + i; });  // the stronger on top
      pos = Object.fromEntries(P.map(p => [p.m, p]));
      // labels: frontier models first, then by the measure; the first free place around the chip, or none (hover shows it)
      const ctx = (layout.c = layout.c || document.createElement("canvas").getContext("2d"));
      ctx.font = `500 12px ${getComputedStyle(pane).fontFamily}`;
      const boxes = P.map(p => [p.x - R, p.y - R, p.x + R, p.y + R]);
      const line = [], fl = priced.filter(x => front.has(x.m)).sort((a, b) => a.cost - b.cost).map(x => [sx(x.cost), sy(x[metric])]);
      for (let i = 1; i < fl.length; i++) {  // the frontier line, as small boxes along it (a frontier model's label may touch it)
        const [ax, ay] = fl[i - 1], [bx, by2] = fl[i], n = Math.ceil(Math.hypot(bx - ax, by2 - ay) / 6);
        for (let k = 0; k <= n; k++) { const x = ax + (bx - ax) * k / n, y = ay + (by2 - ay) * k / n; line.push([x - 2, y - 2, x + 2, y + 2]); }
      }
      const hits = (b, list) => list.some(o => b[0] < o[2] && b[2] > o[0] && b[1] < o[3] && b[3] > o[1]);
      const free = (b, onLine) => b[0] >= M.l - 6 && b[2] <= W - 2 && b[1] >= 0 && b[3] <= H - M.b + 4 && !hits(b, boxes) && (onLine || !hits(b, line));
      const order = [...P].sort((a, b) => (front.has(b.m) - front.has(a.m)) || (by[b.m][metric] - by[a.m][metric]) || (by[a.m].cost - by[b.m].cost));
      const top = new Set(order.slice(0, small ? 5 : 99).map(p => p.m));
      order.forEach(p => {
        const t = name(p.m), w = Math.ceil(ctx.measureText(t).width), h = 14; p.label = null; p.lead = null;
        if (!top.has(p.m)) return;
        // around the chip; then, for the frontier and the strongest, a little farther out with a short leader line
        const ring = g => [[p.x + g, p.y - h / 2], [p.x - g - w, p.y - h / 2], [p.x - w / 2, p.y - g - h], [p.x - w / 2, p.y + g],
          [p.x + g - 3, p.y - g - h + 5], [p.x + g - 3, p.y + g - 5], [p.x - g - w + 3, p.y - g - h + 5], [p.x - g - w + 3, p.y + g - 5]];
        // score every free place: nearer is better, and a place beside another model's chip would read as its label
        let best = null;
        [[R + 5, false], [R + 20, true], [R + 34, true]].forEach(([g, lead], ri) => ring(g).forEach(([lx, ly], ci) => {
          const b = [lx - 2, ly - 1, lx + w + 2, ly + h + 1];
          if (!free(b, front.has(p.m))) return;
          const dist = o => Math.hypot(Math.max(b[0] - o.x, 0, o.x - b[2]), Math.max(b[1] - o.y, 0, o.y - b[3]));
          const own = dist(p), other = Math.min(...P.filter(o => o !== p).map(dist));
          if (lead ? other < R + 8 : other <= own + 4) return;  // it must read as this chip's label, not a neighbour's
          const score = ri * 10 + ci;
          if (!best || score < best.score) best = { score, b, lx, ly, lead };
        }));
        if (best) { p.label = [Math.round(best.lx), Math.round(best.ly)]; boxes.push(best.b); if (best.lead) p.lead = best.b; }
      });
      draw();
      P.forEach(p => {
        chips[p.m].style.transform = `translate(${p.x - R}px,${p.y - R}px)`; chips[p.m].classList.toggle("fr", front.has(p.m));
        const lb = labels[p.m]; lb.classList.toggle("fr", front.has(p.m)); lb.hidden = !p.label;
        if (p.label) { lb.style.left = p.label[0] + "px"; lb.style.top = p.label[1] + "px"; }
      });
      pane.querySelector(".pp-ym").textContent = Y[metric];
    }

    function draw() {
      const s = [], xt = (W < 520 ? [.2, 1, 5, 20] : [.2, .5, 1, 2, 5, 10, 20, 50]), yt = [];
      for (let v = 0; v <= ymax + 1e-9; v += .1) yt.push(+v.toFixed(2));
      yt.forEach(v => s.push(`<line class="gl" x1="${M.l}" x2="${W - M.r}" y1="${sy(v)}" y2="${sy(v)}"/><text class="tk" x="${M.l - 8}" y="${sy(v) + 4}" text-anchor="end">${Math.round(v * 100)}%</text>`));
      xt.forEach(v => s.push(`<line class="gl gx" x1="${sx(v)}" x2="${sx(v)}" y1="${M.t}" y2="${zeroY() + R}"/><text class="tk" x="${sx(v)}" y="${H - M.b + 18}" text-anchor="middle">${v < 1 ? "$" + v.toFixed(2) : "$" + v}</text>`));
      s.push(`<text class="ax" x="${W - M.r}" y="${H - 2}" text-anchor="end">Solver cost per task</text><text class="ax" x="${M.l - 8}" y="${M.t - 2}" text-anchor="end">${Y[metric]}</text>`);
      Object.values(pos).forEach(p => { if (p.lead) { const [l, t2, r, b] = p.lead, tx = clamp(p.x, l, r), ty = clamp(p.y, t2, b), a = Math.atan2(ty - p.y, tx - p.x);
        s.push(`<g class="ld ll" data-m="${p.m}"><line x1="${(p.x + Math.cos(a) * (R + 1)).toFixed(1)}" y1="${(p.y + Math.sin(a) * (R + 1)).toFixed(1)}" x2="${tx.toFixed(1)}" y2="${ty.toFixed(1)}"/></g>`); } });
      Object.values(pos).forEach(p => { if (Math.hypot(p.x - p.x0, p.y - p.y0) > 3) s.push(`<g class="ld" data-m="${p.m}"><line x1="${p.x0}" y1="${p.y0}" x2="${p.x}" y2="${p.y}"/><circle cx="${p.x0}" cy="${p.y0}" r="2.2"/></g>`); });
      const f = priced.filter(x => front.has(x.m)).sort((a, b) => a.cost - b.cost);
      const d = f.map((x, i) => `${i ? "L" : "M"}${sx(x.cost).toFixed(1)},${sy(x[metric]).toFixed(1)}`).join("");
      s.push(`<path class="fr" d="${d}"/>`);
      svg.setAttribute("viewBox", `0 0 ${W} ${H}`); svg.innerHTML = s.join("");
      const fp = svg.querySelector(".fr"), L = fp.getTotalLength(); fp.style.strokeDasharray = L; fp.dataset.l = L;
    }

    // tooltip and linked highlighting (chart point <-> leaderboard row)
    const rows = () => $$("#resBars .mrow.lbr");
    function hl(m) {
      pane.classList.toggle("pp-hl", !!m);
      Object.entries(chips).forEach(([k, c]) => c.classList.toggle("on", k === m));
      Object.entries(labels).forEach(([k, l]) => l.classList.toggle("on", k === m));
      svg.querySelectorAll(".ld").forEach(g => g.classList.toggle("on", g.dataset.m === m));
      rows().forEach(r => r.classList.toggle("lk", r.dataset.m === m));
    }
    function show(m) {
      const x = by[m], c = chips[m]; hl(m);
      tip.innerHTML = `<b>${logo(m)}${esc(name(m))}</b><span class="mono">${esc(x.h)} · ${esc(x.e)}</span><dl><dt>pass³</dt><dd>${pct(x.pass3)}</dd><dt>pass@1</dt><dd>${pct(x.pass1)}</dd><dt>Cost per task</dt><dd>${x.cost == null ? "no list price" : usd(x.cost)}</dd></dl>${front.has(m) ? "<em>On the cost frontier</em>" : ""}`;
      tip.hidden = false;
      const pr = pane.getBoundingClientRect(), cr = c.getBoundingClientRect(), tw = tip.offsetWidth, th = tip.offsetHeight;
      let lx = cr.right - pr.left + 10, ly = cr.top - pr.top + cr.height / 2 - th / 2;
      if (lx + tw > pr.width - 8) lx = cr.left - pr.left - tw - 10;
      tip.style.left = clamp(lx, 8, pr.width - tw - 8) + "px"; tip.style.top = clamp(ly, 8, pr.height - th - 8) + "px";
    }
    const hide = () => { tip.hidden = true; hl(null); };
    let pinned = null;
    Object.entries(chips).forEach(([m, c]) => {
      c.addEventListener("pointerenter", e => { if (e.pointerType !== "touch") show(m); });
      c.addEventListener("pointerleave", e => { if (e.pointerType !== "touch" && pinned !== m) hide(); });
      c.addEventListener("focus", () => show(m)); c.addEventListener("blur", () => { if (pinned !== m) hide(); });
      c.addEventListener("click", e => { e.stopPropagation(); if (pinned === m) { pinned = null; hide(); } else { pinned = m; show(m); } });
    });
    const outside = e => { if (pinned && !e.target.closest(".pp-pt")) { pinned = null; hide(); } };
    document.addEventListener("click", outside);
    const onRow = e => { const r = e.target.closest && e.target.closest("#resBars .mrow.lbr"); if (r) hl(r.dataset.m); };
    const offRow = e => { const r = e.target.closest && e.target.closest("#resBars .mrow.lbr"); if (r && !pinned) hl(null); };
    const bars = $("#resBars"); bars && bars.addEventListener("pointerover", onRow); bars && bars.addEventListener("pointerout", offRow);

    // the measure: pass³ or pass@1
    pane.querySelector(".pp-seg").addEventListener("click", e => {
      const b = e.target.closest("button"); if (!b || b.dataset.y === metric) return;
      metric = b.dataset.y; pane.querySelectorAll(".pp-seg button").forEach(x => x.setAttribute("aria-pressed", x === b));
      hide(); layout(); const fp = svg.querySelector(".fr"); fp.style.transition = "none"; fp.style.strokeDashoffset = fp.dataset.l;
      requestAnimationFrame(() => requestAnimationFrame(() => { fp.style.transition = "stroke-dashoffset .9s ease .25s"; fp.style.strokeDashoffset = 0; }));
      wide() && frame();
    });

    // wide screens: the leaderboard scrolls, its logos fly onto the pinned chart
    let fly = null, raf = 0;
    function flyOn() {
      if (fly) return; fly = document.body.appendChild(el("div", "pp-fly"));
      fly.setAttribute("aria-hidden", "true");
      ms.forEach(x => { const c = fly.appendChild(el("span", "pp-pt pp-cl", logo(x.m))); c.dataset.m = x.m; });
    }
    function frame() {
      raf = 0; if (!wide()) return;
      flyOn();
      const tb = $("#resBars"), rs = rows(); if (!tb || !rs.length) return;
      // P runs from 0, when the leaderboard's top is a third of a screen below the chart's pinned place, to 1 when the
      // leaderboard's end comes into view, so the finished chart stays pinned while the last rows are read
      const stickTop = parseFloat(getComputedStyle(pane).top) || 76, lead = innerHeight * .35, lp = tb.closest(".pane").getBoundingClientRect();
      const P = clamp((stickTop + lead - lp.top) / Math.max(240, stickTop + lead - innerHeight + lp.height), 0, 1);
      const n = ms.length, dur = .2;
      hint.style.opacity = 1 - clamp(P / .06, 0, 1);
      ms.forEach((x, i) => {
        const f = clamp((P - i / (n - 1) * (.82 - dur)) / dur, 0, 1), c = chips[x.m], clone = fly.querySelector(`.pp-cl[data-m="${x.m}"]`);
        const row = rs.find(r => r.dataset.m === x.m), rl = row && row.querySelector(".mlogo");
        c.classList.toggle("in", f >= 1); labels[x.m] && labels[x.m].classList.toggle("in", f >= 1);
        svg.querySelectorAll(`.ld[data-m="${x.m}"]`).forEach(g => g.classList.toggle("in", f >= 1));
        row && row.classList.toggle("fl", f > 0 && f < 1);
        if (!(f > 0 && f < 1) || !rl) { clone.style.opacity = 0; return; }
        const a = rl.getBoundingClientRect(), b = c.getBoundingClientRect(), e = ease(f);
        const ax = a.left + a.width / 2, ay = a.top + a.height / 2, bx = b.left + b.width / 2, by2 = b.top + b.height / 2;
        const cx = (ax + bx) / 2, cy = Math.min(ay, by2) - 70, u = 1 - e;
        const px = u * u * ax + 2 * u * e * cx + e * e * bx, py = u * u * ay + 2 * u * e * cy + e * e * by2;
        clone.style.opacity = 1; clone.style.setProperty("--disc", e.toFixed(3));
        clone.style.transform = `translate(${px - R}px,${py - R}px) scale(${(1.15 - .15 * e).toFixed(3)})`;
      });
      const F = clamp((P - .8) / .2, 0, 1), fp = svg.querySelector(".fr");
      if (fp) { fp.style.transition = "none"; fp.style.strokeDashoffset = (+fp.dataset.l * (1 - F)).toFixed(1); }
    }
    const tick = () => { if (!raf) raf = requestAnimationFrame(frame); };

    // narrower screens: one build when the chart comes into view
    let io = null;
    function enter() {
      if (entered) return; entered = true;
      const keys = Object.keys(pos), fp = svg.querySelector(".fr");
      if (still) { Object.values(chips).forEach(c => c.classList.add("in")); Object.values(labels).forEach(l => l.classList.add("in")); svg.querySelectorAll(".ld").forEach(g => g.classList.add("in")); fp.style.strokeDashoffset = 0; return; }
      const order = ms.map(x => x.m).filter(m => pos[m]);
      order.forEach((m, i) => { const c = chips[m]; c.style.transition = "none"; c.style.transform = `translate(${M.l + 6}px,${M.t + i * (zeroY() - M.t) / order.length}px)`; });
      plot.offsetWidth;
      order.forEach((m, i) => { const c = chips[m], p = pos[m]; c.style.transition = `transform .9s cubic-bezier(.2,.7,.2,1) ${i * 45}ms, opacity .3s ${i * 45}ms`; c.classList.add("in"); c.style.transform = `translate(${p.x - R}px,${p.y - R}px)`; });
      const done = order.length * 45 + 900;
      setTimeout(() => { Object.values(labels).forEach(l => l.classList.add("in")); svg.querySelectorAll(".ld").forEach(g => g.classList.add("in")); fp.style.transition = "stroke-dashoffset 1s ease"; fp.style.strokeDashoffset = 0; unpriced.forEach(x => chips[x.m].classList.add("in")); }, done);
      setTimeout(() => order.forEach(m => { chips[m].style.transition = ""; }), done + 1000);
    }

    function start() {
      layout();
      if (wide()) { hint.hidden = false; io && io.disconnect(); frame(); return; }
      hint.hidden = true; fly && (fly.remove(), fly = null);
      if (entered) { Object.values(chips).forEach(c => c.classList.add("in")); Object.values(labels).forEach(l => l.classList.add("in")); svg.querySelectorAll(".ld").forEach(g => g.classList.add("in")); svg.querySelector(".fr").style.strokeDashoffset = 0; return; }
      svg.querySelector(".fr").style.strokeDashoffset = svg.querySelector(".fr").dataset.l;
      io = new IntersectionObserver(es => es.forEach(e => { if (e.isIntersecting) { io.disconnect(); enter(); } }), { threshold: .3 });
      io.observe(plot);
    }
    let rt = 0; const onResize = () => { clearTimeout(rt); rt = setTimeout(start, 120); };
    addEventListener("scroll", tick, { passive: true }); addEventListener("resize", onResize);
    const ro = window.ResizeObserver ? new ResizeObserver(() => onResize()) : null; ro && ro.observe(plot);
    (document.fonts ? document.fonts.ready : Promise.resolve()).then(start);
    start();
    window.__ppOff = () => { removeEventListener("scroll", tick); removeEventListener("resize", onResize); document.removeEventListener("click", outside); io && io.disconnect(); ro && ro.disconnect(); fly && fly.remove(); fly = null; window.__ppOff = null; };
  };
})();