-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
4229 lines (3889 loc) · 150 KB
/
Copy pathapp.js
File metadata and controls
4229 lines (3889 loc) · 150 KB
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
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* ============================================================
TERMS-Bench leaderboard renderer.
Data source: window.TERMS_DATA, built by leaderboard/build_data.py.
============================================================ */
(function () {
const data = window.TERMS_DATA;
if (!data) {
console.error("TERMS_DATA not loaded");
return;
}
/* --------------------------- Constants --------------------------- */
const SERIES_COLORS = [
"--s1", "--s2", "--s3", "--s4", "--s5",
"--s6", "--s7", "--s8", "--s9", "--s10",
];
const KIND_FILTERS = [
{ id: "all", label: "All" },
{ id: "frontier", label: "Frontier" },
{ id: "open", label: "Open-weight" },
{ id: "baseline", label: "Baselines" },
];
// Metrics whose lower values are better — bar fills reverse orientation.
const LOWER_IS_BETTER = new Set(["fagr_minus", "be_type", "crit_viol_pct"]);
// Known worst-case reference scales for reverse bars (0→worst).
const REVERSE_BAR_MAX = {
fagr_minus: 1.0,
crit_viol_pct: 0.25,
be_type: 0.5,
};
// Expected upper bound for higher-is-better bar normalization.
const FORWARD_BAR_MAX = {
se_plus: 1.0,
agr_plus: 1.0,
cse_plus: 1.0,
mean_utility: null, // computed dynamically from row range
};
/* --------------------------- Utilities --------------------------- */
const $ = (id) => document.getElementById(id);
const ce = (tag, attrs, children) => {
const el = document.createElement(tag);
if (attrs) {
for (const [k, v] of Object.entries(attrs)) {
if (k === "class") el.className = v;
else if (k === "text") el.textContent = v;
else if (k.startsWith("on") && typeof v === "function") {
el.addEventListener(k.slice(2).toLowerCase(), v);
} else el.setAttribute(k, v);
}
}
if (children) {
for (const c of children) {
if (c == null) continue;
if (typeof c === "string") el.appendChild(document.createTextNode(c));
else el.appendChild(c);
}
}
return el;
};
const fmtNum = (x, digits) => {
if (x == null || Number.isNaN(x)) return null;
return Number(x).toFixed(digits ?? 3);
};
const metricCellDigits = {
se_plus: 3,
agr_plus: 3,
cse_plus: 3,
fagr_minus: 3,
be_type: 3,
crit_viol_pct: 3,
mean_utility: 2,
stance_acc: 3,
conditional_utility: 2,
safe_term_minus: 3,
n_episodes: 0,
};
/* --------------------------- Masthead meta --------------------------- */
// Friendly version label shown to readers; the raw build run id from
// build_data.py (data.run) is kept in the data file for provenance but
// not surfaced to end users, since the artifact slug isn't meaningful.
$("meta-run").textContent = "TERMS-Bench-v1 (Bilateral Negotiation)";
$("meta-date").textContent = formatDate(data.generatedAt);
$("meta-agents").textContent = `${data.rows.length}`;
const fr = $("footer-run");
if (fr) fr.textContent = "TERMS-Bench";
function formatDate(iso) {
if (!iso) return "—";
const d = new Date(iso);
if (Number.isNaN(d.getTime())) return iso;
return d.toISOString().slice(0, 10);
}
/* ============================================================
SECTION A — Leaderboard (regime pills, sortable, paginated)
============================================================ */
const boardState = {
regime: "overall",
sortKey: "se_plus",
sortDir: "desc",
pageSize: data.rows.length,
page: 1,
};
function initRegimePills() {
const host = $("regime-pills");
host.innerHTML = "";
for (const id of data.regimes) {
const pill = ce("button", {
class: "pill" + (id === boardState.regime ? " active" : ""),
type: "button",
"data-id": id,
text: data.regimeLabels[id] || id,
onclick: () => {
boardState.regime = id;
boardState.page = 1;
renderRegimePills();
renderBoard();
termsUrlScheduleSync();
},
});
host.appendChild(pill);
}
}
function renderRegimePills() {
for (const pill of $("regime-pills").querySelectorAll(".pill")) {
pill.classList.toggle("active", pill.dataset.id === boardState.regime);
}
}
function initSortHeaders() {
const ths = document.querySelectorAll("#leaderboard thead th.sortable");
ths.forEach((th) => {
th.addEventListener("click", () => {
const key = th.dataset.key;
if (boardState.sortKey === key) {
boardState.sortDir = boardState.sortDir === "desc" ? "asc" : "desc";
} else {
boardState.sortKey = key;
boardState.sortDir = LOWER_IS_BETTER.has(key) ? "asc" : "desc";
}
renderBoard();
});
});
}
function compareRows(a, b, key, dir) {
const va = (a.regimes[boardState.regime] || {})[key];
const vb = (b.regimes[boardState.regime] || {})[key];
const aIsNum = va != null && !Number.isNaN(va);
const bIsNum = vb != null && !Number.isNaN(vb);
if (!aIsNum && !bIsNum) return 0;
if (!aIsNum) return 1; // always sink empty cells
if (!bIsNum) return -1;
return dir === "asc" ? va - vb : vb - va;
}
function renderBoard() {
const rows = [...data.rows].sort((a, b) =>
compareRows(a, b, boardState.sortKey, boardState.sortDir)
);
// header sort state
document.querySelectorAll("#leaderboard thead th.sortable").forEach((th) => {
th.classList.remove("sort-asc", "sort-desc");
if (th.dataset.key === boardState.sortKey) {
th.classList.add(boardState.sortDir === "asc" ? "sort-asc" : "sort-desc");
}
});
const body = $("leaderboard-body");
body.innerHTML = "";
const meanUtilMax = Math.max(
...data.rows.map((r) => Math.abs((r.regimes[boardState.regime] || {}).mean_utility || 0)),
1
);
const start = (boardState.page - 1) * boardState.pageSize;
const end = start + boardState.pageSize;
const pageRows = rows.slice(start, end);
pageRows.forEach((row, idx) => {
const slice = row.regimes[boardState.regime] || {};
const tr = ce("tr");
tr.appendChild(ce("td", { class: "col-rank", text: String(start + idx + 1) }));
tr.appendChild(
ce("td", { class: "col-agent" }, [makeAgentCell(row, { showKind: true })])
);
tr.appendChild(ce("td", { class: "col-provider", text: row.provider || "—" }));
tr.appendChild(makeBarCell(slice.se_plus, "se_plus"));
tr.appendChild(makeBarCell(slice.agr_plus, "agr_plus"));
tr.appendChild(makeBarCell(slice.cse_plus, "cse_plus"));
tr.appendChild(makeBarCell(slice.fagr_minus, "fagr_minus"));
tr.appendChild(makeBarCell(slice.be_type, "be_type"));
tr.appendChild(makeBarCell(slice.crit_viol_pct, "crit_viol_pct"));
tr.appendChild(
makeBarCell(slice.mean_utility, "mean_utility", { max: meanUtilMax })
);
body.appendChild(tr);
});
renderPagination(rows.length);
}
function makeBarCell(value, metric, opts) {
const td = ce("td", { class: "num" });
if (value == null || Number.isNaN(value)) {
td.appendChild(ce("span", { class: "na-cell", text: "—" }));
return td;
}
const digits = metricCellDigits[metric] ?? 3;
const displayNum = fmtNum(value, digits);
const reverse = LOWER_IS_BETTER.has(metric);
const maxVal = reverse
? REVERSE_BAR_MAX[metric] ?? 1
: opts?.max ?? FORWARD_BAR_MAX[metric] ?? 1;
const pct = Math.max(0, Math.min(1, Math.abs(value) / (maxVal || 1))) * 100;
td.appendChild(
ce("div", { class: "bar-cell" }, [
ce("span", { class: "bar-num", text: displayNum }),
ce("div", { class: "bar-track" }, [
ce("div", {
class: reverse ? "bar-fill reverse" : "bar-fill",
style: `width:${pct.toFixed(1)}%`,
}),
]),
])
);
return td;
}
function renderPagination(total) {
const row = $("pagination-row");
row.innerHTML = "";
if (total <= boardState.pageSize) return;
const totalPages = Math.ceil(total / boardState.pageSize);
const prev = ce("button", {
text: "Prev",
disabled: boardState.page === 1 ? "disabled" : null,
onclick: () => {
if (boardState.page > 1) {
boardState.page -= 1;
renderBoard();
}
},
});
const next = ce("button", {
text: "Next",
disabled: boardState.page === totalPages ? "disabled" : null,
onclick: () => {
if (boardState.page < totalPages) {
boardState.page += 1;
renderBoard();
}
},
});
const count = ce("span", {
class: "count",
text: `Page ${boardState.page} / ${totalPages} · ${total} agents`,
});
row.appendChild(count);
row.appendChild(prev);
row.appendChild(next);
}
/* ============================================================
SECTION B/C — Headline line charts
============================================================ */
const chartStates = {
family: { kind: "all", hidden: new Set() },
difficulty: { kind: "all", hidden: new Set() },
};
function initKindPills(hostId, stateKey, rerender) {
const host = $(hostId);
host.innerHTML = "";
for (const { id, label } of KIND_FILTERS) {
const pill = ce("button", {
class: "pill" + (chartStates[stateKey].kind === id ? " active" : ""),
type: "button",
"data-id": id,
text: label,
onclick: () => {
chartStates[stateKey].kind = id;
chartStates[stateKey].hidden = new Set();
for (const p of host.querySelectorAll(".pill")) {
p.classList.toggle("active", p.dataset.id === id);
}
rerender();
termsUrlScheduleSync();
},
});
host.appendChild(pill);
}
}
function eligibleRows(stateKey, sliceKey, axisIds) {
const st = chartStates[stateKey];
const kind = st.kind;
const rows = data.rows.filter((r) => {
if (kind !== "all" && r.kind !== kind) return false;
const slices = r[sliceKey] || {};
// Row must have at least one se_plus value on the axis
return axisIds.some((id) => {
const s = slices[id] || {};
return s.se_plus != null && !Number.isNaN(s.se_plus);
});
});
return rows;
}
function renderChart({
containerId,
footnoteId,
axisIds,
axisLabels,
sliceKey,
stateKey,
xAxisLabel,
yAxisLabel = "SE⁺",
}) {
const container = $(containerId);
container.innerHTML = "";
const rows = eligibleRows(stateKey, sliceKey, axisIds);
const footnote = $(footnoteId);
if (!rows.length || !axisIds.length) {
container.appendChild(
ce("div", {
class: "chart-empty",
text:
"No agents with this slice are available in the current run. " +
"Run a full sweep with the latest schema to populate this panel.",
})
);
if (footnote) footnote.textContent = "";
return;
}
// Determine color per agent (stable by insertion order in data.rows).
const colorIndex = new Map();
let ci = 0;
for (const r of data.rows) {
if (rows.includes(r)) {
colorIndex.set(r.id, SERIES_COLORS[ci % SERIES_COLORS.length]);
ci += 1;
}
}
// SVG layout
const width = 920;
const height = 380;
const margin = { top: 18, right: 24, bottom: 52, left: 54 };
const plotW = width - margin.left - margin.right;
const plotH = height - margin.top - margin.bottom;
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute("viewBox", `0 0 ${width} ${height}`);
svg.setAttribute("role", "img");
svg.setAttribute("aria-label", `${yAxisLabel} vs ${xAxisLabel}`);
// Scales: x is categorical → discrete positions
const n = axisIds.length;
const xAt = (i) => margin.left + (n === 1 ? plotW / 2 : (i * plotW) / (n - 1));
// y-axis: always 0..1 for SE+
const yMax = 1.0;
const yAt = (v) => margin.top + plotH - (v / yMax) * plotH;
// Gridlines + y-axis labels (0, 0.25, 0.5, 0.75, 1)
const yTicks = [0, 0.25, 0.5, 0.75, 1.0];
for (const t of yTicks) {
const y = yAt(t);
const line = document.createElementNS("http://www.w3.org/2000/svg", "line");
line.setAttribute("x1", margin.left);
line.setAttribute("x2", margin.left + plotW);
line.setAttribute("y1", y);
line.setAttribute("y2", y);
line.setAttribute("class", "chart-grid-line");
svg.appendChild(line);
const lbl = document.createElementNS("http://www.w3.org/2000/svg", "text");
lbl.setAttribute("x", margin.left - 8);
lbl.setAttribute("y", y + 3.5);
lbl.setAttribute("text-anchor", "end");
lbl.setAttribute("class", "chart-tick-label");
lbl.textContent = t.toFixed(2);
svg.appendChild(lbl);
}
// x-axis line
const xAxis = document.createElementNS("http://www.w3.org/2000/svg", "line");
xAxis.setAttribute("x1", margin.left);
xAxis.setAttribute("x2", margin.left + plotW);
xAxis.setAttribute("y1", margin.top + plotH);
xAxis.setAttribute("y2", margin.top + plotH);
xAxis.setAttribute("class", "chart-axis-line");
svg.appendChild(xAxis);
// x-tick labels
axisIds.forEach((id, i) => {
const lbl = document.createElementNS("http://www.w3.org/2000/svg", "text");
lbl.setAttribute("x", xAt(i));
lbl.setAttribute("y", margin.top + plotH + 20);
lbl.setAttribute("text-anchor", "middle");
lbl.setAttribute("class", "chart-tick-label");
lbl.textContent = axisLabels[id] || id;
svg.appendChild(lbl);
});
// axis titles
const xTitle = document.createElementNS("http://www.w3.org/2000/svg", "text");
xTitle.setAttribute("x", margin.left + plotW / 2);
xTitle.setAttribute("y", height - 6);
xTitle.setAttribute("text-anchor", "middle");
xTitle.setAttribute("class", "chart-axis-label");
xTitle.textContent = xAxisLabel;
svg.appendChild(xTitle);
const yTitle = document.createElementNS("http://www.w3.org/2000/svg", "text");
const yTitleX = 16;
const yTitleY = margin.top + plotH / 2;
yTitle.setAttribute("x", yTitleX);
yTitle.setAttribute("y", yTitleY);
yTitle.setAttribute("text-anchor", "middle");
yTitle.setAttribute("transform", `rotate(-90 ${yTitleX} ${yTitleY})`);
yTitle.setAttribute("class", "chart-axis-label");
yTitle.textContent = yAxisLabel;
svg.appendChild(yTitle);
// Series — polylines + dots
const hidden = chartStates[stateKey].hidden;
for (const row of rows) {
const colorToken = colorIndex.get(row.id);
const color = `var(${colorToken})`;
const slices = row[sliceKey] || {};
const points = [];
axisIds.forEach((id, i) => {
const s = slices[id] || {};
const v = s.se_plus;
if (v != null && !Number.isNaN(v)) {
points.push([xAt(i), yAt(v), v]);
}
});
if (!points.length) continue;
const isDim = hidden.has(row.id);
const polyline = document.createElementNS("http://www.w3.org/2000/svg", "polyline");
polyline.setAttribute("points", points.map((p) => `${p[0]},${p[1]}`).join(" "));
polyline.setAttribute("class", "chart-series-line" + (isDim ? " dim" : ""));
polyline.setAttribute("stroke", color);
svg.appendChild(polyline);
points.forEach(([x, y]) => {
const c = document.createElementNS("http://www.w3.org/2000/svg", "circle");
c.setAttribute("cx", x);
c.setAttribute("cy", y);
c.setAttribute("r", 3.5);
c.setAttribute("fill", color);
c.setAttribute("stroke", "var(--bg)");
c.setAttribute("class", "chart-series-dot" + (isDim ? " dim" : ""));
svg.appendChild(c);
});
}
container.appendChild(svg);
// Legend
const legend = ce("div", { class: "chart-legend" });
for (const row of rows) {
const colorToken = colorIndex.get(row.id);
const isDim = hidden.has(row.id);
const item = ce("span", {
class: "chart-legend-item" + (isDim ? " dim" : ""),
onclick: () => {
if (hidden.has(row.id)) hidden.delete(row.id);
else hidden.add(row.id);
// Re-render to update line dimming
if (stateKey === "family") renderFamilyChart();
else renderDifficultyChart();
},
});
item.appendChild(
ce("span", {
class: "chart-legend-swatch",
style: `background: var(${colorToken})`,
})
);
item.appendChild(ce("span", { text: row.display }));
legend.appendChild(item);
}
container.appendChild(legend);
if (footnote) {
const omitted = data.rows.length - rows.length;
const kindLabel = chartStates[stateKey].kind === "all"
? "all kinds"
: KIND_FILTERS.find((k) => k.id === chartStates[stateKey].kind)?.label.toLowerCase();
footnote.textContent =
`Showing ${rows.length} of ${data.rows.length} agents (${kindLabel}).` +
(omitted > 0 ? ` ${omitted} agents omitted — either filtered by kind or lacking this slice in the source run.` : "");
}
}
/**
* Persistent state for the family radar — pinned + hovered focus, plus a
* one-shot entry-animation flag so we don't re-animate on every legend
* toggle. Mirrors `bankrollChartState` in spirit.
*/
const familyChartState = {
pinnedAgent: null,
pinnedAxis: null,
hoveredAgent: null,
hoveredAxis: null,
hasAnimated: false,
lastDataKey: null,
};
/**
* Render the "Surplus efficiency by counterpart family" panel as a
* single radar / spider chart: one filled-and-stroked polygon per agent
* across all six counterpart-family axes. The shape of the polygon *is*
* the agent's profile — broadly inflated polygons are robust generalists,
* while sharply asymmetric ones reveal which families an agent leans on.
*
* The chart is fully interactive in the same spirit as the bankroll chart:
* - hovering a polygon spotlights that agent and shows a tooltip with
* all six SE⁺ values (mini-bars) for full-profile read-out;
* - hovering any "family wedge" (the angular slice around a spoke)
* highlights that axis and shows a tooltip with the family's SE⁺
* ranking across all eligible agents;
* - clicking a polygon or wedge pins the focus so the cursor can leave
* the chart; clicking empty radar space unpins;
* - on first reveal each polygon inflates from the center, staggered.
*/
function renderFamilyChart() {
const containerId = "chart-family";
const footnoteId = "chart-family-footnote";
const stateKey = "family";
const sliceKey = "families";
const axisIds = data.families || [];
const container = $(containerId);
container.innerHTML = "";
const footnote = $(footnoteId);
const rows = eligibleRows(stateKey, sliceKey, axisIds);
if (!rows.length || !axisIds.length) {
container.appendChild(
ce("div", {
class: "chart-empty",
text:
"No agents with this slice are available in the current run. " +
"Run a full sweep with the latest schema to populate this panel.",
})
);
if (footnote) footnote.textContent = "";
return;
}
// Stable per-agent series color, ordered by data.rows insertion order
// so a given agent gets the same hue here, in the legend, and in the
// leaderboard table further down the page.
const colorIndex = new Map();
let ci = 0;
for (const r of data.rows) {
if (rows.includes(r)) {
colorIndex.set(r.id, SERIES_COLORS[ci % SERIES_COLORS.length]);
ci += 1;
}
}
const hidden = chartStates[stateKey].hidden;
const labels = data.familyLabels || {};
// Re-animate on a meaningful data change (kind filter changed the set of
// rows). Legend toggles keep the same dataKey so we don't re-animate.
const dataKey =
`${chartStates[stateKey].kind}|${rows.map((r) => r.id).join(",")}`;
if (familyChartState.lastDataKey !== dataKey) {
familyChartState.hasAnimated = false;
familyChartState.pinnedAgent = null;
familyChartState.pinnedAxis = null;
familyChartState.hoveredAgent = null;
familyChartState.hoveredAxis = null;
familyChartState.lastDataKey = dataKey;
}
const radarBlock = ce("div", { class: "family-radar-block" });
const figure = ce("div", { class: "family-radar-figure" });
const SVG_NS = "http://www.w3.org/2000/svg";
const w = 560;
const h = 520;
const cx = w / 2;
const cy = h / 2;
const R = 180;
const N = axisIds.length;
const svg = document.createElementNS(SVG_NS, "svg");
svg.setAttribute("class", "family-radar");
svg.setAttribute("viewBox", `0 0 ${w} ${h}`);
svg.setAttribute("role", "img");
svg.setAttribute(
"aria-label",
"SE⁺ profile across counterpart families, one polygon per agent"
);
const ang = (i) => -Math.PI / 2 + (i * 2 * Math.PI) / N;
const pt = (i, frac) => [
cx + Math.cos(ang(i)) * R * frac,
cy + Math.sin(ang(i)) * R * frac,
];
// ---------- Layer 1: hexagonal grid + ring scale labels ----------
for (const t of [0.25, 0.5, 0.75, 1.0]) {
const points = [];
for (let i = 0; i < N; i++) {
const [x, y] = pt(i, t);
points.push(`${x.toFixed(1)},${y.toFixed(1)}`);
}
const poly = document.createElementNS(SVG_NS, "polygon");
poly.setAttribute("points", points.join(" "));
poly.setAttribute("class", "family-radar-grid");
svg.appendChild(poly);
}
// Scale labels along the topmost spoke so readers can calibrate the rings.
for (const t of [0.25, 0.5, 0.75, 1.0]) {
const [x, y] = pt(0, t);
const lbl = document.createElementNS(SVG_NS, "text");
lbl.setAttribute("x", x + 5);
lbl.setAttribute("y", y + 3);
lbl.setAttribute("class", "family-radar-grid-label");
lbl.textContent = t.toFixed(2);
svg.appendChild(lbl);
}
// ---------- Layer 2: invisible per-axis hover wedges ----------
// Each wedge is a triangle from the center bisecting the angle to its
// neighbors, extended slightly past the axis-label radius so labels are
// also inside the wedge. Wedges sit *under* agent groups so agent hover
// wins where they overlap.
const wedges = [];
for (let i = 0; i < N; i++) {
const a1 = -Math.PI / 2 + ((i - 0.5) * 2 * Math.PI) / N;
const a2 = -Math.PI / 2 + ((i + 0.5) * 2 * Math.PI) / N;
const Rext = R * 1.32;
const x1 = cx + Math.cos(a1) * Rext;
const y1 = cy + Math.sin(a1) * Rext;
const x2 = cx + Math.cos(a2) * Rext;
const y2 = cy + Math.sin(a2) * Rext;
const path = document.createElementNS(SVG_NS, "path");
path.setAttribute(
"d",
`M${cx},${cy} L${x1.toFixed(1)},${y1.toFixed(1)} L${x2.toFixed(1)},${y2.toFixed(1)} Z`
);
path.setAttribute("class", "family-radar-wedge");
path.setAttribute("data-axis-id", axisIds[i]);
svg.appendChild(path);
wedges.push(path);
}
// ---------- Layer 3: spokes ----------
const spokes = [];
for (let i = 0; i < N; i++) {
const [x, y] = pt(i, 1);
const line = document.createElementNS(SVG_NS, "line");
line.setAttribute("x1", cx);
line.setAttribute("y1", cy);
line.setAttribute("x2", x);
line.setAttribute("y2", y);
line.setAttribute("class", "family-radar-spoke");
line.setAttribute("data-axis-id", axisIds[i]);
svg.appendChild(line);
spokes.push(line);
}
// ---------- Layer 4: agent groups (polygons + per-axis dots) ----------
const agentGroups = new Map();
for (const row of rows) {
const colorToken = colorIndex.get(row.id);
const isLegendDim = hidden.has(row.id);
const slices = row[sliceKey] || {};
const polyPoints = [];
for (let i = 0; i < N; i++) {
const v = (slices[axisIds[i]] || {}).se_plus;
const frac =
v != null && !Number.isNaN(v) ? Math.max(0, Math.min(1, v)) : 0;
const [x, y] = pt(i, frac);
polyPoints.push(`${x.toFixed(1)},${y.toFixed(1)}`);
}
const g = document.createElementNS(SVG_NS, "g");
g.setAttribute(
"class",
"family-radar-agent" + (isLegendDim ? " dim" : "")
);
g.setAttribute("data-id", row.id);
// Inflate-from-center transform; CSS handles the transition.
g.style.transformOrigin = `${cx}px ${cy}px`;
const poly = document.createElementNS(SVG_NS, "polygon");
poly.setAttribute("points", polyPoints.join(" "));
poly.setAttribute("stroke", `var(${colorToken})`);
poly.setAttribute("fill", `var(${colorToken})`);
poly.setAttribute("class", "family-radar-poly");
g.appendChild(poly);
const dotByAxis = new Map();
for (let i = 0; i < N; i++) {
const v = (slices[axisIds[i]] || {}).se_plus;
if (v == null || Number.isNaN(v)) continue;
const [x, y] = pt(i, Math.max(0, Math.min(1, v)));
const c = document.createElementNS(SVG_NS, "circle");
c.setAttribute("cx", x);
c.setAttribute("cy", y);
c.setAttribute("r", "4");
c.setAttribute("fill", `var(${colorToken})`);
c.setAttribute("class", "family-radar-dot");
c.setAttribute("data-axis-id", axisIds[i]);
g.appendChild(c);
dotByAxis.set(axisIds[i], c);
}
const titleEl = document.createElementNS(SVG_NS, "title");
titleEl.textContent = row.display || row.id;
g.appendChild(titleEl);
svg.appendChild(g);
agentGroups.set(row.id, { g, poly, dotByAxis, colorToken, row });
}
// ---------- Layer 5: axis labels (drawn last so they're never clipped) ----------
const axisLabelEls = [];
for (let i = 0; i < N; i++) {
const [x, y] = pt(i, 1.18);
const txt = document.createElementNS(SVG_NS, "text");
txt.setAttribute("x", x);
txt.setAttribute("y", y);
txt.setAttribute("text-anchor", "middle");
txt.setAttribute("dominant-baseline", "middle");
txt.setAttribute("class", "family-radar-axis-label");
txt.setAttribute("data-axis-id", axisIds[i]);
txt.textContent = labels[axisIds[i]] || axisIds[i];
svg.appendChild(txt);
axisLabelEls.push(txt);
}
figure.appendChild(svg);
// Floating HTML tooltip. Positioned over the cursor in agent/axis mode,
// anchored next to the active spoke when an axis is *pinned* (so the
// cursor can leave entirely).
const tooltip = ce("div", { class: "family-radar-tooltip" });
tooltip.style.display = "none";
figure.appendChild(tooltip);
// Pin indicator chip — itself the release affordance. Clicking it clears
// both pin types and dispatches an applyFocus() update.
const pinChip = ce("span", {
class: "family-radar-pin-chip",
role: "button",
"aria-label": "Release pinned focus",
title: "Release pinned focus",
});
pinChip.textContent = "Pinned";
pinChip.style.display = "none";
// When the chip captures a click, also clear hover state — otherwise the
// wedge sitting underneath the chip never sees pointerleave (the chip
// blocks it), so its `hoveredAxis` would persist and re-show the
// ranking tooltip immediately after release.
pinChip.addEventListener("click", (e) => {
e.stopPropagation();
familyChartState.pinnedAgent = null;
familyChartState.pinnedAxis = null;
familyChartState.hoveredAgent = null;
familyChartState.hoveredAxis = null;
applyFocus();
});
pinChip.addEventListener("pointerenter", () => {
familyChartState.hoveredAgent = null;
familyChartState.hoveredAxis = null;
applyFocus();
});
figure.appendChild(pinChip);
radarBlock.appendChild(figure);
radarBlock.appendChild(
ce("p", {
class: "family-radar-hint",
text:
"Hover a polygon for that agent's full profile; hover near a spoke for the family's ranking. Click to pin.",
})
);
container.appendChild(radarBlock);
// ---------- Legend (same toggle behavior as the other charts) ----------
// Each item: [color swatch] [provider logo] [model name].
// The swatch ties the legend entry to its polygon hue; the logo
// disambiguates between multiple models from the same provider
// (e.g. GPT-4o mini vs o3-pro) which would otherwise read as
// identical-looking name fragments at small sizes.
const legend = ce("div", { class: "chart-legend" });
for (const row of rows) {
const colorToken = colorIndex.get(row.id);
const isDim = hidden.has(row.id);
const item = ce("span", {
class: "chart-legend-item" + (isDim ? " dim" : ""),
onclick: () => {
if (hidden.has(row.id)) hidden.delete(row.id);
else hidden.add(row.id);
renderFamilyChart();
},
});
item.appendChild(
ce("span", {
class: "chart-legend-swatch",
style: `background: var(${colorToken})`,
})
);
item.appendChild(makeAgentLogoMark(row));
item.appendChild(ce("span", { text: row.display || row.id }));
legend.appendChild(item);
}
container.appendChild(legend);
if (footnote) {
const omitted = data.rows.length - rows.length;
const kindLabel = chartStates[stateKey].kind === "all"
? "all kinds"
: KIND_FILTERS.find((k) => k.id === chartStates[stateKey].kind)?.label.toLowerCase();
footnote.textContent =
`Showing ${rows.length} of ${data.rows.length} agents (${kindLabel}).` +
(omitted > 0
? ` ${omitted} agents omitted — either filtered by kind or lacking this slice in the source run.`
: "");
}
// ====================================================================
// Interactivity wiring.
// Effective focus = pinnedAgent || hoveredAgent || pinnedAxis || hoveredAxis.
// ====================================================================
function effectiveFocus() {
if (familyChartState.pinnedAgent)
return { mode: "agent", id: familyChartState.pinnedAgent, pinned: true };
if (familyChartState.hoveredAgent)
return { mode: "agent", id: familyChartState.hoveredAgent, pinned: false };
if (familyChartState.pinnedAxis)
return { mode: "axis", id: familyChartState.pinnedAxis, pinned: true };
if (familyChartState.hoveredAxis)
return { mode: "axis", id: familyChartState.hoveredAxis, pinned: false };
return { mode: "none" };
}
function rankingForAxis(axisId) {
const list = [];
for (const r of rows) {
const v = ((r[sliceKey] || {})[axisId] || {}).se_plus;
if (v != null && !Number.isNaN(v)) list.push({ row: r, v });
}
list.sort((a, b) => b.v - a.v);
return list;
}
function fillAgentTooltip(agentId) {
tooltip.classList.remove("axis-mode");
tooltip.classList.add("agent-mode");
tooltip.innerHTML = "";
const ag = agentGroups.get(agentId);
if (!ag) return;
const { row, colorToken } = ag;
const slices = row[sliceKey] || {};
const head = ce("div", { class: "family-radar-tooltip-head" });
head.appendChild(
ce("span", {
class: "family-radar-tooltip-swatch",
style: `background: var(${colorToken})`,
})
);
head.appendChild(
ce("span", {
class: "family-radar-tooltip-title",
text: row.display || row.id,
})
);
const activeAxis =
familyChartState.pinnedAxis || familyChartState.hoveredAxis;
tooltip.appendChild(head);
const grid = ce("div", { class: "family-radar-tooltip-grid" });
for (let i = 0; i < N; i++) {
const axisId = axisIds[i];
const v = (slices[axisId] || {}).se_plus;
const frac = v != null && !Number.isNaN(v) ? Math.max(0, Math.min(1, v)) : 0;
const lblEl = ce("span", {
class:
"family-radar-tooltip-axis" +
(axisId === activeAxis ? " active" : ""),
text: labels[axisId] || axisId,
});
const bar = ce("span", { class: "family-radar-tooltip-bar" });
const fill = ce("span", { class: "family-radar-tooltip-bar-fill" });
fill.style.width = (frac * 100).toFixed(1) + "%";
fill.style.background = `var(${colorToken})`;
bar.appendChild(fill);
const valEl = ce("span", {
class: "family-radar-tooltip-val",
text: v != null && !Number.isNaN(v) ? v.toFixed(2) : "—",
});
grid.appendChild(lblEl);
grid.appendChild(bar);
grid.appendChild(valEl);
}
tooltip.appendChild(grid);
}
function fillAxisTooltip(axisId) {
tooltip.classList.remove("agent-mode");
tooltip.classList.add("axis-mode");
tooltip.innerHTML = "";
const head = ce("div", { class: "family-radar-tooltip-head" });
head.appendChild(
ce("span", {
class: "family-radar-tooltip-title",
text: labels[axisId] || axisId,
})
);
head.appendChild(
ce("span", {
class: "family-radar-tooltip-sub",
text: "SE⁺ ranking",
})
);
tooltip.appendChild(head);
const ranked = rankingForAxis(axisId);
const list = ce("ol", { class: "family-radar-tooltip-list" });
let rk = 1;
for (const { row, v } of ranked) {
const colorToken = colorIndex.get(row.id);
const li = ce("li", { class: "family-radar-tooltip-rank-row" });
li.appendChild(
ce("span", { class: "family-radar-tooltip-rank", text: `${rk}.` })
);
li.appendChild(
ce("span", {
class: "family-radar-tooltip-swatch",
style: `background: var(${colorToken})`,
})
);
li.appendChild(
ce("span", {
class: "family-radar-tooltip-name",
text: row.display || row.id,
})
);
li.appendChild(
ce("span", { class: "family-radar-tooltip-val", text: v.toFixed(2) })
);
list.appendChild(li);
rk += 1;
}
if (!ranked.length) {
list.appendChild(
ce("li", {
class: "family-radar-tooltip-empty",
text: "no agents with data on this family",
})
);
}
tooltip.appendChild(list);
}
function positionTooltipAtCursor(clientX, clientY) {
if (clientX == null || clientY == null) {
// Pinned-but-no-mouse fallback: pin the tooltip to the radar corner
// so it's still visible after the cursor leaves the figure.
tooltip.style.left = "12px";
tooltip.style.top = "12px";
return;
}