perf-sentinel-core 0.5.2

Core library for perf-sentinel: polyglot performance anti-pattern detector
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
<!DOCTYPE html>
<html lang="en" data-theme="">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data:; base-uri 'none'; form-action 'none'" />
<title>{{PAGE_TITLE}}</title>
<style>
  :root[data-theme="dark"] {
    --color-background-primary: #1a1a1a;
    --color-background-secondary: #242424;
    --color-background-tertiary: #2e2e2e;
    --color-background-info: #18324d;
    --color-background-danger: #3d1f1f;
    --color-background-warning: #3d2f1f;
    --color-background-success: #1f3d2f;
    --color-text-primary: #e8e8e8;
    --color-text-secondary: #a0a0a0;
    --color-text-tertiary: #707070;
    --color-text-info: #6babff;
    --color-text-danger: #ff7a7a;
    --color-text-warning: #f0b05f;
    --color-text-success: #5fd495;
    --color-border-tertiary: rgba(255,255,255,0.1);
    --color-border-secondary: rgba(255,255,255,0.2);
    --color-border-info: #378add;
    --color-border-success: #3d7d5c;
    --page-bg: #121212;
  }
  :root[data-theme="light"] {
    --color-background-primary: #ffffff;
    --color-background-secondary: #f5f5f5;
    --color-background-tertiary: #ececec;
    --color-background-info: #e6f1fb;
    --color-background-danger: #fcebeb;
    --color-background-warning: #faeeda;
    --color-background-success: #eaf3de;
    --color-text-primary: #1a1a1a;
    --color-text-secondary: #555555;
    --color-text-tertiary: #888888;
    --color-text-info: #0c447c;
    --color-text-danger: #791f1f;
    --color-text-warning: #633806;
    --color-text-success: #27500a;
    --color-border-tertiary: rgba(0,0,0,0.1);
    --color-border-secondary: rgba(0,0,0,0.2);
    --color-border-info: #378add;
    --color-border-success: #7ab85a;
    --page-bg: #fafafa;
  }
  :root {
    --font-sans: -apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif;
    --font-mono: 'JetBrains Mono', 'SF Mono', Consolas, Monaco, monospace;
    --border-radius-md: 8px;
    --border-radius-lg: 12px;
  }
  * { box-sizing: border-box; }
  body { margin: 0; padding: 24px; background: var(--page-bg); color: var(--color-text-primary); font-family: var(--font-sans); font-size: 13px; line-height: 1.5; }
  .ps-container { max-width: 1100px; margin: 0 auto; }
  .ps-header-ctrl { display: flex; justify-content: flex-end; align-items: center; margin-bottom: 10px; font-size: 11px; color: var(--color-text-tertiary); }
  .ps-theme-toggle { background: transparent; border: 0.5px solid var(--color-border-tertiary); color: var(--color-text-secondary); padding: 4px 10px; border-radius: var(--border-radius-md); cursor: pointer; font-size: 11px; font-family: inherit; }
  .ps-theme-toggle:hover { border-color: var(--color-border-secondary); }
  .ps-topbar { display: flex; align-items: center; gap: 12px; padding: 10px 14px; border: 0.5px solid var(--color-border-tertiary); border-radius: var(--border-radius-md); background: var(--color-background-secondary); margin-bottom: 12px; flex-wrap: wrap; }
  .ps-brand { font-weight: 500; font-size: 14px; }
  .ps-meta { color: var(--color-text-secondary); font-size: 12px; font-family: var(--font-mono); }
  .ps-gate-pass { margin-left: auto; background: var(--color-background-success); color: var(--color-text-success); padding: 3px 10px; border-radius: var(--border-radius-md); font-size: 11px; font-weight: 500; }
  .ps-gate-fail { margin-left: auto; background: var(--color-background-danger); color: var(--color-text-danger); padding: 3px 10px; border-radius: var(--border-radius-md); font-size: 11px; font-weight: 500; }
  .ps-tabs { display: flex; gap: 2px; border-bottom: 0.5px solid var(--color-border-tertiary); margin-bottom: 14px; }
  .ps-tab { padding: 8px 14px; font-size: 13px; cursor: pointer; border: none; background: transparent; color: var(--color-text-secondary); border-bottom: 2px solid transparent; margin-bottom: -0.5px; font-family: inherit; }
  .ps-tab:hover { color: var(--color-text-primary); }
  .ps-tab.active { color: var(--color-text-primary); border-bottom-color: var(--color-text-primary); font-weight: 500; }
  .ps-tab .ps-badge { display: inline-block; margin-left: 6px; padding: 1px 7px; border-radius: 10px; font-size: 10px; background: var(--color-background-tertiary); color: var(--color-text-secondary); }
  .ps-metrics { display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px; margin-bottom: 14px; }
  .ps-metrics-3 { grid-template-columns: repeat(3, 1fr); }
  .ps-metric { background: var(--color-background-secondary); border-radius: var(--border-radius-md); padding: 10px 12px; }
  .ps-metric-label { font-size: 11px; color: var(--color-text-secondary); margin-bottom: 4px; }
  .ps-metric-value { font-size: 20px; font-weight: 500; font-family: var(--font-mono); word-break: break-word; }
  .ps-metric-value-sm { font-size: 14px; line-height: 1.4; }
  .ps-metric-sub { font-size: 11px; color: var(--color-text-tertiary); font-family: var(--font-mono); }
  .ps-filters { display: flex; gap: 6px; margin-bottom: 10px; flex-wrap: wrap; align-items: center; }
  .ps-chip-group { display: contents; }
  .ps-chip { padding: 4px 10px; font-size: 11px; border-radius: 12px; border: 0.5px solid var(--color-border-tertiary); background: transparent; cursor: pointer; color: var(--color-text-secondary); font-family: inherit; }
  .ps-chip:hover { background: var(--color-background-secondary); }
  .ps-chip.active { background: var(--color-text-primary); color: var(--color-background-primary); border-color: var(--color-text-primary); }
  .ps-list { display: flex; flex-direction: column; gap: 6px; }
  .ps-row { display: grid; grid-template-columns: 60px 1fr auto; align-items: center; gap: 10px; padding: 10px 12px; border: 0.5px solid var(--color-border-tertiary); border-radius: var(--border-radius-md); cursor: pointer; background: var(--color-background-primary); }
  .ps-row:hover { background: var(--color-background-secondary); border-color: var(--color-border-secondary); }
  .ps-row.selected { border: 2px solid var(--color-border-info); padding: 9px 11px; }
  .ps-sev-crit { background: var(--color-background-danger); color: var(--color-text-danger); font-size: 10px; font-weight: 500; padding: 3px 8px; border-radius: var(--border-radius-md); text-align: center; }
  .ps-sev-warn { background: var(--color-background-warning); color: var(--color-text-warning); font-size: 10px; font-weight: 500; padding: 3px 8px; border-radius: var(--border-radius-md); text-align: center; }
  .ps-sev-info { background: var(--color-background-info); color: var(--color-text-info); font-size: 10px; font-weight: 500; padding: 3px 8px; border-radius: var(--border-radius-md); text-align: center; }
  .ps-fin-main { min-width: 0; }
  .ps-fin-type { font-weight: 500; font-size: 13px; margin-bottom: 2px; }
  .ps-fin-service { color: var(--color-text-tertiary); font-weight: 400; font-size: 11px; }
  .ps-fin-detail { font-size: 11px; color: var(--color-text-secondary); font-family: var(--font-mono); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
  .ps-fin-right { font-size: 11px; color: var(--color-text-secondary); font-family: var(--font-mono); text-align: right; white-space: nowrap; }
  .ps-fin-right-sub { color: var(--color-text-tertiary); }
  .ps-tree-header { font-size: 11px; color: var(--color-text-secondary); margin-bottom: 8px; font-family: var(--font-mono); word-break: break-all; }
  .ps-tree { font-family: var(--font-mono); font-size: 12px; padding: 10px 12px; background: var(--color-background-secondary); border-radius: var(--border-radius-md); line-height: 1.9; }
  .ps-span { display: grid; grid-template-columns: 1fr auto; gap: 10px; padding: 2px 4px; border-radius: 4px; }
  .ps-span.dim { color: var(--color-text-tertiary); }
  .ps-span.hilite { background: var(--color-background-danger); }
  .ps-span-text { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
  .ps-span-dur { color: var(--color-text-tertiary); white-space: nowrap; }
  .ps-span-find { color: var(--color-text-danger); font-weight: 500; }
  .ps-drill { background: var(--color-background-info); border: 0.5px solid var(--color-border-info); border-radius: var(--border-radius-md); padding: 10px 12px; margin-top: 10px; font-size: 12px; color: var(--color-text-info); }
  .ps-drill-label { font-size: 10px; color: var(--color-text-info); margin-bottom: 4px; opacity: 0.8; }
  .ps-drill-link { color: var(--color-text-info); }
  .ps-banner { background: var(--color-background-info); border: 0.5px solid var(--color-border-info); border-radius: var(--border-radius-md); padding: 8px 12px; margin-bottom: 10px; font-size: 11px; color: var(--color-text-info); }
  .ps-empty { padding: 30px; text-align: center; color: var(--color-text-secondary); font-size: 13px; background: var(--color-background-secondary); border-radius: var(--border-radius-md); }
  .ps-table { width: 100%; font-size: 11px; font-family: var(--font-mono); border-collapse: collapse; }
  .ps-table th { text-align: left; font-weight: 500; padding: 6px 8px; border-bottom: 0.5px solid var(--color-border-tertiary); color: var(--color-text-secondary); font-size: 10px; font-family: var(--font-sans); }
  .ps-table td { padding: 6px 8px; border-bottom: 0.5px solid var(--color-border-tertiary); vertical-align: top; }
  /* Highlight row on Explain -> pg_stat cross-nav. Scoped to the
     pg_stat table so other .ps-table instances (diff, green regions)
     stay unaffected if they ever adopt a .hilite class for another
     purpose. */
  #pgstat-body tr.hilite { background: var(--color-background-danger); }
  #pgstat-body tr.hilite td:first-child { color: var(--color-text-danger); font-weight: 500; }
  .ps-footer { margin-top: 14px; font-size: 11px; color: var(--color-text-tertiary); text-align: center; }
  .ps-credit { margin-top: 8px; font-size: 11px; color: var(--color-text-tertiary); text-align: center; }
  .ps-credit a { color: var(--color-text-secondary); text-decoration: underline; }
  .ps-credit a:hover { color: var(--color-text-primary); }
  .ps-kbd { font-family: var(--font-mono); font-size: 10px; background: var(--color-background-tertiary); padding: 1px 5px; border-radius: 3px; color: var(--color-text-secondary); }
  .ps-search { display: none; width: 100%; padding: 6px 10px; margin-bottom: 10px; font-size: 12px; font-family: var(--font-sans); background: var(--color-background-secondary); border: 0.5px solid var(--color-border-tertiary); border-radius: var(--border-radius-md); color: var(--color-text-primary); }
  .ps-search:focus { outline: none; border-color: var(--color-border-info); }
  .ps-span.ps-span-pgstat-link { cursor: pointer; }
  .ps-span.ps-span-pgstat-link:hover .ps-span-text { text-decoration: underline; }
  .ps-drill-clear { color: var(--color-text-info); text-decoration: underline; cursor: pointer; margin-left: 8px; }
  .ps-diff-section { margin-bottom: 18px; }
  .ps-diff-section-header { font-size: 12px; font-weight: 500; margin-bottom: 8px; color: var(--color-text-primary); }
  .ps-diff-section-header.red { color: var(--color-text-danger); }
  .ps-diff-section-header.green { color: var(--color-text-success); }
  .ps-panel-toolbar { display: flex; justify-content: flex-end; margin-bottom: 8px; }
  .ps-export-btn { padding: 4px 10px; font-size: 11px; border-radius: var(--border-radius-md); border: 0.5px solid var(--color-border-info); background: transparent; cursor: pointer; color: var(--color-text-info); font-family: inherit; }
  .ps-export-btn:hover { background: var(--color-background-info); }
  .ps-copy-link-btn { padding: 4px 10px; font-size: 11px; border-radius: var(--border-radius-md); border: 0.5px solid var(--color-border-info); background: transparent; cursor: pointer; color: var(--color-text-info); font-family: inherit; margin-left: 6px; }
  .ps-copy-link-btn:hover { background: var(--color-background-info); }
  .ps-correlation-clickable { cursor: pointer; }
  .ps-correlation-clickable:hover { background: var(--color-background-tertiary); }
  .ps-show-more { margin-top: 10px; padding: 6px 12px; font-size: 11px; border-radius: var(--border-radius-md); border: 0.5px solid var(--color-border-tertiary); background: transparent; color: var(--color-text-secondary); cursor: pointer; font-family: inherit; width: 100%; }
  .ps-show-more:hover { background: var(--color-background-secondary); border-color: var(--color-border-secondary); }
  dialog.ps-modal { position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); max-width: 520px; width: calc(100% - 40px); background: var(--color-background-secondary); color: var(--color-text-primary); border-radius: var(--border-radius-lg); border: 0.5px solid var(--color-border-tertiary); padding: 18px 22px; box-shadow: 0 8px 32px rgba(0,0,0,0.4); }
  dialog.ps-modal::backdrop { background: rgba(0,0,0,0.6); }
  dialog.ps-modal h2 { margin: 0 0 12px 0; font-size: 14px; font-weight: 500; }
  .ps-modal-close { position: absolute; top: 8px; right: 10px; background: transparent; border: none; color: var(--color-text-secondary); font-family: inherit; font-size: 16px; cursor: pointer; line-height: 1; padding: 4px 8px; }
  .ps-modal-close:hover { color: var(--color-text-primary); }
  dialog.ps-modal table { width: 100%; border-collapse: collapse; }
  dialog.ps-modal th { text-align: left; padding: 4px 6px; font-size: 10px; font-weight: 500; color: var(--color-text-secondary); border-bottom: 0.5px solid var(--color-border-tertiary); font-family: var(--font-sans); }
  dialog.ps-modal th:first-child { width: 90px; }
  dialog.ps-modal td { padding: 5px 6px; font-size: 12px; vertical-align: top; }
  dialog.ps-modal td:first-child { width: 90px; white-space: nowrap; }
</style>
</head>
<body>
<div class="ps-container">
  <div class="ps-header-ctrl">
    <button class="ps-theme-toggle" id="theme-toggle" type="button">Toggle theme</button>
  </div>

  <div class="ps-topbar" id="topbar"></div>

  <div class="ps-tabs" id="tabs" role="tablist" aria-label="Dashboard sections"></div>

  <div id="panel-findings" role="tabpanel" aria-labelledby="tab-findings">
    <div class="ps-banner" id="trim-banner" style="display: none;"></div>
    <input type="search" class="ps-search" id="findings-search" placeholder="Filter findings by type, service, endpoint or template..." aria-label="Filter findings" />
    <div class="ps-metrics" id="findings-metrics"></div>
    <div class="ps-filters" id="findings-filters"></div>
    <div class="ps-panel-toolbar">
      <button type="button" class="ps-export-btn" id="findings-export" data-export-tab="findings">Export CSV</button>
      <button type="button" class="ps-copy-link-btn" id="findings-copy-link" data-copy-link-tab="findings">Copy link</button>
    </div>
    <div class="ps-list" id="findings-list"></div>
    <button type="button" class="ps-show-more" id="findings-show-more" style="display: none;"></button>
    <div class="ps-empty" id="findings-empty" style="display: none;">No findings in this trace set.</div>
  </div>

  <div id="panel-explain" role="tabpanel" aria-labelledby="tab-explain" style="display: none;">
    <div class="ps-empty" id="explain-empty">Click a finding to view its trace tree here.</div>
    <div id="explain-content" style="display: none;">
      <div class="ps-tree-header" id="explain-breadcrumb"></div>
      <div class="ps-tree" id="explain-tree"></div>
      <div class="ps-drill" id="explain-fix" style="display: none;"></div>
    </div>
    <div class="ps-empty" id="explain-not-embedded" style="display: none;"></div>
  </div>

  <div id="panel-pgstat" role="tabpanel" aria-labelledby="tab-pgstat" style="display: none;">
    <div class="ps-drill" id="pgstat-drill" style="display: none;">
      <div class="ps-drill-label">Filtered from Explain</div>
      <span id="pgstat-drill-text"></span>
      <span class="ps-drill-clear" id="pgstat-drill-clear">clear</span>
    </div>
    <div class="ps-filters" id="pgstat-rankings"></div>
    <input type="search" class="ps-search" id="pgstat-search" placeholder="Filter by SQL template..." aria-label="Filter pg_stat rows" />
    <div class="ps-panel-toolbar">
      <button type="button" class="ps-export-btn" id="pgstat-export" data-export-tab="pgstat">Export CSV</button>
      <button type="button" class="ps-copy-link-btn" id="pgstat-copy-link" data-copy-link-tab="pgstat">Copy link</button>
    </div>
    <table class="ps-table" id="pgstat-table">
      <thead><tr><th>Template</th><th style="width: 80px;">Calls</th><th style="width: 100px;">Total ms</th><th style="width: 90px;">Mean ms</th></tr></thead>
      <tbody id="pgstat-body"></tbody>
    </table>
    <div class="ps-empty" id="pgstat-empty" style="display: none;">No pg_stat entries.</div>
  </div>

  <div id="panel-diff" role="tabpanel" aria-labelledby="tab-diff" style="display: none;">
    <input type="search" class="ps-search" id="diff-search" placeholder="Filter diff findings by type, service, endpoint or template..." aria-label="Filter diff findings" />
    <div class="ps-panel-toolbar">
      <button type="button" class="ps-export-btn" id="diff-export" data-export-tab="diff">Export CSV</button>
      <button type="button" class="ps-copy-link-btn" id="diff-copy-link" data-copy-link-tab="diff">Copy link</button>
    </div>
    <div class="ps-diff-section">
      <div class="ps-diff-section-header red" id="diff-new-header">New findings (0)</div>
      <div class="ps-list" id="diff-new-list"></div>
    </div>
    <div class="ps-diff-section">
      <div class="ps-diff-section-header green" id="diff-resolved-header">Resolved findings (0)</div>
      <div class="ps-list" id="diff-resolved-list"></div>
    </div>
    <div class="ps-diff-section">
      <div class="ps-diff-section-header" id="diff-sev-header">Severity changes (0)</div>
      <table class="ps-table" id="diff-sev-table" style="display: none;">
        <thead><tr><th>Type</th><th>Service</th><th>Endpoint</th><th>Before</th><th>After</th></tr></thead>
        <tbody id="diff-sev-body"></tbody>
      </table>
    </div>
    <div class="ps-diff-section">
      <div class="ps-diff-section-header" id="diff-endp-header">Endpoint metric deltas (0)</div>
      <table class="ps-table" id="diff-endp-table" style="display: none;">
        <thead><tr><th>Service</th><th>Endpoint</th><th>Before I/O</th><th>After I/O</th><th>Delta</th></tr></thead>
        <tbody id="diff-endp-body"></tbody>
      </table>
    </div>
  </div>

  <div id="panel-correlations" role="tabpanel" aria-labelledby="tab-correlations" style="display: none;">
    <input type="search" class="ps-search" id="correlations-search" placeholder="Filter correlations by service or type..." aria-label="Filter correlations" />
    <div class="ps-panel-toolbar">
      <button type="button" class="ps-export-btn" id="correlations-export" data-export-tab="correlations">Export CSV</button>
      <button type="button" class="ps-copy-link-btn" id="correlations-copy-link" data-copy-link-tab="correlations">Copy link</button>
    </div>
    <div class="ps-list" id="correlations-list"></div>
  </div>

  <div id="panel-green" role="tabpanel" aria-labelledby="tab-green" style="display: none;">
    <div class="ps-metrics ps-metrics-3" id="green-metrics"></div>
    <div class="ps-tree-header" id="green-regions-header" style="margin-top: 14px;"></div>
    <table class="ps-table" id="green-regions-table" style="display: none;">
      <thead><tr><th>Region</th><th>Intensity (gCO2/kWh)</th><th>I/O ops</th><th>CO2</th><th>Source</th></tr></thead>
      <tbody id="green-regions-body"></tbody>
    </table>
    <div class="ps-empty" id="green-regions-empty" style="display: none;">No region breakdown available.</div>
  </div>

  <div class="ps-footer">
    <span class="ps-kbd">j</span>/<span class="ps-kbd">k</span> navigate . <span class="ps-kbd">enter</span> open . <span class="ps-kbd">/</span> search . <span class="ps-kbd">esc</span> back . <span class="ps-kbd">?</span> shortcuts
  </div>
  <div class="ps-credit">
    Powered by <a href="https://github.com/robintra/perf-sentinel" target="_blank" rel="noopener noreferrer">perf-sentinel</a>
  </div>
</div>

<dialog id="cheatsheet" class="ps-modal" aria-labelledby="cheatsheet-title">
  <button type="button" class="ps-modal-close" id="cheatsheet-close" aria-label="Close">x</button>
  <h2 id="cheatsheet-title">Keyboard shortcuts</h2>
  <table id="cheatsheet-table">
    <thead><tr><th scope="col">Key</th><th scope="col">Action</th></tr></thead>
    <tbody id="cheatsheet-body"></tbody>
  </table>
</dialog>

<script id="report-data" type="application/json">
{{REPORT_JSON}}
</script>

<script>
(function () {
  "use strict";

  // -------- persistence (sessionStorage, scoped to this browser tab) --------
  // sessionStorage throws in Safari private mode and some enterprise
  // policies. Every access is wrapped so a failure degrades gracefully
  // to in-memory defaults rather than surfacing a runtime error.
  var STORAGE_KEYS = {
    theme: "perf-sentinel:theme",
    pgstatRanking: "perf-sentinel:pgstat-ranking"
  };
  function sessionGet(key) {
    try {
      return globalThis.sessionStorage.getItem(key);
    } catch {
      // Safari private mode or a locked-down enterprise policy:
      // fall back to the in-memory default rather than surfacing
      // a runtime error to the user.
      return null;
    }
  }
  function sessionSet(key, value) {
    try {
      globalThis.sessionStorage.setItem(key, value);
    } catch {
      // See sessionGet: silent fallback is the intended posture.
      return;
    }
  }
  // -------- theme (tri-state: auto | dark | light) --------
  // "auto" follows prefers-color-scheme live. Legacy "dark"/"light"
  // sessions keep their forced modes. Applied before DOM render so
  // the body background does not flash.
  var THEME_MODES = ["auto", "dark", "light"];
  var prefersDarkMQ = null;
  try {
    prefersDarkMQ = globalThis.matchMedia
      ? globalThis.matchMedia("(prefers-color-scheme: dark)")
      : null;
  } catch {
    prefersDarkMQ = null;
  }
  function currentThemeMode() {
    var stored = sessionGet(STORAGE_KEYS.theme);
    return THEME_MODES.includes(stored) ? stored : "auto";
  }
  function resolveThemeColor(mode) {
    if (mode === "dark" || mode === "light") return mode;
    return prefersDarkMQ && prefersDarkMQ.matches ? "dark" : "light";
  }
  function applyTheme(mode) {
    document.documentElement.dataset.theme = resolveThemeColor(mode);
    var btn = document.getElementById("theme-toggle");
    if (btn) btn.textContent = "Theme: " + mode;
  }
  applyTheme(currentThemeMode());
  if (prefersDarkMQ && typeof prefersDarkMQ.addEventListener === "function") {
    try {
      prefersDarkMQ.addEventListener("change", function () {
        if (currentThemeMode() === "auto") applyTheme("auto");
      });
    } catch {
      // Older browsers expose addListener instead, not worth wiring.
    }
  }

  // -------- load payload --------
  function loadPayload() {
    var raw = document.getElementById("report-data").textContent || "";
    try {
      return JSON.parse(raw);
    } catch (e) {
      document.body.textContent = "Failed to parse embedded report data: " + e.message;
      return null;
    }
  }
  function indexTracesById(list) {
    // Null-prototype map so a hostile trace_id like "__proto__" or
    // "toString" cannot corrupt the lookup by reparenting Object's
    // prototype chain. Not currently exploitable to code execution
    // (downstream consumption is textContent-only), but the fix is
    // a one-liner and removes the family of defects.
    var map = Object.create(null);
    list.forEach(function (trace) { map[trace.trace_id] = trace; });
    return map;
  }

  var payload = loadPayload();
  if (!payload) return;

  var report = payload.report || {};
  var findings = report.findings || [];
  var greenSummary = report.green_summary || null;
  var hasGreen = !!(greenSummary && greenSummary.co2);
  var embeddedTraces = payload.embedded_traces || [];
  var tracesById = indexTracesById(embeddedTraces);

  // -------- small DOM helpers (textContent only) --------
  function el(tag, cls, text) {
    var n = document.createElement(tag);
    if (cls) n.className = cls;
    if (text !== undefined && text !== null) n.textContent = String(text);
    return n;
  }
  function setAttr(node, name, value) { node.setAttribute(name, String(value)); }
  function safeHttpsHref(url) {
    if (typeof url !== "string") return null;
    if (!url.startsWith("https://")) return null;
    return url;
  }
  /// Reusable metric card builder. Hoisted to the outer scope so it is
  /// not re-created on every render of `renderFindingsMetrics` and
  /// `renderGreenPanel` (Sonar S7721).
  function metricCard(label, value, sub, smallValue) {
    var wrap = el("div", "ps-metric");
    wrap.appendChild(el("div", "ps-metric-label", label));
    var v = el("div", "ps-metric-value", value);
    if (smallValue) v.classList.add("ps-metric-value-sm");
    wrap.appendChild(v);
    wrap.appendChild(el("div", "ps-metric-sub", sub));
    return wrap;
  }

  // -------- formatters --------
  function formatGco2(grams) {
    if (!Number.isFinite(grams)) return "-";
    var abs = Math.abs(grams);
    if (abs >= 1) return grams.toFixed(3) + " g";
    if (abs >= 0.001) return (grams * 1000).toFixed(3) + " mg";
    if (abs >= 0.000001) return (grams * 1000000).toFixed(3) + " ug";
    if (abs === 0) return "0 g";
    return grams.toExponential(2) + " g";
  }
  function formatDurationUs(us) {
    if (!Number.isFinite(us)) return "-";
    var ms = us / 1000;
    if (ms < 1) return ms.toFixed(2) + " ms";
    if (ms < 10) return ms.toFixed(2) + " ms";
    return Math.round(ms) + " ms";
  }
  function truncate(s, max) {
    if (typeof s !== "string") return "";
    if (s.length <= max) return s;
    return s.slice(0, max - 1) + "...";
  }
  function percent(num, denom) {
    if (!denom) return "0%";
    return Math.round((num * 100) / denom) + "%";
  }

  // severity + finding-type display maps
  var SEV_CLASS = { critical: "ps-sev-crit", warning: "ps-sev-warn", info: "ps-sev-info" };
  var SEV_LABEL = { critical: "CRIT", warning: "WARN", info: "INFO" };
  var TYPE_LABEL = {
    n_plus_one_sql: "N+1 SQL",
    n_plus_one_http: "N+1 HTTP",
    redundant_sql: "Redundant SQL",
    redundant_http: "Redundant HTTP",
    slow_sql: "Slow SQL",
    slow_http: "Slow HTTP",
    excessive_fanout: "Excessive fanout",
    chatty_service: "Chatty service",
    pool_saturation: "Pool saturation",
    serialized_calls: "Serialized calls"
  };
  function typeLabel(t) { return TYPE_LABEL[t] || String(t); }

  // -------- top bar --------
  function renderTopbar() {
    var bar = document.getElementById("topbar");
    var brand = el("span", "ps-brand", "perf-sentinel");
    var version = el("span", "ps-meta", "v" + (payload.version || ""));
    var analysis = report.analysis || { events_processed: 0, traces_analyzed: 0 };
    var meta = el(
      "span",
      "ps-meta",
      (payload.input_label || "-") +
        " . " + analysis.traces_analyzed + " traces" +
        " . " + analysis.events_processed + " spans"
    );
    var gate = report.quality_gate || { passed: true };
    var badge = el(
      "span",
      gate.passed ? "ps-gate-pass" : "ps-gate-fail",
      gate.passed ? "Quality gate passed" : "Quality gate failed"
    );
    bar.appendChild(brand);
    bar.appendChild(version);
    bar.appendChild(meta);
    bar.appendChild(badge);
  }

  // -------- tabs (generic) --------
  var tabs = [];
  // Used by g-prefixed shortcuts and deep-link hash application to bail
  // out silently when a tab is not present in the current report.
  var registeredTabs = Object.create(null);
  function registerTab(key, label, countFn) {
    tabs.push({ key: key, label: label, countFn: countFn });
    registeredTabs[key] = true;
  }
  function tabIsRegistered(key) { return !!registeredTabs[key]; }
  function renderTabs() {
    var bar = document.getElementById("tabs");
    tabs.forEach(function (t) {
      var btn = el("button", "ps-tab", t.label);
      btn.type = "button";
      // ARIA tab pattern: each button is a `role="tab"` that controls
      // its tabpanel. tabindex rotates between 0 (active) and -1
      // (inactive) so keyboard users traverse the tablist exactly once
      // when tabbing through the page, then use arrow keys inside.
      setAttr(btn, "role", "tab");
      setAttr(btn, "data-tab", t.key);
      setAttr(btn, "id", "tab-" + t.key);
      setAttr(btn, "aria-controls", "panel-" + t.key);
      setAttr(btn, "aria-selected", "false");
      setAttr(btn, "tabindex", "-1");
      if (t.countFn) {
        var c = t.countFn();
        if (c !== null && c !== undefined) {
          var badge = el("span", "ps-badge", String(c));
          btn.appendChild(document.createTextNode(" "));
          btn.appendChild(badge);
        }
      }
      btn.addEventListener("click", function () { switchTab(t.key); });
      bar.appendChild(btn);
    });
    wireTablistKeyboardNav(bar);
    // default to first tab
    if (tabs.length > 0) switchTab(tabs[0].key);
  }

  function wireTablistKeyboardNav(bar) {
    // WAI-ARIA arrow-key pattern on the tablist. Coexists with the
    // g-prefixed shortcuts since they listen on different keys.
    bar.addEventListener("keydown", function (event) {
      var target = event.target;
      if (!target || target.getAttribute("role") !== "tab") return;
      var buttons = Array.prototype.slice.call(
        bar.querySelectorAll("button[role=\"tab\"]")
      );
      if (buttons.length === 0) return;
      var idx = buttons.indexOf(target);
      if (idx < 0) return;

      var next = -1;
      switch (event.key) {
        case "ArrowRight":
        case "ArrowDown":
          next = (idx + 1) % buttons.length;
          break;
        case "ArrowLeft":
        case "ArrowUp":
          next = (idx - 1 + buttons.length) % buttons.length;
          break;
        case "Home":
          next = 0;
          break;
        case "End":
          next = buttons.length - 1;
          break;
        case "Enter":
        case " ":
          event.preventDefault();
          switchTab(target.dataset.tab, true);
          return;
        default:
          return;
      }
      event.preventDefault();
      var targetBtn = buttons[next];
      if (targetBtn) {
        targetBtn.focus();
        switchTab(targetBtn.dataset.tab, true);
      }
    });
  }

  var currentTab = null;
  function switchTab(key, fromKeyboard) {
    // Clear open search filters so a stale one does not resurface
    // when the user comes back to a tab.
    if (typeof clearAllSearchFilters === "function") clearAllSearchFilters();
    currentTab = key;
    document.querySelectorAll(".ps-tab").forEach(function (btn) {
      var active = btn.dataset.tab === key;
      btn.classList.toggle("active", active);
      setAttr(btn, "aria-selected", active ? "true" : "false");
      setAttr(btn, "tabindex", active ? "0" : "-1");
    });
    tabs.forEach(function (t) {
      var panel = document.getElementById("panel-" + t.key);
      if (panel) panel.style.display = t.key === key ? "" : "none";
    });
    // Move focus only for keyboard activation. Clicks and hash
    // restoration must not steal focus.
    if (fromKeyboard) {
      var active = document.getElementById("tab-" + key);
      if (active && typeof active.focus === "function") {
        try { active.focus(); } catch { /* detached node */ }
      }
    }
    scheduleHashWrite();
  }

  // -------- findings metrics --------
  function countBySeverity() {
    var c = { critical: 0, warning: 0, info: 0 };
    findings.forEach(function (f) { if (c[f.severity] !== undefined) c[f.severity] += 1; });
    return c;
  }
  function renderFindingsMetrics() {
    var root = document.getElementById("findings-metrics");
    var sev = countBySeverity();
    var total = findings.length;

    root.appendChild(metricCard(
      "Findings",
      String(total),
      sev.critical + " crit . " + sev.warning + " warn . " + sev.info + " info"
    ));

    var avoidable = greenSummary ? (greenSummary.avoidable_io_ops || 0) : 0;
    var ratio = greenSummary ? Math.round((greenSummary.io_waste_ratio || 0) * 100) : 0;
    root.appendChild(metricCard(
      "Avoidable I/O",
      String(avoidable),
      ratio + "% waste ratio"
    ));

    if (hasGreen) {
      var co2 = greenSummary.co2;
      root.appendChild(metricCard(
        "CO2 estimate",
        formatGco2(co2.total.mid),
        String(co2.total.model || "")
      ));
    }

    var offender = greenSummary && greenSummary.top_offenders && greenSummary.top_offenders[0];
    if (offender) {
      root.appendChild(metricCard(
        "Top offender",
        truncate(offender.service, 24),
        "IIS " + (offender.io_intensity_score || 0).toFixed(1),
        true
      ));
    }
  }

  // -------- filters --------
  var filterState = { severity: null, service: null };
  function renderFilterChips() {
    var root = document.getElementById("findings-filters");
    root.textContent = "";

    // Severity chips (All / Critical / Warning) behave as a single
    // mutually-exclusive selector, so they go inside a radiogroup.
    // Service chips are independent toggles: each one is pressable and
    // can be cleared by re-clicking, but they don't form a group in
    // the ARIA sense.
    var severityGroup = el("span", "ps-chip-group", null);
    setAttr(severityGroup, "role", "radiogroup");
    setAttr(severityGroup, "aria-label", "Finding severity");
    root.appendChild(severityGroup);

    var serviceGroup = el("span", "ps-chip-group", null);
    setAttr(serviceGroup, "role", "group");
    setAttr(serviceGroup, "aria-label", "Finding service");
    root.appendChild(serviceGroup);

    function appendChip(parent, label, key, chipRole, stateAttr) {
      var btn = el("button", "ps-chip", label);
      btn.type = "button";
      setAttr(btn, "role", chipRole);
      setAttr(btn, "data-key", key);
      setAttr(btn, stateAttr, "false");
      btn.addEventListener("click", function () { onFilterClick(key); });
      parent.appendChild(btn);
    }

    appendChip(severityGroup, "All", "all", "radio", "aria-checked");
    var hasCrit = findings.some(function (f) { return f.severity === "critical"; });
    var hasWarn = findings.some(function (f) { return f.severity === "warning"; });
    if (hasCrit) appendChip(severityGroup, "Critical", "sev:critical", "radio", "aria-checked");
    if (hasWarn) appendChip(severityGroup, "Warning", "sev:warning", "radio", "aria-checked");

    var services = Object.create(null);
    findings.forEach(function (f) { services[f.service] = true; });
    Object.keys(services).sort().forEach(function (s) {
      appendChip(serviceGroup, s, "svc:" + s, "button", "aria-pressed");
    });

    syncFilterChips();
  }
  function onFilterClick(key) {
    if (key === "all") {
      filterState.severity = null;
      filterState.service = null;
    } else if (key.startsWith("sev:")) {
      var sv = key.slice(4);
      filterState.severity = filterState.severity === sv ? null : sv;
    } else if (key.startsWith("svc:")) {
      var svc = key.slice(4);
      filterState.service = filterState.service === svc ? null : svc;
    }
    syncFilterChips();
    resetShownCount();
    renderFindingsList();
    scheduleHashWrite();
  }
  function syncFilterChips() {
    var anyActive = !!(filterState.severity || filterState.service);
    document.querySelectorAll("#findings-filters .ps-chip").forEach(function (chip) {
      var key = chip.dataset.key;
      var active = false;
      if (key === "all") active = !anyActive;
      else if (key === "sev:" + filterState.severity) active = true;
      else if (key === "svc:" + filterState.service) active = true;
      chip.classList.toggle("active", active);
      // Severity chips and "All" are radio-role, service chips are
      // toggle buttons. Pick the right ARIA state attribute per chip.
      var role = chip.getAttribute("role");
      var stateAttr = role === "radio" ? "aria-checked" : "aria-pressed";
      setAttr(chip, stateAttr, active ? "true" : "false");
    });
  }

  // -------- findings list --------
  // Cap the initial render at LIST_CAP rows to keep the DOM small.
  // Additional rows are revealed LIST_CAP at a time via the
  // `findings-show-more` button, tracked by `shownCount`. Every filter,
  // search or hash apply resets `shownCount` to LIST_CAP so the user
  // never ends up paginated into rows that no longer match.
  var LIST_CAP = 500;
  var visibleFindings = [];
  var selectedIndex = -1;
  var shownCount = LIST_CAP;

  function applyFilters() {
    return findings.filter(function (f) {
      if (filterState.severity && f.severity !== filterState.severity) return false;
      if (filterState.service && f.service !== filterState.service) return false;
      return true;
    });
  }

  function renderFindingsList() {
    var root = document.getElementById("findings-list");
    var empty = document.getElementById("findings-empty");
    root.textContent = "";
    var filtered = applyFilters();
    visibleFindings = filtered.slice(0, shownCount);
    selectedIndex = visibleFindings.length > 0 ? 0 : -1;

    if (visibleFindings.length === 0) {
      empty.style.display = "";
      syncShowMore(filtered.length);
      return;
    }
    empty.style.display = "none";

    visibleFindings.forEach(function (f, idx) {
      root.appendChild(buildFindingRow(f, idx));
    });
    syncSelection();
    syncShowMore(filtered.length);
  }

  function syncShowMore(totalMatching) {
    var btn = document.getElementById("findings-show-more");
    if (!btn) return;
    if (visibleFindings.length >= totalMatching) {
      btn.style.display = "none";
      return;
    }
    var remaining = totalMatching - visibleFindings.length;
    var next = Math.min(LIST_CAP, remaining);
    btn.style.display = "";
    btn.textContent = "Show " + next + " more findings (" + remaining + " remaining)";
  }

  function resetShownCount() { shownCount = LIST_CAP; }

  function buildFindingRow(f, idx) {
    var row = el("div", "ps-row");
    setAttr(row, "data-idx", idx);

    var sev = el("div", SEV_CLASS[f.severity] || "ps-sev-info", SEV_LABEL[f.severity] || "INFO");
    row.appendChild(sev);

    var main = el("div", "ps-fin-main");
    var typeRow = el("div", "ps-fin-type");
    typeRow.appendChild(document.createTextNode(typeLabel(f.type || f.finding_type)));
    var svc = el("span", "ps-fin-service", " in " + (f.service || "-"));
    typeRow.appendChild(svc);
    main.appendChild(typeRow);

    var tpl = (f.pattern && f.pattern.template) || "";
    main.appendChild(el("div", "ps-fin-detail", tpl));
    row.appendChild(main);

    var right = el("div", "ps-fin-right");
    var occ = (f.pattern && f.pattern.occurrences) || 0;
    right.appendChild(document.createTextNode(occ + " occ"));
    right.appendChild(document.createElement("br"));
    right.appendChild(el("span", "ps-fin-right-sub", truncate(f.source_endpoint || "-", 48)));
    row.appendChild(right);

    row.addEventListener("click", function () {
      selectedIndex = idx;
      syncSelection();
      openExplain(f);
    });
    return row;
  }

  function syncSelection() {
    document.querySelectorAll("#findings-list .ps-row").forEach(function (row, idx) {
      row.classList.toggle("selected", idx === selectedIndex);
    });
  }

  // -------- explain tree --------
  // Shared empty state for cap-reached, resolved-diff, and
  // Correlations clickthroughs whose trace is not in embedded_traces.
  function renderExplainEmpty(message) {
    document.getElementById("explain-empty").style.display = "none";
    var content = document.getElementById("explain-content");
    var notEmbedded = document.getElementById("explain-not-embedded");
    content.style.display = "none";
    notEmbedded.style.display = "";
    notEmbedded.textContent = message;
    switchTab("explain");
  }

  function openExplain(f) {
    document.getElementById("explain-empty").style.display = "none";
    var content = document.getElementById("explain-content");
    var notEmbedded = document.getElementById("explain-not-embedded");
    notEmbedded.style.display = "none";
    notEmbedded.textContent = "";

    var trace = tracesById[f.trace_id];
    if (!trace) {
      // Happens when the finding's trace was dropped by the size cap.
      renderExplainEmpty(
        "Trace not embedded (cap reached). Rerun with --max-traces-embedded <higher> to include it."
      );
      return;
    }

    content.style.display = "";
    var breadcrumb = document.getElementById("explain-breadcrumb");
    var shortTraceId = (f.trace_id || "").slice(0, 12);
    breadcrumb.textContent =
      "trace_id = " + shortTraceId + " . " + (f.service || "-") + " . " + (f.source_endpoint || "-");

    var treeRoot = document.getElementById("explain-tree");
    treeRoot.textContent = "";
    renderTree(treeRoot, trace, f);

    var fix = document.getElementById("explain-fix");
    fix.textContent = "";
    if (f.suggested_fix) {
      fix.style.display = "";
      renderSuggestedFix(fix, f.suggested_fix);
    } else {
      fix.style.display = "none";
    }

    switchTab("explain");
  }

  /// Build the parent -> children adjacency for a span list plus the
  /// roots array. Extracted from `renderTree` to keep its cognitive
  /// complexity under Sonar's 15-point threshold.
  function buildSpanTree(spans) {
    // Null-prototype maps for all user-controlled keys (span_id,
    // parent_span_id) so hostile identifiers like "__proto__" cannot
    // corrupt the lookup chain. Mirrors the indexTracesById fix.
    var byId = Object.create(null);
    spans.forEach(function (s) { byId[s.span_id] = s; });
    var childrenByParent = Object.create(null);
    var roots = [];
    spans.forEach(function (s, idx) {
      var parent = s.parent_span_id;
      if (parent && byId[parent]) {
        if (!childrenByParent[parent]) childrenByParent[parent] = [];
        childrenByParent[parent].push(idx);
      } else {
        roots.push(idx);
      }
    });
    return { roots: roots, childrenByParent: childrenByParent };
  }

  /// Iterative DFS walker that appends one row per span. Depth is
  /// capped at 64 to cut cycles if any, the total row count is capped
  /// at 2000 to bound worst-case DOM size.
  function emitSpanTreeRows(root, spans, tree, targetTpl) {
    var stack = [];
    for (var r = tree.roots.length - 1; r >= 0; r--) {
      stack.push({ idx: tree.roots[r], depth: 0 });
    }
    var emitted = 0;
    var HARD_SPAN_CAP = 2000;
    var MAX_DEPTH = 64;
    while (stack.length > 0 && emitted < HARD_SPAN_CAP) {
      var frame = stack.pop();
      if (frame.depth > MAX_DEPTH) continue;
      var span = spans[frame.idx];
      root.appendChild(buildSpanRow(span, frame.depth, targetTpl));
      emitted += 1;
      var kids = tree.childrenByParent[span.span_id] || [];
      for (var k = kids.length - 1; k >= 0; k--) {
        stack.push({ idx: kids[k], depth: frame.depth + 1 });
      }
    }
  }

  function renderTree(root, trace, finding) {
    var spans = trace.spans || [];
    if (spans.length === 0) {
      root.appendChild(el("div", "ps-span dim", "(empty trace)"));
      return;
    }
    var tree = buildSpanTree(spans);
    var targetTpl = (finding.pattern && finding.pattern.template) || null;
    emitSpanTreeRows(root, spans, tree, targetTpl);
  }

  function buildSpanRow(span, depth, targetTpl) {
    var row = el("div", "ps-span");
    var isFinding = targetTpl && span.template === targetTpl;
    if (isFinding) row.classList.add("hilite");
    else row.classList.add("dim");
    row.style.paddingLeft = (depth * 20) + "px";

    // Cross-nav to pg_stat: a SQL span whose normalized template matches
    // a row in pg_stat becomes clickable. The click switches to the
    // pg_stat tab with the matching row highlighted and the filter
    // banner shown.
    var pgStatMatch =
      hasPgStat && span.event_type === "sql" && pgStatByTemplate[span.template]
        ? span.template
        : null;
    if (pgStatMatch) {
      row.classList.add("ps-span-pgstat-link");
      row.addEventListener("click", function () {
        switchTab("pgstat");
        showPgStatDrill(pgStatMatch);
      });
    }

    var text = el("span", "ps-span-text");
    if (isFinding) text.classList.add("ps-span-find");
    text.textContent = describeSpan(span);
    row.appendChild(text);

    row.appendChild(el("span", "ps-span-dur", formatDurationUs(span.duration_us)));
    return row;
  }

  function describeSpan(span) {
    if (span.event_type === "sql") {
      return span.template || span.target || span.operation || "(sql)";
    }
    if (span.event_type === "http_out") {
      var op = (span.operation || "GET").toUpperCase();
      return op + " " + (span.template || span.target || "");
    }
    return span.operation || span.target || "(span)";
  }

  function renderSuggestedFix(root, fix) {
    var label = el("div", "ps-drill-label", "Suggested fix . " + (fix.framework || "-"));
    root.appendChild(label);
    root.appendChild(document.createTextNode(fix.recommendation || ""));
    var href = safeHttpsHref(fix.reference_url);
    if (href) {
      root.appendChild(document.createTextNode(" "));
      var a = el("a", "ps-drill-link", "See documentation");
      setAttr(a, "href", href);
      setAttr(a, "target", "_blank");
      setAttr(a, "rel", "noopener noreferrer");
      root.appendChild(a);
    }
  }

  // -------- green panel --------
  function renderGreenPanel() {
    if (!hasGreen) return;
    var co2 = greenSummary.co2;

    var metrics = document.getElementById("green-metrics");
    metrics.appendChild(metricCard(
      "Operational CO2",
      formatGco2(co2.operational_gco2),
      "low " + formatGco2(co2.total.low) + " . high " + formatGco2(co2.total.high)
    ));
    metrics.appendChild(metricCard(
      "Embodied CO2",
      formatGco2(co2.embodied_gco2),
      "SCI v1.0 M term"
    ));
    var avoidMid = co2.avoidable.mid;
    var ratio = percent(avoidMid, co2.operational_gco2);
    metrics.appendChild(metricCard(
      "Avoidable",
      formatGco2(avoidMid),
      ratio + " of operational"
    ));

    var regions = greenSummary.regions || [];
    var header = document.getElementById("green-regions-header");
    header.textContent = "Regions (" + regions.length + ")";
    if (regions.length === 0) {
      document.getElementById("green-regions-empty").style.display = "";
      return;
    }
    document.getElementById("green-regions-table").style.display = "";
    var tbody = document.getElementById("green-regions-body");
    regions.forEach(function (r) {
      var tr = document.createElement("tr");
      tr.appendChild(el("td", null, r.region || "-"));
      tr.appendChild(el("td", null, (r.grid_intensity_gco2_kwh || 0).toFixed(0)));
      tr.appendChild(el("td", null, String(r.io_ops || 0)));
      tr.appendChild(el("td", null, formatGco2(r.co2_gco2 || 0)));
      tr.appendChild(el("td", null, r.intensity_source || "-"));
      tbody.appendChild(tr);
    });
  }

  // -------- pg_stat / diff / correlations state --------
  var pgStat = payload.pg_stat || null;
  // Cross-nav lookup indexed across every ranking's entries so the
  // Explain-to-pg_stat hotlink fires regardless of which ranking the
  // user switches to.
  var pgStatByTemplate = Object.create(null);
  if (pgStat && Array.isArray(pgStat.rankings)) {
    pgStat.rankings.forEach(function (r) {
      (r.entries || []).forEach(function (entry) {
        pgStatByTemplate[entry.normalized_template] = entry;
      });
    });
  }
  var hasPgStat = Object.keys(pgStatByTemplate).length > 0;

  var diffData = payload.diff || null;
  var hasDiff = !!diffData;

  // Correlations are populated only in daemon-produced reports. The batch
  // pipeline does not emit them. This branch lights up automatically
  // when a future daemon report is fed into
  // `perf-sentinel report --input <daemon.json>`.
  var correlations =
    report.correlations && report.correlations.length > 0 ? report.correlations : [];
  var hasCorrelations = correlations.length > 0;

  // -------- pg_stat panel --------
  // Rankings stay in the stable order `rank_pg_stat` emits:
  // [by_total_time, by_calls, by_mean_time, by_io_blocks]. The
  // sub-switcher chips are built from `pgStatRankings` so new rankings
  // appended server-side surface automatically without any JS change.
  var pgStatRankings =
    pgStat && Array.isArray(pgStat.rankings) ? pgStat.rankings : [];
  var activeRankingIndex = 0;
  // Template currently highlighted by the drill banner, if any. Used
  // to decide whether to re-apply the hilite after a ranking switch.
  var pgStatHiliteTemplate = null;

  // Human-friendly chip labels for the four known rankings. Unknown
  // labels fall through to the raw server-side string so an older or
  // customized PgStatReport still renders something sensible.
  var PGSTAT_LABELS = {
    "top by total_exec_time": "Total time",
    "top by calls": "Calls",
    "top by mean_exec_time": "Mean time",
    "top by shared_blks_total": "I/O blocks"
  };

  function activePgStatEntries() {
    if (pgStatRankings.length === 0) return [];
    var idx = Math.min(activeRankingIndex, pgStatRankings.length - 1);
    return pgStatRankings[idx].entries || [];
  }

  function renderPgStatPanel() {
    if (!hasPgStat) {
      document.getElementById("pgstat-empty").style.display = "";
      return;
    }
    renderPgStatRankings();
    renderPgStatTable();
  }

  function renderPgStatRankings() {
    var root = document.getElementById("pgstat-rankings");
    root.textContent = "";
    if (pgStatRankings.length <= 1) {
      // Hide the chip row when there is nothing to switch between.
      root.style.display = "none";
      return;
    }
    root.style.display = "";
    // Mutually-exclusive chip group. ARIA radiogroup pattern: the
    // container carries role="radiogroup", each chip is role="radio"
    // with aria-checked rewritten on every selection.
    setAttr(root, "role", "radiogroup");
    setAttr(root, "aria-label", "pg_stat ranking");
    pgStatRankings.forEach(function (r, idx) {
      var label = PGSTAT_LABELS[r.label] || r.label || ("Ranking " + (idx + 1));
      var btn = el("button", "ps-chip", label);
      btn.type = "button";
      setAttr(btn, "role", "radio");
      setAttr(btn, "data-ranking-index", String(idx));
      var isActive = idx === activeRankingIndex;
      setAttr(btn, "aria-checked", isActive ? "true" : "false");
      if (isActive) btn.classList.add("active");
      btn.addEventListener("click", function () {
        selectPgStatRanking(idx);
      });
      root.appendChild(btn);
    });
  }

  function selectPgStatRanking(idx) {
    // Persist the choice even when idx already matches activeRankingIndex.
    // This covers the deep-link restore path where the hash carries the
    // current ranking but sessionStorage was empty, so we still honor
    // the user's implicit intent to remember this ranking.
    sessionSet(STORAGE_KEYS.pgstatRanking, rankingSlugForIndex(idx));
    if (idx === activeRankingIndex) return;
    activeRankingIndex = idx;
    var chips = document.querySelectorAll("#pgstat-rankings .ps-chip");
    for (var i = 0; i < chips.length; i++) {
      var isActive = i === idx;
      chips[i].classList.toggle("active", isActive);
      setAttr(chips[i], "aria-checked", isActive ? "true" : "false");
    }
    renderPgStatTable();
    scheduleHashWrite();
    // Preserve the hilite when the previously-hilited template exists
    // in the new ranking; else silently clear the drill + hilite.
    if (pgStatHiliteTemplate) {
      var stillPresent = activePgStatEntries().some(function (entry) {
        return entry.normalized_template === pgStatHiliteTemplate;
      });
      if (stillPresent) {
        highlightPgStatRow(pgStatHiliteTemplate);
      } else {
        clearPgStatDrill();
      }
    }
    // Re-apply the search filter against the new rowset. Null-guard
    // covers the boot path where the filter init has not run yet.
    if (SEARCHABLE_TABS && SEARCHABLE_TABS.pgstat) {
      applySearchFilter(SEARCHABLE_TABS.pgstat);
    }
  }

  function renderPgStatTable() {
    var body = document.getElementById("pgstat-body");
    body.textContent = "";
    activePgStatEntries().forEach(function (entry) {
      var tr = document.createElement("tr");
      setAttr(tr, "data-template", entry.normalized_template);
      tr.appendChild(el("td", null, entry.normalized_template));
      tr.appendChild(el("td", null, String(entry.calls || 0)));
      tr.appendChild(el("td", null, (entry.total_exec_time_ms || 0).toFixed(1)));
      tr.appendChild(el("td", null, (entry.mean_exec_time_ms || 0).toFixed(2)));
      body.appendChild(tr);
    });
  }

  function showPgStatDrill(template) {
    var drill = document.getElementById("pgstat-drill");
    var txt = document.getElementById("pgstat-drill-text");
    drill.style.display = "";
    txt.textContent = template;
    pgStatHiliteTemplate = template;
    highlightPgStatRow(template);
  }
  function clearPgStatDrill() {
    document.getElementById("pgstat-drill").style.display = "none";
    pgStatHiliteTemplate = null;
    document.querySelectorAll("#pgstat-body tr").forEach(function (row) {
      row.classList.remove("hilite");
    });
  }
  function highlightPgStatRow(template) {
    var matched = null;
    document.querySelectorAll("#pgstat-body tr").forEach(function (row) {
      if (row.dataset.template === template) {
        row.classList.add("hilite");
        matched = row;
      } else {
        row.classList.remove("hilite");
      }
    });
    if (matched) matched.scrollIntoView({ block: "nearest" });
  }

  // -------- diff panel --------
  function renderDiffPanel() {
    if (!hasDiff) return;
    renderDiffFindingsList(
      "diff-new-list",
      "diff-new-header",
      "New findings",
      diffData.new_findings || [],
      true
    );
    renderDiffFindingsList(
      "diff-resolved-list",
      "diff-resolved-header",
      "Resolved findings",
      diffData.resolved_findings || [],
      "resolved"
    );
    renderDiffSevTable(diffData.severity_changes || []);
    renderDiffEndpTable(diffData.endpoint_metric_deltas || []);
  }
  function renderDiffFindingsList(listId, headerId, label, items, kind) {
    var list = document.getElementById(listId);
    var hdr = document.getElementById(headerId);
    hdr.textContent = label + " (" + items.length + ")";
    list.textContent = "";
    items.forEach(function (f) {
      list.appendChild(buildDiffFindingRow(f, kind));
    });
  }
  function buildDiffFindingRow(f, kind) {
    var row = el("div", "ps-row");
    row.appendChild(
      el("div", SEV_CLASS[f.severity] || "ps-sev-info", SEV_LABEL[f.severity] || "INFO")
    );
    var main = el("div", "ps-fin-main");
    var typeRow = el("div", "ps-fin-type");
    typeRow.appendChild(document.createTextNode(typeLabel(f.type || f.finding_type)));
    typeRow.appendChild(el("span", "ps-fin-service", " in " + (f.service || "-")));
    main.appendChild(typeRow);
    main.appendChild(el("div", "ps-fin-detail", (f.pattern && f.pattern.template) || ""));
    row.appendChild(main);
    var right = el("div", "ps-fin-right");
    right.appendChild(document.createTextNode(((f.pattern && f.pattern.occurrences) || 0) + " occ"));
    right.appendChild(document.createElement("br"));
    right.appendChild(el("span", "ps-fin-right-sub", truncate(f.source_endpoint || "-", 48)));
    row.appendChild(right);
    if (kind === "resolved") {
      // Resolved findings have no trace in the current run. Route the
      // click through the shared empty-state helper so the user ends
      // up on Explain with a clear explanation rather than on an
      // empty panel.
      row.addEventListener("click", function () {
        renderExplainEmpty(
          "This finding was resolved. Its trace lives in the baseline report, not in the current run. Open the baseline report separately to explore its traces."
        );
      });
    } else if (kind === true || kind === "new") {
      row.addEventListener("click", function () {
        openExplain(f);
      });
    } else {
      row.style.cursor = "default";
    }
    return row;
  }
  function renderDiffSevTable(items) {
    var hdr = document.getElementById("diff-sev-header");
    var tbl = document.getElementById("diff-sev-table");
    var body = document.getElementById("diff-sev-body");
    hdr.textContent = "Severity changes (" + items.length + ")";
    body.textContent = "";
    if (items.length === 0) {
      tbl.style.display = "none";
      return;
    }
    tbl.style.display = "";
    items.forEach(function (c) {
      var f = c.finding || {};
      var tr = document.createElement("tr");
      tr.appendChild(el("td", null, typeLabel(f.type || f.finding_type)));
      tr.appendChild(el("td", null, f.service || "-"));
      tr.appendChild(el("td", null, f.source_endpoint || "-"));
      tr.appendChild(el("td", null, SEV_LABEL[c.before_severity] || String(c.before_severity)));
      tr.appendChild(el("td", null, SEV_LABEL[c.after_severity] || String(c.after_severity)));
      body.appendChild(tr);
    });
  }
  function renderDiffEndpTable(items) {
    var hdr = document.getElementById("diff-endp-header");
    var tbl = document.getElementById("diff-endp-table");
    var body = document.getElementById("diff-endp-body");
    hdr.textContent = "Endpoint metric deltas (" + items.length + ")";
    body.textContent = "";
    if (items.length === 0) {
      tbl.style.display = "none";
      return;
    }
    tbl.style.display = "";
    items.forEach(function (d) {
      var tr = document.createElement("tr");
      tr.appendChild(el("td", null, d.service || "-"));
      tr.appendChild(el("td", null, d.endpoint || "-"));
      tr.appendChild(el("td", null, String(d.before_io_ops || 0)));
      tr.appendChild(el("td", null, String(d.after_io_ops || 0)));
      var delta = d.delta || 0;
      tr.appendChild(el("td", null, (delta > 0 ? "+" : "") + String(delta)));
      body.appendChild(tr);
    });
  }

  // -------- correlations panel --------
  // Renders `CrossTraceCorrelation` entries emitted by the daemon,
  // matching the Rust struct shape: `source` and `target` are
  // `CorrelationEndpoint { finding_type, service, template }`,
  // timing is `median_lag_ms` and `co_occurrence_count`.
  function renderCorrelationsPanel() {
    if (!hasCorrelations) return;
    var list = document.getElementById("correlations-list");
    list.textContent = "";
    correlations.forEach(function (c) {
      var src = c.source || {};
      var tgt = c.target || {};
      var row = el("div", "ps-row ps-correlation-row");
      var leftLabel =
        (src.service || "?") + ":" + typeLabel(src.finding_type || "?");
      var rightLabel =
        (tgt.service || "?") + ":" + typeLabel(tgt.finding_type || "?");
      var main = el("div", "ps-fin-main");
      main.appendChild(el("div", "ps-fin-type", leftLabel + " -> " + rightLabel));
      var conf = Math.round((c.confidence || 0) * 100);
      var lag = (c.median_lag_ms || 0).toFixed(0);
      main.appendChild(
        el(
          "div",
          "ps-fin-detail",
          "confidence " + conf + "% . median lag " + lag + " ms"
        )
      );
      row.appendChild(el("div", "ps-sev-info", "CORR"));
      row.appendChild(main);
      row.appendChild(
        el("div", "ps-fin-right", String(c.co_occurrence_count || 0) + "x")
      );
      // Daemon-produced correlations carry sample_trace_id. When set,
      // clicking jumps to Explain. openExplain falls back to the
      // shared empty state when the trace is not embedded.
      if (c.sample_trace_id) {
        row.classList.add("ps-correlation-clickable");
        row.addEventListener("click", function () {
          openExplain(syntheticFindingFromCorrelation(c));
        });
      } else {
        row.style.cursor = "default";
      }
      list.appendChild(row);
    });
  }

  function syntheticFindingFromCorrelation(c) {
    // Minimum shape openExplain reads: trace_id plus the fields used
    // by the breadcrumb.
    var tgt = c.target || {};
    return {
      trace_id: c.sample_trace_id,
      service: tgt.service || "-",
      source_endpoint: "-",
      pattern: { template: tgt.template || "" }
    };
  }

  // -------- search --------
  // Filter state is cleared on tab switch. The current panel's search
  // input stays empty and hidden on activation, so switching away and
  // back resets the filter implicitly. Simple, no cross-tab carryover.
  function matchRowByText(row, q) {
    return (row.textContent || "").toLowerCase().includes(q);
  }
  var SEARCHABLE_TABS = {
    findings: {
      inputId: "findings-search",
      rowsSelector: "#findings-list .ps-row"
    },
    pgstat: {
      inputId: "pgstat-search",
      rowsSelector: "#pgstat-body tr"
    },
    diff: {
      inputId: "diff-search",
      // Filter only the two findings lists; the severity_changes and
      // endpoint_metric_deltas tables stay unfiltered (short lists).
      rowsSelector: "#diff-new-list .ps-row, #diff-resolved-list .ps-row"
    },
    correlations: {
      inputId: "correlations-search",
      rowsSelector: "#correlations-list .ps-row"
    }
  };
  function initSearchInputs() {
    Object.keys(SEARCHABLE_TABS).forEach(function (tabKey) {
      var cfg = SEARCHABLE_TABS[tabKey];
      var input = document.getElementById(cfg.inputId);
      if (!input) return;
      input.addEventListener("input", function () {
        applySearchFilter(cfg);
        scheduleHashWrite();
      });
    });
  }
  function applySearchFilter(cfg) {
    var input = document.getElementById(cfg.inputId);
    var q = (input.value || "").toLowerCase();
    document.querySelectorAll(cfg.rowsSelector).forEach(function (row) {
      row.style.display = !q || matchRowByText(row, q) ? "" : "none";
    });
  }
  function openSearchForActiveTab() {
    var cfg = SEARCHABLE_TABS[currentTab];
    if (!cfg) return;
    var input = document.getElementById(cfg.inputId);
    if (!input) return;
    input.style.display = "block";
    input.focus();
    input.select();
  }
  function closeSearch(input) {
    input.value = "";
    applySearchFilter(SEARCHABLE_TABS[currentTab]);
    input.style.display = "none";
    input.blur();
  }
  function clearAllSearchFilters() {
    Object.keys(SEARCHABLE_TABS).forEach(function (tabKey) {
      var cfg = SEARCHABLE_TABS[tabKey];
      var input = document.getElementById(cfg.inputId);
      if (!input) return;
      if (input.value) {
        input.value = "";
        applySearchFilter(cfg);
      }
      input.style.display = "none";
    });
  }

  // -------- trim banner --------
  function renderTrimBanner() {
    var t = payload.trimmed_traces;
    if (!t) return;
    var b = document.getElementById("trim-banner");
    b.style.display = "";
    b.textContent = "Showing " + t.kept + " of " + t.total +
      " traces (trimmed for file size). Rerun with --max-traces-embedded <higher> to see more.";
  }

  // -------- theme toggle --------
  // Click cycles through auto -> dark -> light -> auto. The actual
  // data-theme attribute and button label are handled by applyTheme,
  // defined above alongside the initial boot-time resolution.
  document.getElementById("theme-toggle").addEventListener("click", function () {
    var idx = THEME_MODES.indexOf(currentThemeMode());
    var next = THEME_MODES[(idx + 1) % THEME_MODES.length];
    sessionSet(STORAGE_KEYS.theme, next);
    applyTheme(next);
  });

  // -------- CSV export --------
  // Rows are assembled as arrays of cell values, then each cell is
  // RFC 4180 escaped and the joined line is written to a Blob. No DOM
  // injection involved, so this bypasses the innerHTML hazard entirely.
  function csvEscape(value) {
    if (value === null || value === undefined) return "";
    var s = String(value);
    // Formula-injection guard (OWASP CSV Injection). Excel, LibreOffice
    // and Google Sheets all interpret a cell that starts with =, +, -,
    // @ or a tab as a formula. A hostile SQL template or service name
    // that begins with one of those characters would execute on open.
    // The apostrophe prefix neutralizes the formula without losing the
    // original text: spreadsheets display the cell as-is and drop the
    // leading apostrophe, consumers that parse the CSV literally keep
    // it. Strict first-byte check: do not strip leading whitespace
    // (a leading tab is itself a formula trigger on some clients).
    if (s.length > 0 && "=+-@\t".includes(s.charAt(0))) {
      s = "'" + s;
    }
    if (s.includes(",") || s.includes("\"") ||
        s.includes("\n") || s.includes("\r")) {
      return "\"" + s.replaceAll("\"", "\"\"") + "\"";
    }
    return s;
  }
  function csvLine(cells) {
    return cells.map(csvEscape).join(",");
  }
  // Note on numeric cells: producers pass JS numbers straight through
  // csvEscape, which calls String(n). That drops trailing zeros
  // (`840.0` -> `"840"`) because V8 Number.toString() normalizes the
  // decimal representation. Excel and every major CSV consumer handle
  // this correctly, so we keep the cheap path rather than forcing
  // `.toFixed(n)` per column.
  function buildCsv(header, rows) {
    var lines = [csvLine(header)];
    rows.forEach(function (r) { lines.push(csvLine(r)); });
    return lines.join("\r\n") + "\r\n";
  }
  function sanitizeLabelForFilename(s) {
    if (!s) return "";
    var cleaned = String(s).replaceAll(/[^A-Za-z0-9]+/g, "-");
    cleaned = cleaned.replaceAll(/-+/g, "-").replaceAll(/^-|-$/g, "");
    return cleaned;
  }
  function pad2(n) { return n < 10 ? "0" + n : String(n); }
  function timestampForFilename() {
    var d = new Date();
    return d.getFullYear() +
      pad2(d.getMonth() + 1) +
      pad2(d.getDate()) + "-" +
      pad2(d.getHours()) +
      pad2(d.getMinutes()) +
      pad2(d.getSeconds());
  }
  function buildCsvFilename(tabName) {
    var label = sanitizeLabelForFilename(payload.input_label || "");
    var prefix = label ? "perf-sentinel-" + label : "perf-sentinel";
    return prefix + "-" + tabName + "-" + timestampForFilename() + ".csv";
  }
  function downloadCsv(tabName, csvText) {
    var blob = new Blob([csvText], { type: "text/csv;charset=utf-8" });
    var url = URL.createObjectURL(blob);
    var a = document.createElement("a");
    a.href = url;
    a.download = buildCsvFilename(tabName);
    document.body.appendChild(a);
    a.click();
    a.remove();
    // Delay the revoke so the browser has the URL in hand when it
    // kicks off the download. Immediate revoke breaks the download on
    // some browsers. 0ms is enough to escape the current task.
    setTimeout(function () { URL.revokeObjectURL(url); }, 0);
  }

  function searchTermFor(tabKey) {
    var cfg = SEARCHABLE_TABS && SEARCHABLE_TABS[tabKey];
    if (!cfg) return "";
    var input = document.getElementById(cfg.inputId);
    if (!input) return "";
    return (input.value || "").toLowerCase();
  }
  function matchesSearch(haystack, term) {
    if (!term) return true;
    return String(haystack || "").toLowerCase().includes(term);
  }

  function exportFindingsCsv() {
    var term = searchTermFor("findings");
    var header = [
      "severity", "type", "service", "endpoint", "template",
      "occurrences", "first_timestamp", "last_timestamp",
      "code_function", "code_filepath", "code_lineno",
      "suggested_fix_framework", "suggested_fix_recommendation"
    ];
    var rows = applyFilters().filter(function (f) {
      var blob = [
        f.severity, f.type || f.finding_type, f.service, f.source_endpoint,
        f.pattern && f.pattern.template
      ].join(" ");
      return matchesSearch(blob, term);
    }).map(function (f) {
      var p = f.pattern || {};
      var loc = f.code_location || {};
      var fix = f.suggested_fix || {};
      return [
        f.severity || "",
        f.type || f.finding_type || "",
        f.service || "",
        f.source_endpoint || "",
        p.template || "",
        p.occurrences ?? "",
        f.first_timestamp || "",
        f.last_timestamp || "",
        loc.function || "",
        loc.filepath || "",
        loc.lineno ?? "",
        fix.framework || "",
        fix.recommendation || ""
      ];
    });
    downloadCsv("findings", buildCsv(header, rows));
  }

  function exportPgStatCsv() {
    var term = searchTermFor("pgstat");
    var header = [
      "template", "calls", "total_exec_time_ms", "mean_exec_time_ms",
      "rows", "shared_blks_hit", "shared_blks_read", "seen_in_traces"
    ];
    var rows = activePgStatEntries().filter(function (e) {
      return matchesSearch(e.normalized_template, term);
    }).map(function (e) {
      return [
        e.normalized_template || "",
        e.calls ?? "",
        e.total_exec_time_ms ?? "",
        e.mean_exec_time_ms ?? "",
        e.rows ?? "",
        e.shared_blks_hit ?? "",
        e.shared_blks_read ?? "",
        e.seen_in_traces ? "true" : "false"
      ];
    });
    downloadCsv("pgstat", buildCsv(header, rows));
  }

  function diffFindingMatchBlob(f) {
    return [
      f.severity, f.type || f.finding_type, f.service, f.source_endpoint,
      f.pattern && f.pattern.template
    ].join(" ");
  }
  function exportDiffCsv() {
    if (!hasDiff) return;
    var term = searchTermFor("diff");
    var header = [
      "section", "severity", "type", "service", "endpoint", "template",
      "occurrences", "before_severity", "after_severity",
      "before_io_ops", "after_io_ops", "delta"
    ];
    var rows = [];
    (diffData.new_findings || []).forEach(function (f) {
      if (!matchesSearch(diffFindingMatchBlob(f), term)) return;
      var p = f.pattern || {};
      rows.push([
        "new", f.severity || "", f.type || f.finding_type || "",
        f.service || "", f.source_endpoint || "", p.template || "",
        p.occurrences ?? "",
        "", "", "", "", ""
      ]);
    });
    (diffData.resolved_findings || []).forEach(function (f) {
      if (!matchesSearch(diffFindingMatchBlob(f), term)) return;
      var p = f.pattern || {};
      rows.push([
        "resolved", f.severity || "", f.type || f.finding_type || "",
        f.service || "", f.source_endpoint || "", p.template || "",
        p.occurrences ?? "",
        "", "", "", "", ""
      ]);
    });
    (diffData.severity_changes || []).forEach(function (c) {
      var f = c.finding || {};
      if (!matchesSearch(diffFindingMatchBlob(f), term)) return;
      var p = f.pattern || {};
      rows.push([
        "severity_change", "", f.type || f.finding_type || "",
        f.service || "", f.source_endpoint || "", p.template || "",
        p.occurrences ?? "",
        c.before_severity || "", c.after_severity || "",
        "", "", ""
      ]);
    });
    (diffData.endpoint_metric_deltas || []).forEach(function (d) {
      var blob = [d.service, d.endpoint].join(" ");
      if (!matchesSearch(blob, term)) return;
      rows.push([
        "endpoint_delta", "", "",
        d.service || "", d.endpoint || "", "",
        "", "", "",
        d.before_io_ops ?? "",
        d.after_io_ops ?? "",
        d.delta ?? ""
      ]);
    });
    downloadCsv("diff", buildCsv(header, rows));
  }

  function exportCorrelationsCsv() {
    var term = searchTermFor("correlations");
    var header = [
      "service_a", "type_a", "template_a",
      "service_b", "type_b", "template_b",
      "confidence", "co_occurrence_count",
      "source_total_occurrences", "median_lag_ms",
      "first_seen", "last_seen"
    ];
    var rows = correlations.filter(function (c) {
      var src = c.source || {};
      var tgt = c.target || {};
      var blob = [
        src.service, src.finding_type, tgt.service, tgt.finding_type
      ].join(" ");
      return matchesSearch(blob, term);
    }).map(function (c) {
      var s = c.source || {};
      var t = c.target || {};
      return [
        s.service || "", s.finding_type || "", s.template || "",
        t.service || "", t.finding_type || "", t.template || "",
        c.confidence ?? "",
        c.co_occurrence_count ?? "",
        c.source_total_occurrences ?? "",
        c.median_lag_ms ?? "",
        c.first_seen || "", c.last_seen || ""
      ];
    });
    downloadCsv("correlations", buildCsv(header, rows));
  }

  // -------- deep-link hash --------
  // Shape: `#<tab>[&k=v[&k=v...]]`. Medium-scope: tab, search term,
  // pg_stat ranking slug, findings severity chip, findings service chip.
  // Writes replace history entries (no back/forward pollution).
  var RANKING_SLUGS = ["total_time", "calls", "mean_time", "io_blocks"];
  function rankingSlugForIndex(idx) {
    return RANKING_SLUGS[idx] || String(idx);
  }
  function rankingIndexForSlug(slug) {
    if (RANKING_SLUGS.includes(slug)) return RANKING_SLUGS.indexOf(slug);
    var n = Number.parseInt(slug, 10);
    return Number.isFinite(n) ? n : -1;
  }

  // Keys accepted from the URL fragment. Anything outside this set is
  // ignored so a malformed or malicious hash cannot override the tab
  // via a later `tab=` pair, inject arbitrary properties onto `state`,
  // or confuse `applyHash`. The tab itself is positional (first
  // token), not a key=value pair. Stored as a Set so existence checks
  // are O(1) regardless of how many keys land here in the future.
  var HASH_KEYS = new Set(["search", "ranking", "severity", "service"]);
  function readHash() {
    var raw = (location.hash || "").replace(/^#/, "");
    if (!raw) return null;
    var parts = raw.split("&");
    var state = { tab: parts.shift() || null };
    parts.forEach(function (p) {
      if (!p) return;
      var eq = p.indexOf("=");
      if (eq < 0) return;
      var k = p.slice(0, eq);
      if (!HASH_KEYS.has(k)) return;
      var v = p.slice(eq + 1);
      try {
        v = decodeURIComponent(v);
      } catch {
        // Malformed percent-encoding in a shared URL, keep the raw
        // value so downstream string compares still work.
        return;
      }
      state[k] = v;
    });
    return state;
  }

  function currentStateForHash() {
    var state = { tab: currentTab };
    if (currentTab && SEARCHABLE_TABS[currentTab]) {
      var term = searchTermFor(currentTab);
      if (term) state.search = term;
    }
    if (currentTab === "findings") {
      if (filterState.severity) state.severity = filterState.severity;
      if (filterState.service) state.service = filterState.service;
    }
    if (currentTab === "pgstat") {
      state.ranking = rankingSlugForIndex(activeRankingIndex);
    }
    return state;
  }

  function encodeHashFromState(state) {
    if (!state || !state.tab) return "";
    var parts = [state.tab];
    ["search", "ranking", "severity", "service"].forEach(function (k) {
      var v = state[k];
      if (v !== null && v !== undefined && v !== "") {
        parts.push(k + "=" + encodeURIComponent(String(v)));
      }
    });
    return parts.join("&");
  }

  // Guards against applyHash / writeHash ping-pong. The hashchange
  // listener compares this against location.hash to tell user-driven
  // changes from our own writeHash calls.
  var _lastWrittenHash = null;

  function writeHash(state) {
    var hashStr = encodeHashFromState(state);
    var full = hashStr ? "#" + hashStr : "";
    try {
      history.replaceState(null, "", full || location.pathname + location.search);
      _lastWrittenHash = hashStr;
    } catch {
      // Old browsers without history.replaceState: fall back to a
      // direct hash assignment. Pushes one history entry per change,
      // the lesser of two evils.
      location.hash = hashStr;
      _lastWrittenHash = hashStr;
    }
  }

  // Debounce writeHash to smooth keystrokes in search inputs and bursty
  // chip clicks; 200ms is barely perceptible and keeps history quiet.
  var hashWriteTimer = null;
  function scheduleHashWrite() {
    if (hashWriteTimer) clearTimeout(hashWriteTimer);
    hashWriteTimer = setTimeout(function () {
      hashWriteTimer = null;
      writeHash(currentStateForHash());
    }, 200);
  }

  function applyHash(state) {
    if (!state || !state.tab) return false;
    if (!tabIsRegistered(state.tab)) return false;
    // Apply filter state before switching so the target tab already
    // shows the correct view. Severity / service chips modify
    // filterState and re-render the findings list.
    if (state.tab === "findings") {
      filterState.severity = null;
      filterState.service = null;
      if (state.severity === "critical" || state.severity === "warning") {
        filterState.severity = state.severity;
      }
      if (state.service) filterState.service = state.service;
      syncFilterChips();
      resetShownCount();
      renderFindingsList();
    }
    if (state.tab === "pgstat") {
      var idx = rankingIndexForSlug(state.ranking || "");
      if (idx >= 0 && idx < pgStatRankings.length) {
        // Single source of truth: selectPgStatRanking handles both the
        // sessionStorage write and the early-return when idx already
        // matches activeRankingIndex.
        selectPgStatRanking(idx);
      }
    }
    switchTab(state.tab);
    // Restore the search input for the target tab after tab switch,
    // which runs `clearAllSearchFilters`. Reapply the filter so rows
    // match the decoded search term.
    if (state.search && SEARCHABLE_TABS[state.tab]) {
      var cfg = SEARCHABLE_TABS[state.tab];
      var input = document.getElementById(cfg.inputId);
      if (input) {
        input.style.display = "block";
        input.value = state.search;
        applySearchFilter(cfg);
      }
    }
    return true;
  }

  // -------- cheatsheet modal --------
  var CHEATSHEET_ROWS = [
    ["j", "Move finding selection down"],
    ["k", "Move finding selection up"],
    ["Enter", "Open selected finding in Explain"],
    ["Esc", "Close help, close search, clear filters, back from Explain"],
    ["/", "Open filter search for active tab"],
    ["g f", "Go to Findings"],
    ["g e", "Go to Explain (if available)"],
    ["g p", "Go to pg_stat (if available)"],
    ["g d", "Go to Diff (if available)"],
    ["g c", "Go to Correlations (if available)"],
    ["g r", "Go to GreenOps (if available)"],
    ["?", "Show this cheatsheet"]
  ];
  function populateCheatsheet() {
    var body = document.getElementById("cheatsheet-body");
    if (!body) return;
    body.textContent = "";
    CHEATSHEET_ROWS.forEach(function (row) {
      var tr = document.createElement("tr");
      var tdK = document.createElement("td");
      var kbd = el("span", "ps-kbd", row[0]);
      tdK.appendChild(kbd);
      tr.appendChild(tdK);
      tr.appendChild(el("td", null, row[1]));
      body.appendChild(tr);
    });
  }
  // Native <dialog> element: the browser manages the backdrop, the
  // focus trap, and the Esc-to-close behavior. We only layer focus
  // restoration and backdrop-click-to-close on top.
  function isCheatsheetOpen() {
    var dlg = document.getElementById("cheatsheet");
    return !!(dlg && dlg.open);
  }
  // Stash the element that owned focus when the cheatsheet opened so
  // closing restores the j/k cursor position in the Findings list (or
  // wherever the user came from). Cleared on close.
  var cheatsheetPriorFocus = null;
  function openCheatsheet() {
    var dlg = document.getElementById("cheatsheet");
    if (!dlg || dlg.open) return;
    cheatsheetPriorFocus = document.activeElement;
    dlg.showModal();
    var closeBtn = document.getElementById("cheatsheet-close");
    if (closeBtn) closeBtn.focus();
  }
  function closeCheatsheet() {
    var dlg = document.getElementById("cheatsheet");
    if (dlg && dlg.open) dlg.close();
  }
  function toggleCheatsheet() {
    if (isCheatsheetOpen()) closeCheatsheet();
    else openCheatsheet();
  }

  function anyFilterChipActive() {
    return !!(filterState.severity || filterState.service);
  }
  function clearFilterChips() {
    filterState.severity = null;
    filterState.service = null;
    syncFilterChips();
    resetShownCount();
    renderFindingsList();
  }

  // -------- keyboard --------
  function isSearchInputFocused() {
    var active = document.activeElement;
    return !!(active && active.tagName === "INPUT" && active.classList.contains("ps-search"));
  }
  function isTextInputFocused() {
    var a = document.activeElement;
    if (!a) return false;
    var tag = a.tagName;
    if (tag === "INPUT" || tag === "TEXTAREA") return true;
    return a.isContentEditable === true;
  }
  /// Escape ladder: close cheatsheet, close search, leave Explain,
  /// clear filter chips. Each tier returns as soon as it acts.
  function handleEscape(ev) {
    if (isCheatsheetOpen()) {
      closeCheatsheet();
      ev.preventDefault();
      return;
    }
    if (isSearchInputFocused()) {
      closeSearch(document.activeElement);
      ev.preventDefault();
      return;
    }
    if (currentTab === "explain") {
      switchTab("findings");
      return;
    }
    if (currentTab === "findings" && anyFilterChipActive()) {
      clearFilterChips();
      scheduleHashWrite();
      ev.preventDefault();
    }
  }
  /// Slash handling: open the active tab's search input.
  function handleSlash(ev) {
    if (isSearchInputFocused() || !SEARCHABLE_TABS[currentTab]) return;
    openSearchForActiveTab();
    ev.preventDefault();
  }
  /// j / k / enter navigation on the Findings list.
  function handleFindingsNav(ev) {
    if (visibleFindings.length === 0) return;
    if (ev.key === "j") {
      selectedIndex = (selectedIndex + 1) % visibleFindings.length;
      syncSelection();
      scrollSelectedIntoView();
    } else if (ev.key === "k") {
      selectedIndex = (selectedIndex - 1 + visibleFindings.length) % visibleFindings.length;
      syncSelection();
      scrollSelectedIntoView();
    } else if (ev.key === "Enter" && selectedIndex >= 0) {
      openExplain(visibleFindings[selectedIndex]);
    }
    ev.preventDefault();
  }
  // g-prefixed tab shortcuts. `g` alone arms a 1000ms window; the next
  // key consumes it regardless of whether it matches a tab. Hidden tabs
  // are a silent no-op (no feedback, no flash).
  var pendingGTimer = null;
  var G_MAPPING = {
    f: "findings", e: "explain", p: "pgstat",
    d: "diff", c: "correlations", r: "green"
  };
  function clearPendingG() {
    if (pendingGTimer) {
      clearTimeout(pendingGTimer);
      pendingGTimer = null;
    }
  }
  function handleGPrefix(ev) {
    // Ignore OS-level key autorepeat: holding `g` must not rearm the
    // prefix, and holding the second letter must not fire the tab
    // switch twice. The dispatcher continues past this handler so
    // autorepeat on j/k/Enter still drives Findings navigation.
    if (ev.repeat) return false;
    if (ev.key === "g" && pendingGTimer === null) {
      pendingGTimer = setTimeout(function () { pendingGTimer = null; }, 1000);
      return true;
    }
    if (pendingGTimer !== null) {
      clearPendingG();
      var target = G_MAPPING[ev.key];
      if (target && tabIsRegistered(target)) {
        switchTab(target);
        ev.preventDefault();
      }
      return true;
    }
    return false;
  }
  document.addEventListener("keydown", function (ev) {
    if (ev.key === "Escape") { handleEscape(ev); return; }
    // `?` opens the cheatsheet unless a text input is consuming it.
    if (ev.key === "?" && !isTextInputFocused()) {
      toggleCheatsheet();
      ev.preventDefault();
      return;
    }
    if (isCheatsheetOpen()) return;
    if (ev.key === "/") { handleSlash(ev); return; }
    if (isSearchInputFocused()) return;
    if (isTextInputFocused()) return;
    if (handleGPrefix(ev)) return;
    if (currentTab !== "findings") return;
    if (ev.key === "j" || ev.key === "k" || ev.key === "Enter") {
      handleFindingsNav(ev);
    }
  });
  function scrollSelectedIntoView() {
    var rows = document.querySelectorAll("#findings-list .ps-row");
    if (selectedIndex >= 0 && selectedIndex < rows.length) {
      rows[selectedIndex].scrollIntoView({ block: "nearest" });
    }
  }

  document.getElementById("pgstat-drill-clear").addEventListener("click", clearPgStatDrill);

  // -------- boot helpers --------
  // Each helper owns one slice of boot work so the IIFE body stays
  // linear and cognitive complexity stays bounded. Sonar flags the
  // IIFE itself when too many branches accumulate at this level.

  function registerAllTabs() {
    registerTab("findings", "Findings", function () { return findings.length; });
    registerTab("explain", "Explain", null);
    if (hasPgStat) {
      registerTab("pgstat", "pg_stat", function () {
        // Badge shows the currently-active ranking's entry count. Every
        // ranking contains the same top-N entries, just reordered, so
        // the number is identical across rankings (see rank_pg_stat).
        return activePgStatEntries().length;
      });
    }
    if (hasDiff) {
      registerTab("diff", "Diff", function () {
        return (
          (diffData.new_findings || []).length + (diffData.resolved_findings || []).length
        );
      });
    }
    if (hasCorrelations) {
      registerTab("correlations", "Correlations", function () {
        return correlations.length;
      });
    }
    if (hasGreen) registerTab("green", "GreenOps", null);
    renderTabs();
  }

  function restorePersistedPgStatRanking() {
    // Restore the persisted ranking before the first render so the
    // initial table already reflects the user's last choice. A hash
    // with a ranking slug overrides this, inside `applyHash`.
    if (!hasPgStat) return;
    var storedRanking = sessionGet(STORAGE_KEYS.pgstatRanking);
    if (!storedRanking) return;
    var storedIdx = rankingIndexForSlug(storedRanking);
    if (storedIdx >= 0 && storedIdx < pgStatRankings.length) {
      activeRankingIndex = storedIdx;
    }
  }

  function renderAllPanels() {
    renderTrimBanner();
    renderFindingsMetrics();
    renderFilterChips();
    restorePersistedPgStatRanking();
    renderFindingsList();
    if (hasPgStat) renderPgStatPanel();
    if (hasDiff) renderDiffPanel();
    if (hasCorrelations) renderCorrelationsPanel();
    if (hasGreen) renderGreenPanel();
  }

  function wireCheatsheetDialog() {
    var closeBtn = document.getElementById("cheatsheet-close");
    if (closeBtn) closeBtn.addEventListener("click", closeCheatsheet);
    var dlg = document.getElementById("cheatsheet");
    if (!dlg) return;
    // Native <dialog> manages Esc-to-close and the focus trap for us.
    // We only restore focus to wherever it was before the dialog
    // opened, on the close event (covers both our manual close and
    // the native Esc path).
    dlg.addEventListener("close", restorePriorFocus);
    // Click outside the dialog's content area closes it. With
    // showModal(), clicks on the backdrop hit the dialog itself,
    // clicks on any descendant hit that descendant.
    dlg.addEventListener("click", function (ev) {
      if (ev.target === dlg) closeCheatsheet();
    });
  }

  function restorePriorFocus() {
    var prior = cheatsheetPriorFocus;
    cheatsheetPriorFocus = null;
    if (!prior || typeof prior.focus !== "function") return;
    try {
      prior.focus();
    } catch {
      // Prior element was removed while the dialog was open (most
      // likely a re-render). Silent fallback: the browser picks a
      // sensible default.
      return;
    }
  }

  function wireShowMoreButton() {
    var btn = document.getElementById("findings-show-more");
    if (!btn) return;
    btn.addEventListener("click", function () {
      shownCount += LIST_CAP;
      renderFindingsList();
    });
  }

  function wireExportButtons() {
    var exportHandlers = {
      findings: exportFindingsCsv,
      pgstat: exportPgStatCsv,
      diff: exportDiffCsv,
      correlations: exportCorrelationsCsv
    };
    Object.keys(exportHandlers).forEach(function (tabKey) {
      var btn = document.getElementById(tabKey + "-export");
      if (btn) btn.addEventListener("click", exportHandlers[tabKey]);
    });
  }

  // -------- copy-link buttons --------
  function copyCurrentLink(btn) {
    // Capture the label once so repeat clicks inside the flash window
    // do not end up restoring "Copied" as the baseline.
    if (!btn.dataset.baseLabel) btn.dataset.baseLabel = btn.textContent;
    var baseLabel = btn.dataset.baseLabel;
    var href = location.href;

    function flashCopied() {
      btn.textContent = "Copied";
      if (btn._copyFlashTimer) clearTimeout(btn._copyFlashTimer);
      btn._copyFlashTimer = setTimeout(function () {
        btn._copyFlashTimer = null;
        btn.textContent = baseLabel;
      }, 1500);
    }

    // file:// origins and older browsers reject navigator.clipboard,
    // so fall back to a throwaway textarea + execCommand.
    function fallbackCopy() {
      try {
        var ta = document.createElement("textarea");
        ta.value = href;
        ta.setAttribute("readonly", "");
        ta.style.position = "absolute";
        ta.style.left = "-9999px";
        document.body.appendChild(ta);
        ta.select();
        var ok = document.execCommand("copy");
        ta.remove();
        if (ok) {
          flashCopied();
        } else {
          console.error("copyCurrentLink: execCommand('copy') returned false");
        }
      } catch (err) {
        console.error("copyCurrentLink fallback failed", err);
      }
    }

    if (navigator.clipboard && typeof navigator.clipboard.writeText === "function") {
      navigator.clipboard.writeText(href).then(flashCopied, function (err) {
        console.error("navigator.clipboard.writeText rejected", err);
        fallbackCopy();
      });
    } else {
      fallbackCopy();
    }
  }

  function wireCopyLinkButtons() {
    ["findings", "pgstat", "diff", "correlations"].forEach(function (tabKey) {
      var btn = document.getElementById(tabKey + "-copy-link");
      if (!btn) return;
      btn.addEventListener("click", function () {
        copyCurrentLink(btn);
      });
    });
  }

  function applyInitialHashOrWrite() {
    // Apply the deep-link hash last so it can override the initial
    // ranking / filter chips / tab selection derived above. Falls
    // through silently when the hash is missing, malformed, or points
    // to a tab that is not registered in this report.
    var initialHash = readHash();
    if (applyHash(initialHash)) return;
    // No hash: emit the current state so sharing the URL immediately
    // after load produces a self-describing link.
    writeHash(currentStateForHash());
  }

  function wireHashChangeListener() {
    // Skip events triggered by our own writeHash replaceState, apply
    // only real user-driven changes.
    globalThis.addEventListener("hashchange", function () {
      var raw = (location.hash || "").replace(/^#/, "");
      if (raw === _lastWrittenHash) return;
      applyHash(readHash());
    });
  }

  // -------- boot --------
  renderTopbar();
  registerAllTabs();
  renderAllPanels();
  initSearchInputs();
  populateCheatsheet();
  wireCheatsheetDialog();
  wireShowMoreButton();
  wireExportButtons();
  wireCopyLinkButtons();
  applyInitialHashOrWrite();
  wireHashChangeListener();
})();
</script>
</body>
</html>