perf-sentinel-core 0.9.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
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
<!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="{{CONTENT_SECURITY_POLICY}}" />
<title>{{PAGE_TITLE}}</title>
<style>
{{FONT_FACES}}
  /* ============================================================
     perf-sentinel HTML report, app-shell redesign (release/0.9.0)
     Design tokens ported verbatim from the hi-fi handoff prototype.
     @font-face blocks for embedded Geist / Geist Mono are injected
     in the font-embedding step; the stacks below fall back to
     system fonts until then.
     ============================================================ */
  :root {
    --font-ui: 'Geist', system-ui, -apple-system, 'Segoe UI', sans-serif;
    --font-mono: 'Geist Mono', 'JetBrains Mono', 'SF Mono', ui-monospace, Consolas, monospace;
    /* Legacy aliases kept so any un-migrated rule still resolves. */
    --font-sans: var(--font-ui);
    --r: 11px; --r-sm: 7px;
  }
  :root[data-theme="dark"] {
    --bg: #0c100e; --surface: #141a17; --surface-2: #1a221d; --surface-3: #212b25;
    --border: rgba(255,255,255,.35); --border-2: rgba(255,255,255,.5);
    --text: #e8ede9; --text-2: #aabbb3; --text-3: #8a988f;
    --brand: #2fd49a; --brand-2: #0ba671; --brand-text: #2fd49a; --accent-bg: rgba(47,212,154,.10);
    --crit-fg: #ff8d8d; --crit-bg: rgba(255,99,99,.12); --crit-bd: rgba(255,99,99,.26);
    --warn-fg: #f2b65f; --warn-bg: rgba(242,170,80,.12); --warn-bd: rgba(242,170,80,.24);
    --info-fg: #74b8ff; --info-bg: rgba(96,166,255,.12); --info-bd: rgba(96,166,255,.24);
    --ok-fg: #46d6a0; --ok-bg: rgba(47,212,154,.13); --ok-bd: rgba(47,212,154,.28);
    --glow: radial-gradient(120% 140% at 0% 0%, rgba(47,212,154,.10), transparent 55%);
  }
  :root[data-theme="light"] {
    --bg: #f3f6f4; --surface: #ffffff; --surface-2: #f6f9f7; --surface-3: #eef2f0;
    --border: rgba(11,40,30,.55); --border-2: rgba(11,40,30,.66);
    --text: #0f1f18; --text-2: #4d5d56; --text-3: #5f6d65;
    --brand: #0ba671; --brand-2: #0b523a; --brand-text: #0a7850; --accent-bg: rgba(11,166,113,.09);
    --crit-fg: #bf2a22; --crit-bg: #fbeceb; --crit-bd: #f0cdca;
    --warn-fg: #8a5a14; --warn-bg: #f7efdc; --warn-bd: #e8d4ab;
    --info-fg: #1f5e9e; --info-bg: #e9f0f8; --info-bd: #c8dbef;
    --ok-fg: #0a7a52; --ok-bg: #e7f4ee; --ok-bd: #a6d4be;
    --glow: radial-gradient(120% 140% at 0% 0%, rgba(11,166,113,.07), transparent 55%);
  }

  /* -------- base -------- */
  * { box-sizing: border-box; }
  html, body { margin: 0; height: 100%; }
  body { background: var(--bg); color: var(--text); font-family: var(--font-ui); font-size: 13px; line-height: 1.5; }
  ::-webkit-scrollbar { width: 10px; height: 10px; }
  ::-webkit-scrollbar-thumb { background: var(--border-2); border-radius: 6px; }
  ::-webkit-scrollbar-track { background: transparent; }
  input { font-family: inherit; }
  a { color: var(--brand-text); }

  /* -------- severity + tone (attribute-driven, drives every pill/tag) -------- */
  [data-sev] { font-family: var(--font-mono); font-weight: 600; letter-spacing: .4px; }
  [data-sev="crit"] { color: var(--crit-fg); background: var(--crit-bg); border: 1px solid var(--crit-bd); }
  [data-sev="warn"] { color: var(--warn-fg); background: var(--warn-bg); border: 1px solid var(--warn-bd); }
  [data-sev="info"] { color: var(--info-fg); background: var(--info-bg); border: 1px solid var(--info-bd); }
  [data-sev="ok"] { color: var(--ok-fg); background: var(--ok-bg); border: 1px solid var(--ok-bd); }
  [data-tone="crit"] { color: var(--crit-fg); }
  [data-tone="ok"] { color: var(--ok-fg); }
  [data-tone="warn"] { color: var(--warn-fg); }
  [data-tone="neutral"] { color: var(--text); }
  [data-tone="brand"] { color: var(--brand); }
  [data-d="0"] { margin-left: 0; } [data-d="1"] { margin-left: 22px; }
  [data-d="2"] { margin-left: 44px; } [data-d="3"] { margin-left: 66px; }

  /* -------- app shell -------- */
  .ps-shell { display: grid; grid-template-columns: 252px 1fr; min-height: 100vh; background-image: var(--glow); }
  .ps-sidebar { border-right: 1px solid var(--border); background: var(--surface); }
  /* Inner wrapper carries the sticky 100vh column so the sidebar element
     itself stretches to the full grid-cell height (no empty gap below the
     nav on tabs taller than the viewport). */
  .ps-sidebar-sticky { position: sticky; top: 0; height: 100vh; display: flex; flex-direction: column; }
  .ps-brand-block { padding: 20px 18px 14px; display: flex; flex-direction: column; gap: 7px; align-items: flex-start; }
  .ps-brand { display: block; text-decoration: none; }
  .ps-logo { display: none; }
  .ps-logo svg, .ps-logo img { height: 34px; width: auto; display: block; }
  /* Theme-swapped wordmark. data-theme is always resolved to a concrete
     light/dark by applyTheme, so exactly one variant shows. */
  :root[data-theme="dark"] .ps-logo-dark { display: block; }
  :root[data-theme="light"] .ps-logo-light { display: block; }
  .ps-brand-eyebrow { font-family: var(--font-mono); font-size: 11px; letter-spacing: .6px; color: var(--text-3); padding-left: 2px; }
  .ps-nav { display: flex; flex-direction: column; gap: 0; padding: 8px 10px; flex: 1; overflow: auto; }
  .ps-nav-eyebrow { font-family: var(--font-mono); font-size: 11px; letter-spacing: 1.2px; text-transform: uppercase; color: var(--text-3); padding: 10px 9px 6px; }
  [data-nav] { appearance: none; font-family: inherit; width: 100%; text-align: left; display: flex; align-items: center; gap: 10px; padding: 8px 9px; border-radius: var(--r-sm); font-size: 13px; font-weight: 500; color: var(--text-2); background: transparent; border: 0; cursor: pointer; transition: background .13s, color .13s, transform .13s; }
  [data-nav]:hover { color: var(--text); background: var(--surface-2); transform: translateX(3px); }
  [data-nav]:hover > .ps-nav-dot { background: var(--brand); opacity: 1; }
  [data-nav] + [data-nav] { border-top: 1px solid var(--border); }
  [data-nav][aria-selected="true"] { color: var(--text); background: var(--accent-bg); box-shadow: inset 2px 0 0 var(--brand); }
  .ps-nav-dot { width: 6px; height: 6px; border-radius: 2px; background: currentColor; opacity: .85; flex: none; }
  .ps-nav-label { flex: 1; }
  .ps-nav-badge { font-family: var(--font-mono); font-size: 11px; color: var(--text-3); }
  /* The run-context line (batch/CI, daemon staging/prod) and the version
     line show in every mode. The dot only pulses in live/daemon mode. */
  .ps-sidebar-foot { display: flex; height: 62px; padding: 0 16px; border-top: 1px solid var(--border); flex-direction: column; justify-content: center; gap: 6px; }
  .ps-sidebar-foot-status { display: flex; align-items: center; gap: 8px; }
  .ps-sidebar-foot-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--text-3); flex: none; }
  .ps-sidebar-foot-dot[data-ctx="ok"] { background: var(--ok-fg); }
  .ps-sidebar-foot-dot[data-ctx="warn"] { background: var(--warn-fg); }
  body.ps-live .ps-sidebar-foot-dot { animation: ps-pulse 2.4s ease-in-out infinite; }
  .ps-sidebar-foot-text { font-family: var(--font-mono); font-size: 11px; color: var(--text-2); }
  .ps-sidebar-foot-version { font-family: var(--font-mono); font-size: 11px; color: var(--text-3); }

  .ps-main { display: flex; flex-direction: column; min-width: 0; }
  .ps-topbar { position: sticky; top: 0; z-index: 5; display: flex; align-items: center; gap: 12px; row-gap: 10px; flex-wrap: wrap; padding: 14px 28px; border-bottom: 1px solid var(--border); background: color-mix(in srgb, var(--bg) 82%, transparent); backdrop-filter: blur(8px); }
  .ps-topbar-title { display: flex; flex-direction: column; gap: 3px; min-width: 0; flex: 1 1 auto; }
  .ps-topbar-eyebrow { font-family: var(--font-mono); font-size: 11px; letter-spacing: 1.2px; text-transform: uppercase; color: var(--text-3); }
  .ps-topbar-h1 { margin: 0; font-size: 17px; font-weight: 600; letter-spacing: -.3px; color: var(--text); }
  .ps-gate-pass, .ps-gate-fail { display: inline-flex; align-items: center; gap: 7px; padding: 6px 11px; border-radius: 20px; font-size: 11px; font-family: var(--font-mono); font-weight: 600; white-space: nowrap; }
  .ps-gate-pass { color: var(--ok-fg); background: var(--ok-bg); border: 1px solid var(--ok-bd); }
  .ps-gate-fail { color: var(--crit-fg); background: var(--crit-bg); border: 1px solid var(--crit-bd); }
  .ps-gate-pass::before, .ps-gate-fail::before { content: ""; width: 6px; height: 6px; border-radius: 50%; background: currentColor; }
  .ps-content { padding: 24px 28px 0; overflow: auto; flex: 1; display: flex; flex-direction: column; }
  .ps-panel { display: flex; flex-direction: column; gap: 14px; }
  .ps-panel-narrow { max-width: 1100px; }
  .ps-panel-wide { max-width: 1240px; }

  /* -------- generic controls -------- */
  [data-ghost] { cursor: pointer; transition: border-color .12s, color .12s; border: 1px solid var(--border); border-radius: var(--r-sm); padding: 7px 11px; font-size: 12px; color: var(--text-2); background: transparent; font-family: inherit; }
  [data-ghost]:hover { border-color: var(--border-2); color: var(--text); }
  .ps-theme-toggle { display: inline-flex; align-items: center; gap: 7px; border: 1px solid var(--border); border-radius: var(--r-sm); padding: 7px 11px; font-size: 12px; color: var(--text-2); background: transparent; cursor: pointer; font-family: inherit; }
  .ps-theme-toggle:hover { border-color: var(--border-2); color: var(--text); }
  .ps-theme-toggle .ps-th-svg { flex: none; }
  .ps-theme-toggle .ps-th-svg.accent { color: var(--brand-text); }
  /* Per-panel filter input: hidden until the user presses "/" (toggled via inline style by the search wiring). */
  .ps-search { display: none; width: 100%; padding: 8px 11px; font-size: 12.5px; font-family: var(--font-ui); background: var(--surface-2); border: 1px solid var(--border); border-radius: var(--r-sm); color: var(--text); outline: none; }
  .ps-search:focus { border-color: var(--brand); }
  .ps-search-box { display: flex; align-items: center; gap: 8px; border: 1px solid var(--border); background: var(--surface); border-radius: var(--r-sm); padding: 0 11px; height: 34px; flex: 0 0 390px; min-width: 0; }
  .ps-search-box .ps-search-glyph { color: var(--text-3); font-size: 13px; }
  .ps-search-box .ps-search { display: flex; width: auto; flex: 1; min-width: 0; border: 0; background: transparent; padding: 0; }
  .ps-search-box .ps-search-kbd { font-family: var(--font-mono); font-size: 11px; color: var(--text-3); border: 1px solid var(--border); border-radius: 4px; padding: 1px 5px; }

  /* -------- cards / metrics -------- */
  /* overflow:hidden clips edge-to-edge rows (and the selected row's inset
     brand bar) to the card's rounded corners, so the green selection bar
     never spills past the corner and the border stays unbroken. */
  .ps-card { border: 1px solid var(--border); border-radius: var(--r); background: var(--surface); overflow: hidden; }
  .ps-metrics { display: grid; grid-template-columns: repeat(4, 1fr); gap: 12px; }
  .ps-metrics-3 { grid-template-columns: repeat(3, 1fr); }
  .ps-metric { border: 1px solid var(--border); border-radius: var(--r); background: var(--surface); padding: 15px 16px; display: flex; flex-direction: column; gap: 9px; }
  /* Severity-tinted gradient (top -> transparent), matching the gate hero. */
  .ps-metric[data-grad="crit"] { background-image: linear-gradient(180deg, var(--crit-bg), transparent); }
  .ps-metric[data-grad="warn"] { background-image: linear-gradient(180deg, var(--warn-bg), transparent); }
  .ps-metric[data-grad="ok"] { background-image: linear-gradient(180deg, var(--ok-bg), transparent); }
  .ps-metric[data-grad="brand"] { background-image: linear-gradient(180deg, var(--accent-bg), transparent); }
  .ps-metric-label { font-family: var(--font-mono); font-size: 11px; letter-spacing: .9px; text-transform: uppercase; color: var(--text-3); }
  .ps-metric-value { font-size: 27px; font-weight: 600; letter-spacing: -.6px; word-break: break-word; }
  .ps-metric-value-sm { font-size: 16px; line-height: 1.4; }
  .ps-metric-sub { font-family: var(--font-mono); font-size: 11px; color: var(--text-3); }

  /* -------- overview landing -------- */
  .ps-hero { display: grid; grid-template-columns: 300px 1fr; overflow: hidden; }
  .ps-hero-left { padding: 24px 26px; border-right: 1px solid var(--border); background: linear-gradient(180deg, var(--accent-bg), transparent); }
  /* Gate FAIL: same gradient as PASS but red at the top, fading to transparent. */
  .ps-hero-left[data-tone="crit"] { background: linear-gradient(180deg, var(--crit-bg), transparent); }
  .ps-hero-verdict { display: flex; align-items: center; gap: 12px; margin-top: 14px; }
  .ps-hero-dot { width: 13px; height: 13px; border-radius: 50%; background: currentColor; flex: none; }
  .ps-hero-big { font-size: 44px; font-weight: 700; letter-spacing: -1px; line-height: 1; }
  .ps-hero-line { margin: 14px 0 0; font-size: 13px; color: var(--text-2); max-width: 230px; }
  .ps-hero-right { padding: 20px 24px; display: flex; flex-direction: column; justify-content: center; gap: 16px; }
  .ps-hero-rules { display: grid; grid-template-columns: 1fr 1fr; gap: 10px 22px; }
  .ps-hero-rule { display: flex; align-items: flex-start; gap: 10px; min-width: 0; }
  .ps-hero-rule-chip { width: 16px; height: 16px; border-radius: 5px; display: flex; align-items: center; justify-content: center; font-size: 11px; flex: none; margin-top: 1px; }
  .ps-hero-rule-text { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
  .ps-hero-rule-name { font-size: 12.5px; font-weight: 500; color: var(--text); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
  .ps-hero-rule-detail { font-family: var(--font-mono); font-size: 11px; color: var(--text-3); }
  .ps-hero-meta { display: flex; flex-wrap: wrap; gap: 18px; padding-top: 14px; border-top: 1px solid var(--border); font-family: var(--font-mono); font-size: 11px; color: var(--text-3); }
  /* correlations cards */
  #correlations-list { display: flex; flex-direction: column; gap: 10px; }
  .ps-corr-card { display: flex; align-items: center; gap: 14px; border: 1px solid var(--border); border-radius: var(--r); background: var(--surface); padding: 15px 18px; }
  .ps-corr-tag { padding: 3px 8px; border-radius: 5px; font-size: 11px; }
  .ps-corr-path { font-family: var(--font-mono); font-size: 12.5px; color: var(--text); }
  .ps-corr-meta { font-family: var(--font-mono); font-size: 11px; color: var(--text-3); margin-left: auto; white-space: nowrap; }
  /* carbon formula banner (class name mirrors the existing .ps-scoring-bandeau) */
  .ps-formula-bandeau { display: flex; align-items: center; gap: 22px; flex-wrap: wrap; border: 1px solid var(--border); border-radius: var(--r); background: linear-gradient(180deg, var(--accent-bg), transparent); padding: 18px 22px; }
  .ps-formula-code { font-family: var(--font-mono); font-size: 17px; color: var(--text); font-weight: 500; background: var(--surface-3); border: 1px solid var(--border); border-radius: var(--r-sm); padding: 8px 14px; }
  .ps-formula-text { font-size: 12.5px; color: var(--text-2); max-width: 560px; }
  /* diff two-column cards + horizontal rows */
  .ps-diff-cols { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; align-items: start; }
  .ps-row.ps-diff-row { flex-direction: row; align-items: center; gap: 10px; padding: 12px 18px; }
  .ps-diff-type { font-size: 12.5px; color: var(--text); }
  .ps-diff-endpoint { font-family: var(--font-mono); font-size: 11px; color: var(--text-3); margin-left: auto; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
  .ps-card .ps-table th:first-child, .ps-card .ps-table td:first-child { padding-left: 18px; }
  .ps-card .ps-table th:last-child, .ps-card .ps-table td:last-child { padding-right: 18px; }
  .ps-overview-cols { display: grid; grid-template-columns: 1.55fr 1fr; gap: 14px; align-items: start; }
  .ps-overview-card-head { display: flex; align-items: center; justify-content: space-between; padding: 15px 18px; border-bottom: 1px solid var(--border); }
  .ps-overview-card-title { font-size: 13px; font-weight: 600; color: var(--text); }
  .ps-overview-link { font-family: var(--font-mono); font-size: 11px; color: var(--text-2); background: transparent; border: 0; cursor: pointer; }
  .ps-overview-link:hover { color: var(--text); }
  .ps-overview-rail { display: flex; flex-direction: column; gap: 14px; }
  .ps-row.ps-overview-finding { flex-direction: row; align-items: center; justify-content: space-between; gap: 12px; }
  .ps-of-left { display: flex; flex-direction: column; gap: 7px; min-width: 0; }
  .ps-of-right { display: flex; flex-direction: column; align-items: flex-end; gap: 3px; flex: none; }
  .ps-of-primary { font-family: var(--font-mono); font-size: 12px; color: var(--text-2); }
  .ps-of-secondary { font-family: var(--font-mono); font-size: 11px; color: var(--text-3); }
  .ps-mini-card { border: 1px solid var(--border); border-radius: var(--r); background: var(--surface); padding: 16px 18px; display: flex; flex-direction: column; gap: 13px; }
  .ps-mini-head { display: flex; align-items: baseline; justify-content: space-between; }
  .ps-mini-title { font-size: 13px; font-weight: 600; color: var(--text); }
  .ps-mini-total { font-family: var(--font-mono); font-size: 12px; color: var(--brand-text); }
  .ps-mini-pills { display: flex; gap: 9px; flex-wrap: wrap; }
  .ps-mini-pill { padding: 4px 10px; border-radius: 20px; font-size: 11px; }
  .ps-mini-link { font-family: var(--font-mono); font-size: 11px; color: var(--text-2); background: transparent; border: 0; cursor: pointer; align-self: flex-start; }
  .ps-mini-link:hover { color: var(--text); }
  /* Underline the link label but not the trailing arrow. */
  .ps-link-txt { text-decoration: underline; }
  .ps-mini-row { display: flex; flex-direction: column; gap: 5px; }
  .ps-mini-row-head { display: flex; justify-content: space-between; font-family: var(--font-mono); font-size: 11px; }
  .ps-bar-track { height: 6px; border-radius: 4px; background: var(--surface-3); overflow: hidden; }
  .ps-bar-fill { height: 100%; border-radius: 4px; background: var(--brand); }

  /* -------- chips / filters -------- */
  .ps-filters { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; }
  .ps-chip-group { display: contents; }
  .ps-chip { padding: 4px 11px; font-size: 11px; border-radius: 20px; border: 1px solid var(--border); background: transparent; cursor: pointer; color: var(--text-2); font-family: var(--font-mono); }
  .ps-chip:hover { background: var(--surface-2); }
  .ps-chip.active { background: var(--text); color: var(--bg); border-color: var(--text); }
  .ps-chip[data-sev] { font-weight: 600; }
  .ps-chip[data-sev="crit"] { color: var(--crit-fg); background: var(--crit-bg); border-color: var(--crit-bd); }
  .ps-chip[data-sev="warn"] { color: var(--warn-fg); background: var(--warn-bg); border-color: var(--warn-bd); }
  .ps-chip[data-sev="info"] { color: var(--info-fg); background: var(--info-bg); border-color: var(--info-bd); }
  .ps-chip[data-sev].active { box-shadow: inset 0 0 0 1px currentColor; }
  .ps-findings-count { font-family: var(--font-mono); font-size: 11px; color: var(--text-3); margin-left: 6px; }

  /* -------- lists / rows -------- */
  .ps-list { display: flex; flex-direction: column; }
  .ps-row { display: flex; flex-direction: column; gap: 7px; padding: 12px 14px; border-bottom: 1px solid var(--border); cursor: pointer; transition: background .12s; }
  .ps-row:hover { background: var(--surface-2); }
  .ps-row.selected { background: var(--surface-2); box-shadow: inset 2px 0 0 var(--brand); }
  .ps-row:last-child { border-bottom-color: transparent; }
  .ps-sev { padding: 2px 6px; border-radius: 4px; font-size: 11px; }
  .ps-badge-estimated, .ps-badge-measured { display: inline-block; padding: 2px 7px; border-radius: 4px; font-size: 11px; font-family: var(--font-mono); font-weight: 600; }
  .ps-badge-estimated { color: var(--warn-fg); background: var(--warn-bg); border: 1px solid var(--warn-bd); }
  .ps-badge-measured { color: var(--ok-fg); background: var(--ok-bg); border: 1px solid var(--ok-bd); }
  .ps-scoring-bandeau { display: flex; align-items: center; gap: 8px; font-size: 12px; flex-wrap: wrap; }
  .ps-scoring-label { color: var(--text-2); font-weight: 500; }
  .ps-scoring-chip { display: inline-block; padding: 3px 10px; border-radius: 20px; font-size: 11px; font-weight: 500; white-space: nowrap; font-family: var(--font-mono); }
  .ps-scoring-chip-neutral { background: var(--surface-2); color: var(--text-2); }
  .ps-scoring-chip-warning { background: var(--warn-bg); color: var(--warn-fg); }
  .ps-scoring-chip-accent { background: var(--accent-bg); color: var(--brand-text); }
  .ps-fin-main { min-width: 0; }
  .ps-fin-type { font-weight: 600; font-size: 12.5px; color: var(--text); }
  .ps-fin-service { color: var(--text-3); font-weight: 400; font-size: 11px; font-family: var(--font-mono); }
  .ps-fin-detail { font-size: 11px; color: var(--text-2); font-family: var(--font-mono); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
  .ps-fin-right { font-size: 11px; color: var(--text-2); font-family: var(--font-mono); text-align: right; white-space: nowrap; }
  .ps-fin-right-sub { color: var(--text-3); }
  .ps-fin-topline { display: flex; align-items: center; gap: 8px; }
  .ps-fin-metric { margin-left: auto; }
  .ps-fin-sub { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
  .ps-sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; }
  .ps-detail-titlewrap { flex: 1; min-width: 0; }

  /* -------- findings master / detail -------- */
  .ps-triage { display: grid; grid-template-columns: 340px 1fr; gap: 14px; align-items: start; }
  .ps-detail { border: 1px solid var(--border); border-radius: var(--r); background: var(--surface); padding: 20px 22px; display: flex; flex-direction: column; gap: 17px; }
  /* Space the detail sections evenly (title -> meta -> template, breadcrumb -> tree -> pg_stat -> fix). */
  #explain-detail-head, #explain-content { display: flex; flex-direction: column; gap: 18px; }
  .ps-detail-empty { color: var(--text-3); font-size: 13px; }
  .ps-detail-head { display: flex; align-items: flex-start; gap: 12px; }
  .ps-detail-h2 { margin: 0; font-size: 18px; font-weight: 600; letter-spacing: -.3px; color: var(--text); }
  .ps-detail-sub { margin: 4px 0 0; font-size: 12.5px; color: var(--text-2); }
  .ps-meta-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px; }
  .ps-meta-cell { border: 1px solid var(--border); border-radius: var(--r-sm); background: var(--surface-2); padding: 11px 12px; }
  .ps-meta-cell-label { font-family: var(--font-mono); font-size: 11px; letter-spacing: .6px; text-transform: uppercase; color: var(--text-3); }
  .ps-meta-cell-value { font-size: 12.5px; font-weight: 500; color: var(--text); margin-top: 5px; }
  .ps-meta-cell-value.mono { font-family: var(--font-mono); font-size: 11.5px; font-weight: 400; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
  .ps-meta-cell-value.brand { color: var(--brand-text); }
  .ps-eyebrow { font-family: var(--font-mono); font-size: 11px; letter-spacing: 1.1px; text-transform: uppercase; color: var(--text-3); }
  .ps-eyebrow.brand { color: var(--brand-text); }
  .ps-codeblock { display: block; font-family: var(--font-mono); font-size: 12px; color: var(--text); background: var(--surface-3); border: 1px solid var(--border); border-radius: var(--r-sm); padding: 12px 14px; overflow: auto; white-space: pre; }
  .ps-section { display: flex; flex-direction: column; gap: 8px; }

  /* -------- explain tree -------- */
  .ps-tree-header { font-size: 11px; color: var(--text-2); padding: 10px 12px; background: var(--surface-2); border: 1px solid var(--border); border-radius: var(--r-sm); font-family: var(--font-mono); word-break: break-all; }
  .ps-tree { border: 1px solid var(--border); border-radius: var(--r-sm); background: var(--surface-2); padding: 12px 14px; display: flex; flex-direction: column; gap: 8px; }
  .ps-span { display: flex; align-items: center; gap: 9px; padding: 1px 0; border-radius: 4px; }
  .ps-span.dim { color: var(--text-3); }
  .ps-span.hilite { background: var(--crit-bg); }
  .ps-span-text { font-family: var(--font-mono); font-size: 11.5px; color: var(--text); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
  .ps-span-flag { padding: 1px 6px; border-radius: 4px; font-size: 11px; }
  .ps-span-dur { font-family: var(--font-mono); font-size: 11px; color: var(--text-3); margin-left: auto; white-space: nowrap; }
  .ps-span-count { flex: none; font-family: var(--font-mono); font-size: 10.5px; padding: 0 6px; border-radius: 5px; background: var(--surface-2); color: var(--text-2); }
  .ps-span-find { color: var(--crit-fg); font-weight: 600; }
  .ps-span.ps-span-pgstat-link { cursor: pointer; }
  .ps-span.ps-span-pgstat-link:hover .ps-span-text { text-decoration: underline; }

  /* -------- suggested fix (green callout) -------- */
  .ps-fix { border: 1px solid var(--ok-bd); border-radius: var(--r-sm); background: var(--ok-bg); padding: 12px 14px; display: flex; flex-direction: column; gap: 9px; }
  /* pg_stat cross-ref (left) + suggested fix (right), side by side like the model; collapses to one column when only one is present. */
  .ps-detail-cols { display: grid; grid-template-columns: 1fr 1fr; gap: 18px; align-items: start; }
  .ps-detail-cols.single { grid-template-columns: 1fr; }
  .ps-detail-foot { font-family: var(--font-mono); font-size: 11px; color: var(--text-3); border-top: 1px solid var(--border); padding-top: 13px; }
  .ps-pgstat-xref { display: flex; align-items: center; justify-content: space-between; gap: 14px; padding: 9px 12px; background: var(--surface-2); border: 1px solid var(--border); border-radius: var(--r-sm); font-family: var(--font-mono); font-size: 12px; }
  .ps-pgstat-xref-stat { color: var(--text-3); white-space: nowrap; }
  .ps-fix-prose { font-size: 12.5px; color: var(--text); line-height: 1.55; }
  .ps-fix-code { font-family: var(--font-mono); font-size: 11.5px; color: var(--text); background: var(--surface); border: 1px solid var(--ok-bd); border-radius: 6px; padding: 9px 11px; overflow: auto; white-space: pre; }
  .ps-fix-alt { display: block; font-size: 12px; color: var(--text); line-height: 1.55; padding-top: 9px; border-top: 1px solid var(--ok-bd); }
  .ps-fix-link { align-self: flex-start; font-family: var(--font-mono); font-size: 11px; color: var(--brand-text); text-decoration: none; border-bottom: 1px solid var(--brand-text); }
  .ps-source-link { color: var(--brand-text); text-decoration: underline; }

  /* prose inline-code chip emitted by proseHl */
  .ps-code-inline { font-family: var(--font-mono); font-size: .9em; background: var(--surface-3); border: 1px solid var(--border); border-radius: 4px; padding: 0 5px; color: var(--text); }
  /* syntax-highlight token weight (color set inline by the highlighter via data-hl) */
  .ps-hl-kw { font-weight: 600; }

  /* -------- banner / empty / drill -------- */
  .ps-banner { background: var(--info-bg); border: 1px solid var(--info-bd); border-radius: var(--r-sm); padding: 8px 12px; font-size: 11px; color: var(--info-fg); }
  .ps-empty { padding: 30px; text-align: center; color: var(--text-2); font-size: 13px; background: var(--surface); border: 1px solid var(--border); border-radius: var(--r); }
  .ps-drill { background: var(--info-bg); border: 1px solid var(--info-bd); border-radius: var(--r-sm); padding: 10px 12px; font-size: 12px; color: var(--info-fg); }
  .ps-drill-label { font-size: 10px; color: var(--info-fg); margin-bottom: 4px; opacity: .8; }
  .ps-drill-link { color: var(--info-fg); }
  .ps-drill-clear { color: var(--info-fg); text-decoration: underline; cursor: pointer; margin-left: 8px; }

  /* -------- tables -------- */
  .ps-table { width: 100%; font-size: 11.5px; font-family: var(--font-mono); border-collapse: collapse; }
  .ps-table th { text-align: left; font-weight: 600; padding: 11px 12px; border-bottom: 1px solid var(--border); color: var(--text-3); font-size: 11px; letter-spacing: .6px; text-transform: uppercase; font-family: var(--font-mono); }
  .ps-table td { padding: 12px; border-bottom: 1px solid var(--border); vertical-align: top; color: var(--text-2); }
  /* Diff delta tone (override the base td color) + emphasized "after" value. */
  .ps-table td[data-tone="crit"] { color: var(--crit-fg); }
  .ps-table td[data-tone="ok"] { color: var(--ok-fg); }
  .ps-table td.ps-diff-after { color: var(--text); font-weight: 600; }
  .ps-table tr:last-child td { border-bottom-color: transparent; }
  #pgstat-body tr.hilite { background: var(--crit-bg); }
  #pgstat-body tr.hilite td:first-child { color: var(--crit-fg); font-weight: 600; }
  /* pg_stat controls row: "rank by" label + ranking chips + filter box */
  .ps-pgstat-controls { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
  .ps-rankby-label { font-family: var(--font-mono); font-size: 11px; color: var(--text-3); margin-right: 2px; }
  .ps-pgstat-filter { margin-left: auto; height: 32px; flex: 0 1 260px; max-width: 260px; min-width: 180px; }

  /* -------- footer -------- */
  .ps-footer { margin-top: auto; min-height: 62px; border-top: 1px solid var(--border); display: flex; align-items: center; gap: 10px; flex-wrap: wrap; font-family: var(--font-mono); font-size: 11px; color: var(--text-3); }
  .ps-credit { margin-left: auto; }
  .ps-credit a, .ps-footer a { color: var(--brand-text); text-decoration: none; border-bottom: 1px solid var(--brand-text); }
  .ps-credit a:hover, .ps-footer a:hover { color: var(--text); }
  .ps-kbd { font-family: var(--font-mono); font-size: 11px; border: 1px solid var(--border); border-radius: 4px; padding: 1px 6px; color: var(--text-3); }

  /* -------- diff / section headers -------- */
  .ps-diff-section { display: flex; flex-direction: column; }
  .ps-diff-section-header { font-size: 13px; font-weight: 600; padding: 13px 18px; border-bottom: 1px solid var(--border); color: var(--text); }
  .ps-diff-section-header.red { color: var(--crit-fg); }
  .ps-diff-section-header.green { color: var(--ok-fg); }
  .ps-quality-gate { display: flex; flex-direction: column; gap: 0; }
  .ps-section-title { font-size: 13px; font-weight: 600; margin: 0; color: var(--text); }
  .ps-panel-toolbar { display: flex; justify-content: flex-end; align-items: center; gap: 8px; }
  .ps-export-btn, .ps-copy-link-btn { padding: 6px 12px; font-size: 11.5px; border-radius: var(--r-sm); border: 1px solid var(--border); background: transparent; cursor: pointer; color: var(--text-2); font-family: inherit; }
  .ps-export-btn:hover, .ps-copy-link-btn:hover { border-color: var(--border-2); color: var(--text); }
  .ps-correlation-clickable { cursor: pointer; }
  .ps-correlation-clickable:hover { background: var(--surface-2); }
  .ps-show-more { padding: 12px 14px; font-size: 11px; border: 0; border-top: 1px solid var(--border); background: transparent; color: var(--brand-text); cursor: pointer; font-family: var(--font-mono); width: 100%; text-align: center; }
  .ps-show-more:hover { background: var(--surface-2); }

  @keyframes ps-pulse { 0%, 100% { opacity: 1; } 50% { opacity: .55; } }

  /* -------- modals (native <dialog>) -------- */
  dialog.ps-modal { position: fixed; inset: 0; margin: auto; max-width: 460px; width: calc(100% - 40px); height: fit-content; max-height: calc(100vh - 40px); overflow-y: auto; background: var(--surface); color: var(--text); border-radius: var(--r); border: 1px solid var(--border-2); padding: 22px 24px; box-shadow: 0 24px 70px rgba(0,0,0,.45); }
  dialog.ps-modal::backdrop { background: rgba(0,0,0,.55); }
  dialog.ps-modal h2 { margin: 0 0 16px 0; font-size: 15px; font-weight: 600; }
  .ps-modal-close { position: absolute; top: 14px; right: 16px; background: transparent; border: none; color: var(--text-2); font-family: var(--font-mono); font-size: 12px; cursor: pointer; line-height: 1; padding: 4px 8px; }
  .ps-modal-close:hover { color: var(--text); }
  dialog.ps-modal table { width: 100%; border-collapse: collapse; }
  dialog.ps-modal th { text-align: left; padding: 4px 6px; font-size: 11px; font-weight: 600; color: var(--text-3); border-bottom: 1px solid var(--border); font-family: var(--font-mono); }
  dialog.ps-modal th:first-child { width: 110px; }
  dialog.ps-modal td { padding: 6px 6px; font-size: 12.5px; vertical-align: top; color: var(--text-2); }
  dialog.ps-modal td:first-child { width: 110px; white-space: nowrap; font-family: var(--font-mono); color: var(--text); }
  dialog.ps-modal label { display: block; font-size: 11px; color: var(--text-3); margin: 12px 0 4px 0; font-family: var(--font-mono); text-transform: uppercase; letter-spacing: .6px; }
  dialog.ps-modal input[type="password"], dialog.ps-modal input[type="text"], dialog.ps-modal textarea, dialog.ps-modal select { width: 100%; box-sizing: border-box; padding: 8px 11px; font-size: 12.5px; font-family: inherit; background: var(--surface-2); border: 1px solid var(--border); border-radius: var(--r-sm); color: var(--text); }
  dialog.ps-modal textarea { min-height: 70px; resize: vertical; }
  dialog.ps-modal .ps-modal-actions { display: flex; justify-content: flex-end; gap: 10px; margin-top: 16px; }
  dialog.ps-modal .ps-modal-btn { padding: 8px 15px; font-size: 12.5px; border-radius: var(--r-sm); border: 1px solid var(--border); background: transparent; color: var(--text-2); cursor: pointer; font-family: inherit; }
  dialog.ps-modal .ps-modal-btn:hover { border-color: var(--border-2); color: var(--text); }
  dialog.ps-modal .ps-modal-btn.primary { background: var(--ok-bg); color: var(--ok-fg); border: 1px solid var(--ok-bd); font-weight: 600; }
  dialog.ps-modal .ps-modal-error { display: none; margin-top: 10px; padding: 8px 10px; font-size: 11px; background: var(--crit-bg); color: var(--crit-fg); border-radius: var(--r-sm); }

  /* -------- live mode (since 0.5.23) -------- */
  .ps-daemon-status { display: none; align-items: center; gap: 6px; font-size: 11px; color: var(--text-2); }
  body.ps-live .ps-daemon-status { display: inline-flex; }
  .ps-daemon-dot { width: 8px; height: 8px; border-radius: 50%; background: var(--text-3); display: inline-block; }
  .ps-daemon-dot.connected { background: #2ea043; }
  .ps-daemon-dot.disconnected { background: #cf222e; }
  .ps-daemon-dot.unauthorized { background: #d4a72c; }
  .ps-refresh-btn { display: none; padding: 7px 11px; font-size: 12px; border-radius: var(--r-sm); border: 1px solid var(--border); background: transparent; color: var(--text-2); cursor: pointer; font-family: inherit; }
  body.ps-live .ps-refresh-btn { display: inline-block; }
  body.ps-live .ps-refresh-btn[hidden] { display: none; }
  .ps-refresh-btn:hover { border-color: var(--border-2); color: var(--text); }
  .ps-refresh-btn:disabled { cursor: not-allowed; opacity: 0.6; }
  .ps-fin-actions { display: none; margin-left: 8px; }
  body.ps-live .ps-fin-actions { display: inline-flex; gap: 6px; }
  .ps-fin-action-btn { padding: 5px 11px; font-size: 11px; border-radius: var(--r-sm); border: 1px solid var(--ok-bd); background: transparent; color: var(--ok-fg); cursor: pointer; font-family: inherit; }
  .ps-fin-action-btn:hover { background: var(--ok-bg); }
  .ps-fin-action-btn.revoke { border-color: var(--border); color: var(--text-2); }
  .ps-fin-action-btn.revoke:hover { background: var(--surface-2); }
  .ps-fin-action-btn:disabled { cursor: not-allowed; opacity: 0.5; }
  .ps-include-acked-wrap { display: none; align-items: center; gap: 6px; font-size: 11.5px; color: var(--text-2); margin-left: auto; cursor: pointer; }
  body.ps-live .ps-include-acked-wrap { display: inline-flex; }
  .ps-acks-footer { margin-top: 10px; font-size: 11px; color: var(--text-3); }

  /* -------- toast -------- */
  .ps-toast { position: fixed; bottom: 20px; right: 20px; padding: 10px 16px; font-size: 12px; background: var(--surface); color: var(--text); border: 1px solid var(--border); border-radius: var(--r-sm); box-shadow: 0 4px 16px rgba(0,0,0,0.3); z-index: 9999; max-width: 380px; }
  .ps-toast.error { border-color: var(--crit-bd); background: var(--crit-bg); color: var(--crit-fg); }
  .ps-toast.success { border-color: var(--ok-bd); background: var(--ok-bg); color: var(--ok-fg); }
  /* Narrow viewports (small windows, embedded iframes): give the content room
     by narrowing the sidebar, stacking the two-column blocks, and letting the
     search box shrink. */
  @media (max-width: 920px) {
    .ps-shell { grid-template-columns: 200px 1fr; }
    .ps-hero { grid-template-columns: 1fr; }
    .ps-hero-left { border-right: 0; border-bottom: 1px solid var(--border); }
    .ps-hero-rules { grid-template-columns: 1fr; }
    .ps-metrics { grid-template-columns: repeat(2, 1fr); }
    .ps-overview-cols, .ps-diff-cols, .ps-triage { grid-template-columns: 1fr; }
    .ps-meta-grid { grid-template-columns: repeat(2, 1fr); }
    .ps-search-box { flex: 1 1 auto; min-width: 0; }
    .ps-footer { min-height: 0; padding: 18px 0 14px; }
  }
</style>
</head>
<body>
<div class="ps-shell" id="ps-shell">
  <aside class="ps-sidebar">
    <div class="ps-sidebar-sticky">
    <div class="ps-brand-block">
      <a class="ps-brand" href="https://perf-sentinel.dev/" target="_blank" rel="noopener noreferrer" aria-label="perf-sentinel, perf-sentinel.dev">{{BRAND_LOGO}}</a>
      <span class="ps-brand-eyebrow">HTML REPORT</span>
    </div>
    <div class="ps-nav" id="tabs" role="tablist" aria-label="Dashboard sections" aria-orientation="vertical">
      <div class="ps-nav-eyebrow">// sections</div>
    </div>
    <div class="ps-sidebar-foot">
      <div class="ps-sidebar-foot-status">
        <span class="ps-sidebar-foot-dot" id="ps-sidebar-dot"></span>
        <span class="ps-sidebar-foot-text" id="ps-sidebar-context"></span>
      </div>
      <div class="ps-sidebar-foot-version" id="ps-sidebar-version"></div>
    </div>
    </div>
  </aside>

  <main class="ps-main">
    <header class="ps-topbar">
      <div class="ps-topbar-title">
        <span class="ps-topbar-eyebrow" id="topbar-eyebrow"></span>
        <h1 class="ps-topbar-h1" id="topbar-h1">Overview</h1>
      </div>
      <div class="ps-topbar-actions" style="display: flex; align-items: center; gap: 8px; flex-wrap: nowrap;">
        <div class="ps-search-box" id="topbar-search-box">
          <span class="ps-search-glyph"></span>
          <input type="search" class="ps-search" id="topbar-search" placeholder="Search findings, templates, endpoints…" aria-label="Search findings, templates, endpoints" />
          <span class="ps-search-kbd">⌘K</span>
        </div>
        <span id="topbar-gate"></span>
        <output class="ps-daemon-status" id="ps-daemon-status" aria-live="polite">
          <span class="ps-daemon-dot" id="ps-daemon-dot"></span>
          <span id="ps-daemon-status-text">Connecting...</span>
        </output>
        <button class="ps-refresh-btn" id="ps-refresh-btn" type="button" aria-label="Refresh daemon data">Refresh</button>
        <button class="ps-refresh-btn" id="ps-logout-btn" type="button" aria-label="Forget key for this tab (clears the daemon API key from session storage)" hidden>Forget key</button>
        <button class="ps-theme-toggle" id="theme-toggle" type="button">Toggle theme</button>
      </div>
    </header>

    <div class="ps-content">

  <div id="panel-overview" role="tabpanel" aria-labelledby="tab-overview" class="ps-panel ps-panel-wide" style="display: none;">
    <div id="overview-hero"></div>
    <div class="ps-metrics" id="findings-metrics"></div>
    <div id="overview-body"></div>
  </div>

  <div id="panel-findings" role="tabpanel" aria-labelledby="tab-findings" class="ps-panel">
    <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-filters" id="findings-filters"></div>
    <div class="ps-panel-toolbar">
      <label class="ps-include-acked-wrap" id="findings-include-acked-wrap">
        <input type="checkbox" id="findings-include-acked" />
        <span>Show acknowledged</span>
      </label>
      <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-triage">
      <div class="ps-card">
        <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 class="ps-detail" id="findings-detail">
        <div class="ps-detail-empty" id="explain-empty">Select a finding to view its trace tree and suggested fix.</div>
        <div id="explain-detail-head"></div>
        <div id="explain-content" style="display: none;">
          <div class="ps-tree-header" id="explain-breadcrumb"></div>
          <div class="ps-section">
            <span class="ps-eyebrow">// explain &middot; trace tree</span>
            <div class="ps-tree" id="explain-tree"></div>
          </div>
          <div class="ps-detail-cols" id="explain-cols">
            <div class="ps-section" id="explain-pgstat" style="display: none;"></div>
            <div class="ps-fix" id="explain-fix" style="display: none;"></div>
          </div>
          <div class="ps-detail-foot" id="explain-foot" style="display: none;"></div>
        </div>
        <div class="ps-detail-empty" id="explain-not-embedded" style="display: none;"></div>
      </div>
    </div>
  </div>

  <div id="panel-pgstat" role="tabpanel" aria-labelledby="tab-pgstat" class="ps-panel ps-panel-narrow" 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-pgstat-controls">
      <span class="ps-rankby-label">rank by</span>
      <div class="ps-filters" id="pgstat-rankings"></div>
      <div class="ps-search-box ps-pgstat-filter">
        <span class="ps-search-glyph"></span>
        <input type="search" class="ps-search" id="pgstat-search" placeholder="Filter by SQL template…" aria-label="Filter pg_stat rows" />
      </div>
      <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>
    <div class="ps-card">
      <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>
    <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" class="ps-panel ps-panel-narrow" 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-cols">
      <div class="ps-card 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-card 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>
    <div class="ps-card 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>Endpoint</th><th>Before</th><th>After</th></tr></thead>
        <tbody id="diff-sev-body"></tbody>
      </table>
    </div>
    <div class="ps-card 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</th><th>After</th><th>Δ</th></tr></thead>
        <tbody id="diff-endp-body"></tbody>
      </table>
    </div>
  </div>

  <div id="panel-correlations" role="tabpanel" aria-labelledby="tab-correlations" class="ps-panel ps-panel-narrow" 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" class="ps-panel ps-panel-narrow" style="display: none;">
    <div class="ps-metrics ps-metrics-3" id="green-metrics"></div>
    <div id="green-formula" class="ps-formula-bandeau" style="display: none;"></div>
    <div id="green-scoring-config" class="ps-scoring-bandeau" style="display: none;" aria-label="Carbon scoring configuration"></div>
    <div class="ps-tree-header" id="green-regions-header"></div>
    <div class="ps-card" id="green-regions-card" style="display: none;">
      <table class="ps-table" id="green-regions-table">
        <thead><tr><th>Region</th><th>Intensity (gCO2/kWh)</th><th>I/O ops</th><th>CO2</th><th>Source</th><th>Estimated</th></tr></thead>
        <tbody id="green-regions-body"></tbody>
      </table>
    </div>
    <div class="ps-empty" id="green-regions-empty" style="display: none;">No region breakdown available.</div>
  </div>

  <div id="panel-acknowledgments" role="tabpanel" aria-labelledby="tab-acknowledgments" class="ps-panel ps-panel-narrow" style="display: none;">
    <div class="ps-card" id="acks-card" style="display: none;">
      <table class="ps-table" id="acks-table">
        <thead><tr><th>Signature</th><th style="width: 140px;">By</th><th>Reason</th><th style="width: 120px;">Expires</th><th style="width: 90px;"></th></tr></thead>
        <tbody id="acks-body"></tbody>
      </table>
    </div>
    <div class="ps-empty" id="acks-empty" style="display: none;">No daemon acknowledgments active.</div>
    <div class="ps-acks-footer" id="acks-footer"></div>
  </div>

      <div style="height: 28px; flex: none;"></div>
      <footer class="ps-footer">
        <span class="ps-kbd">j/k</span> navigate
        <span class="ps-kbd">enter</span> open
        <span class="ps-kbd">/</span> search
        <span class="ps-kbd">esc</span> back
        <button type="button" class="ps-kbd" id="footer-shortcuts" style="cursor: pointer; background: transparent;">?</button> shortcuts
        <span class="ps-credit">Powered by <a href="https://perf-sentinel.dev/" target="_blank" rel="noopener noreferrer">perf-sentinel</a> &middot; eco-designed report &middot; logo by <a href="https://www.linkedin.com/in/gwendoline-meignen-b0224873/" target="_blank" rel="noopener noreferrer">Gwendoline Meignen</a></span>
      </footer>

    </div>
  </main>
</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>

<dialog id="auth-modal" class="ps-modal" aria-labelledby="auth-modal-title">
  <button type="button" class="ps-modal-close" id="auth-modal-close" aria-label="Close">x</button>
  <h2 id="auth-modal-title">Daemon authentication required</h2>
  <p id="auth-modal-hint" style="margin: 0 0 8px 0; font-size: 11px; color: var(--color-text-warning);">The daemon rejected the request with 401. Enter the API key to retry. The key is held in browser memory only for this tab session and cleared when the tab closes.</p>
  <form id="auth-modal-form">
    <label for="auth-modal-key">API key</label>
    <input type="password" id="auth-modal-key" autocomplete="off" />
    <div class="ps-modal-error" id="auth-modal-error" role="alert"></div>
    <div class="ps-modal-actions">
      <button type="button" class="ps-modal-btn" id="auth-modal-cancel">Cancel</button>
      <button type="submit" class="ps-modal-btn primary" id="auth-modal-submit">Submit</button>
    </div>
  </form>
</dialog>

<dialog id="ack-modal" class="ps-modal" aria-labelledby="ack-modal-title">
  <button type="button" class="ps-modal-close" id="ack-modal-close" aria-label="Close">x</button>
  <h2 id="ack-modal-title">Acknowledge finding</h2>
  <form id="ack-modal-form">
    <label for="ack-modal-sig">Signature</label>
    <input type="text" id="ack-modal-sig" readonly />
    <label for="ack-modal-reason">Reason</label>
    <textarea id="ack-modal-reason" required></textarea>
    <label for="ack-modal-expires">Expires</label>
    <select id="ack-modal-expires">
      <option value="">Never (permanent)</option>
      <option value="24h">24 hours</option>
      <option value="7d" selected>7 days</option>
      <option value="30d">30 days</option>
    </select>
    <label for="ack-modal-by">Acknowledged by</label>
    <input type="text" id="ack-modal-by" placeholder="optional" />
    <div class="ps-modal-error" id="ack-modal-error" role="alert"></div>
    <div class="ps-modal-actions">
      <button type="button" class="ps-modal-btn" id="ack-modal-cancel">Cancel</button>
      <button type="submit" class="ps-modal-btn primary" id="ack-modal-submit">Acknowledge</button>
    </div>
  </form>
</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";
  }
  // Build an inline SVG (CSP-safe, no innerHTML) from a list of child
  // {tag, attrs}. Stroke follows `currentColor` so CSS colors the icon.
  function themeSvg(children, accent) {
    var NS = "http://www.w3.org/2000/svg";
    var svg = document.createElementNS(NS, "svg");
    var base = { width: "13", height: "13", viewBox: "0 0 24 24", fill: "none",
      stroke: "currentColor", "stroke-width": "2.2", "stroke-linecap": "round",
      "stroke-linejoin": "round", "class": accent ? "ps-th-svg accent" : "ps-th-svg" };
    setAttrs(svg, base);
    children.forEach(function (c) {
      var node = document.createElementNS(NS, c.tag);
      setAttrs(node, c.attrs);
      svg.appendChild(node);
    });
    return svg;
  }
  // Sun (light) and moon (dark) match the website; auto is a half-filled
  // circle (◐) drawn as SVG so all three align the same way (the ◐ text
  // glyph falls back to a different font and sits off-center).
  function themeIcon(mode) {
    if (mode === "light") {
      return themeSvg([
        { tag: "circle", attrs: { cx: "12", cy: "12", r: "4.2" } },
        { tag: "path", attrs: { d: "M12 2.6v2.1M12 19.3v2.1M4.5 4.5l1.5 1.5M18 18l1.5 1.5M2.6 12h2.1M19.3 12h2.1M4.5 19.5l1.5-1.5M18 6l1.5-1.5" } }
      ], true);
    }
    if (mode === "dark") {
      return themeSvg([{ tag: "path", attrs: { d: "M21 12.8A9 9 0 1 1 11.2 3 7 7 0 0 0 21 12.8z" } }], true);
    }
    return themeSvg([
      { tag: "circle", attrs: { cx: "12", cy: "12", r: "9" } },
      { tag: "path", attrs: { d: "M12 3 A9 9 0 0 0 12 21 Z", fill: "currentColor", stroke: "none" } }
    ], false);
  }
  function applyTheme(mode) {
    document.documentElement.dataset.theme = resolveThemeColor(mode);
    var btn = document.getElementById("theme-toggle");
    if (btn) {
      btn.textContent = "";
      btn.appendChild(themeIcon(mode));
      btn.appendChild(el("span", null, mode.charAt(0).toUpperCase() + mode.slice(1)));
    }
  }
  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 setAttrs(node, attrs) { Object.keys(attrs).forEach(function (k) { node.setAttribute(k, String(attrs[k])); }); }
  function safeHttpsHref(url) {
    if (typeof url !== "string") return null;
    if (!url.startsWith("https://")) return null;
    if (/[\x00-\x1f\x7f-\x9f]/.test(url)) 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";
  }
  // Thousands separators (comma, en-US) on the integer part, decimals kept:
  // 55500 -> "55,500", 1240.5 -> "1,240.5", 320 -> "320".
  function fmtNum(value) {
    var parts = String(value).split(".");
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    return parts.join(".");
  }
  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) + "%";
  }

  // -------- syntax highlighting (textContent-only span builders) --------
  // Ported from the design prototype's sqlHl/proseHl. Builds colored
  // <span> nodes via el() (textContent each), never innerHTML, so the
  // CSP + no_forbidden_apis_in_template invariants hold. Token colors map
  // to the severity/info/ok/brand CSS variables. The tokenizers are pure
  // regex scans (first-match-wins) and cannot throw on odd input; the
  // outer guard falls back to a plain text node just in case.
  function buildKwSet(words) {
    var set = Object.create(null);
    words.forEach(function (w) { set[w] = true; });
    return set;
  }
  var SQL_KW = buildKwSet([
    "SELECT","FROM","WHERE","INSERT","INTO","VALUES","UPDATE","SET","DELETE","AND","OR","ON",
    "JOIN","LEFT","RIGHT","INNER","OUTER","GROUP","BY","ORDER","HAVING","LIMIT","OFFSET","LIKE",
    "ILIKE","ANY","ALL","AS","NULL","NOT","IN","IS","DISTINCT","EXISTS","BETWEEN","ASC","DESC",
    "RETURNING","CREATE","INDEX","USING","TABLE","ALTER","ADD","CONSTRAINT"
  ]);
  var GENERIC_KW = buildKwSet([
    "fn","let","mut","pub","use","impl","struct","enum","trait","match","if","else","for","while",
    "loop","return","async","await","move","self","Self","as","where","const","static","ref","dyn",
    "in","break","continue","unsafe","crate","mod","type",
    "func","package","import","var","interface","map","chan","go","defer","range","select","case",
    "default","switch","nil",
    "function","new","class","extends","implements","export","from","of","typeof","instanceof",
    "yield","try","catch","finally","throw","throws","this","null","true","false","void","undefined",
    "def","elif","with","except","raise","lambda","not","and","or","is","None","True","False","pass",
    "global","del","assert","print",
    "public","private","protected","final","abstract","sealed","record","super","synchronized",
    "readonly","internal","base","volatile","transient","namespace","using","override","virtual",
    "out","params","foreach",
    "GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS","TRACE","CONNECT"
  ]);
  function makeTokenSpan(text, color, bold) {
    var span = el("span", null, text);
    if (color) span.style.color = color;
    if (bold) span.style.fontWeight = "600";
    return span;
  }
  // Small inline-SVG icon (stroke = currentColor, so the parent's color
  // applies). Used for the gate-rule check/cross so they center exactly,
  // rather than relying on text-glyph metrics.
  function iconSvg(size, d) {
    var NS = "http://www.w3.org/2000/svg";
    var svg = document.createElementNS(NS, "svg");
    var attrs = { width: String(size), height: String(size), viewBox: "0 0 24 24",
      fill: "none", stroke: "currentColor", "stroke-width": "3",
      "stroke-linecap": "round", "stroke-linejoin": "round", display: "block" };
    setAttrs(svg, attrs);
    var path = document.createElementNS(NS, "path");
    path.setAttribute("d", d);
    svg.appendChild(path);
    return svg;
  }
  function sqlHlFragment(frag, sql) {
    var re = /(\s+)|('(?:[^']|'')*')|(\$\d+)|(\b\d+\b)|([A-Za-z_][A-Za-z0-9_]*)|([(),.*=<>!|+\/-]+)|(\S)/g;
    var toks = [], m;
    while ((m = re.exec(sql))) {
      if (m[1]) toks.push({ t: "ws", v: m[1] });
      else if (m[2]) toks.push({ t: "str", v: m[2] });
      else if (m[3]) toks.push({ t: "param", v: m[3] });
      else if (m[4]) toks.push({ t: "num", v: m[4] });
      else if (m[5]) toks.push({ t: "ident", v: m[5] });
      else if (m[6]) toks.push({ t: "op", v: m[6] });
      else toks.push({ t: "other", v: m[0] });
    }
    toks.forEach(function (tk, i) {
      var color = null, bold = false;
      if (tk.t === "ident") {
        if (SQL_KW[tk.v.toUpperCase()]) { color = "var(--info-fg)"; bold = true; }
        else {
          var j = i + 1;
          while (toks[j] && toks[j].t === "ws") j++;
          if (toks[j] && toks[j].t === "op" && toks[j].v[0] === "(") color = "var(--warn-fg)";
        }
      } else if (tk.t === "str") color = "var(--ok-fg)";
      else if (tk.t === "param") color = "var(--warn-fg)";
      else if (tk.t === "num") color = "var(--ok-fg)";
      else if (tk.t === "op") color = "var(--text-3)";
      if (color) frag.appendChild(makeTokenSpan(tk.v, color, bold));
      else frag.appendChild(document.createTextNode(tk.v));
    });
  }
  function genericHlFragment(frag, src) {
    var gre = /(\s+)|(\/\/[^\n]*|#[^\n]*)|(\/\*[\s\S]*?\*\/)|("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`)|(@[A-Za-z_][A-Za-z0-9_.]*)|(\b\d+(?:\.\d+)?\b)|([A-Za-z_][A-Za-z0-9_]*!?)|(::|->|=>|[(){}\[\].,:;=<>!&|+\-*\/%?@]+)|(\S)/g;
    var gtk = [], gm;
    while ((gm = gre.exec(src))) {
      if (gm[1]) gtk.push({ t: "ws", v: gm[1] });
      else if (gm[2] || gm[3]) gtk.push({ t: "cmt", v: gm[2] || gm[3] });
      else if (gm[4]) gtk.push({ t: "str", v: gm[4] });
      else if (gm[5]) gtk.push({ t: "ann", v: gm[5] });
      else if (gm[6]) gtk.push({ t: "num", v: gm[6] });
      else if (gm[7]) gtk.push({ t: "id", v: gm[7] });
      else if (gm[8]) gtk.push({ t: "op", v: gm[8] });
      else gtk.push({ t: "o", v: gm[0] });
    }
    gtk.forEach(function (x, i) {
      var color = null, bold = false;
      if (x.t === "cmt") color = "var(--text-3)";
      else if (x.t === "ann") color = "var(--warn-fg)";
      else if (x.t === "str") color = "var(--ok-fg)";
      else if (x.t === "num") color = "var(--ok-fg)";
      else if (x.t === "id") {
        if (GENERIC_KW[x.v]) { color = "var(--info-fg)"; bold = true; } // keyword
        else {
          var j = i + 1;
          while (gtk[j] && gtk[j].t === "ws") j++;
          var nx = gtk[j] && gtk[j].t === "op" ? gtk[j].v : "";
          // IDE-style: functions, macros and snake_case method/property names
          // are amber; PascalCase types are teal; plain identifiers and module
          // path segments keep the default text color.
          if (x.v.slice(-1) === "!" || nx[0] === "(" || /_/.test(x.v)) color = "var(--warn-fg)";
          else if (/^[A-Z].*[a-z]/.test(x.v)) color = "var(--brand-text)";
        }
      } else if (x.t === "op") color = "var(--text-3)";
      if (color) frag.appendChild(makeTokenSpan(x.v, color, bold));
      else frag.appendChild(document.createTextNode(x.v));
    });
  }
  // Highlight `text` (SQL or generic code / HTTP) into `target`. SQL is
  // detected by a leading statement keyword; everything else goes through
  // the generic multi-language branch.
  // Endpoint / metadata highlighter: colors only the HTTP method, {path
  // params} and numbers, leaving service names and path segments plain. A
  // URL path is not code, so a segment that happens to match a code keyword
  // ("export", "class", ...) must NOT be highlighted as one.
  var HTTP_METHODS = { GET: 1, POST: 1, PUT: 1, PATCH: 1, DELETE: 1, HEAD: 1, OPTIONS: 1, TRACE: 1, CONNECT: 1 };
  // Derived from HTTP_METHODS so the dispatch gate cannot drift from the set.
  var HTTP_DISPATCH_RE = new RegExp("^\\s*(" + Object.keys(HTTP_METHODS).join("|") + ")\\s+/", "i");
  function endpointHlFragment(frag, src) {
    var re = /(\s+)|(\{[^}]*\})|(\d+)|([A-Za-z][A-Za-z0-9_-]*)|(\S)/g;
    var m;
    while ((m = re.exec(src))) {
      var color = null, bold = false, v = m[0];
      if (m[1]) { frag.appendChild(document.createTextNode(v)); continue; }
      if (m[2]) color = "var(--warn-fg)";
      else if (m[3]) color = "var(--ok-fg)";
      else if (m[4] && HTTP_METHODS[m[4].toUpperCase()]) { color = "var(--info-fg)"; bold = true; }
      if (color) frag.appendChild(makeTokenSpan(v, color, bold));
      else frag.appendChild(document.createTextNode(v));
    }
  }
  function highlightEndpoint(target, text) {
    if (text == null) return;
    var frag = document.createDocumentFragment();
    endpointHlFragment(frag, String(text));
    target.appendChild(frag);
  }
  function highlightInto(target, text) {
    if (text == null) return;
    var src = String(text);
    var frag = document.createDocumentFragment();
    try {
      // Endpoint ("METHOD /path") first, so "DELETE /x" is not mistaken for
      // a SQL DELETE statement.
      if (HTTP_DISPATCH_RE.test(src)) {
        endpointHlFragment(frag, src);
      } else if (/^\s*(SELECT|INSERT|UPDATE|DELETE|WITH|CREATE|ALTER)\b/i.test(src)) {
        sqlHlFragment(frag, src);
      } else {
        genericHlFragment(frag, src);
      }
    } catch (e) {
      target.appendChild(document.createTextNode(src));
      return;
    }
    target.appendChild(frag);
  }
  // Inline-code in prose: `token` segments become monospace chips, the
  // rest is plain text. Each chip is syntax-highlighted through the same
  // language-agnostic highlighter as the code blocks, so method calls,
  // macros, annotations, keywords and operators get colored.
  function proseInto(target, text) {
    if (text == null) return;
    var parts = String(text).split(/`([^`]+)`/);
    for (var i = 0; i < parts.length; i++) {
      if (i % 2 === 1) {
        var code = el("code", "ps-code-inline");
        highlightInto(code, parts[i]);
        target.appendChild(code);
      } else if (parts[i]) {
        target.appendChild(document.createTextNode(parts[i]));
      }
    }
  }

  // severity + finding-type display maps
  var SEV_LABEL = { critical: "CRIT", warning: "WARN", info: "INFO" };
  // Maps a finding severity to the [data-sev] attribute value driving the
  // severity-pill colors in the redesigned stylesheet.
  var SEV_DATA = { critical: "crit", warning: "warn", info: "info" };
  // Builds a label/value cell for the finding detail meta grid.
  function metaCell(label, value, mono, brand, code) {
    var cell = el("div", "ps-meta-cell");
    cell.appendChild(el("div", "ps-meta-cell-label", label));
    var v = el("div", "ps-meta-cell-value");
    if (code) highlightInto(v, value);
    else v.textContent = value;
    if (mono) v.classList.add("mono");
    if (brand) v.classList.add("brand");
    cell.appendChild(v);
    return cell;
  }
  // Builds a severity pill carrying the [data-sev] attribute.
  function sevPill(severity, cls) {
    var pill = el("span", cls || "ps-sev", SEV_LABEL[severity] || "INFO");
    setAttr(pill, "data-sev", SEV_DATA[severity] || "info");
    return pill;
  }
  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 / sidebar chrome --------
  // The brand wordmark is static markup in the sidebar (inline SVG,
  // theme-swapped by CSS). renderTopbar fills the sidebar version line
  // and the top-bar quality-gate pill; the per-route eyebrow + title
  // are set by switchTab via updateTopbarTitle.
  // Run-context line in the sidebar foot, derived from the Finding
  // `confidence` the producing instance stamps (mode-driven, uniform per
  // run). Batch runs stamp local_batch (developer machine) or ci_batch
  // (CI env detected); daemon runs stamp staging/production from the
  // [daemon] environment. See detect/mod.rs::Confidence and pipeline.rs.
  var CONFIDENCE_CONTEXT = {
    local_batch: { label: "batch · local", tone: "neutral" },
    ci_batch: { label: "batch · CI", tone: "neutral" },
    daemon_staging: { label: "daemon · live · staging", tone: "warn" },
    daemon_production: { label: "daemon · live · prod", tone: "ok" }
  };
  function renderSidebarContext() {
    var ctx = document.getElementById("ps-sidebar-context");
    var dot = document.getElementById("ps-sidebar-dot");
    if (!ctx) return;
    var conf = findings.length ? findings[0].confidence : null;
    var meta = CONFIDENCE_CONTEXT[conf];
    if (!meta) {
      // No findings to read confidence from: fall back to mode only.
      meta = payload.daemon && payload.daemon.url
        ? { label: "daemon · live", tone: "ok" }
        : { label: "batch", tone: "neutral" };
    }
    ctx.textContent = meta.label;
    if (dot) setAttr(dot, "data-ctx", meta.tone);
  }

  function renderTopbar() {
    var verEl = document.getElementById("ps-sidebar-version");
    if (verEl) verEl.textContent = "v" + (payload.version || "") + " · AGPL-3.0";
    renderSidebarContext();
    var gate = report.quality_gate || { passed: true };
    var slot = document.getElementById("topbar-gate");
    if (slot) {
      slot.textContent = "";
      slot.appendChild(
        el(
          "span",
          gate.passed ? "ps-gate-pass" : "ps-gate-fail",
          gate.passed ? "GATE PASS" : "GATE FAIL"
        )
      );
    }
  }

  // Per-route top-bar eyebrow + title. Keys match the registered tab keys.
  var ROUTE_META = {
    overview: { title: "Overview", eyebrow: "summary" },
    findings: { title: "Findings", eyebrow: "findings · triage" },
    pgstat: { title: "pg_stat", eyebrow: "postgres statements" },
    diff: { title: "Diff", eyebrow: "diff vs baseline" },
    correlations: { title: "Correlations", eyebrow: "cross-trace" },
    green: { title: "Carbon", eyebrow: "greenops" },
    acknowledgments: { title: "Acknowledgments", eyebrow: "acks" }
  };
  function updateTopbarTitle(key) {
    var meta = ROUTE_META[key] || { title: key, eyebrow: "" };
    var eb = document.getElementById("topbar-eyebrow");
    var h1 = document.getElementById("topbar-h1");
    if (eb) eb.textContent = "// " + meta.eyebrow;
    if (h1) h1.textContent = meta.title;
  }

  // -------- 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) {
      // Sidebar nav item. `data-nav` drives the hover/active styling;
      // the `ps-tab` class + role="tab" preserve the existing ARIA
      // tablist semantics and let switchTab find every nav item.
      var btn = el("button", "ps-tab");
      btn.type = "button";
      setAttr(btn, "data-nav", "");
      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");
      btn.appendChild(el("span", "ps-nav-dot"));
      btn.appendChild(el("span", "ps-nav-label", t.label));
      if (t.countFn) {
        var c = t.countFn();
        if (c !== null && c !== undefined) {
          btn.appendChild(el("span", "ps-nav-badge", String(c)));
        }
      }
      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";
    });
    updateTopbarTitle(key);
    // Lazily render the detail pane the first time the Findings panel is
    // shown (renderFindingsList skips it while another route is active, so
    // landing on Overview pays nothing for the trace tree + highlighter).
    if (key === "findings" && selectedFinding) {
      var emptyState = document.getElementById("explain-empty");
      if (emptyState && emptyState.style.display !== "none") openExplain(selectedFinding);
    }
    // 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;
  }
  // Overview KPI row: Findings / Critical / Δ baseline / co2.total, with
  // tone-colored values. Adapted to the real payload (Δ baseline reads the
  // diff when present; co2.total reads green_summary).
  function tonedValue(card, tone) {
    var v = card.querySelector(".ps-metric-value");
    if (v) setAttr(v, "data-tone", tone);
    setAttr(card, "data-grad", tone);
    return card;
  }
  function renderFindingsMetrics() {
    var root = document.getElementById("findings-metrics");
    root.textContent = "";
    var sev = countBySeverity();
    var total = findings.length;
    var traces = (report.analysis && report.analysis.traces_analyzed) || 0;

    root.appendChild(metricCard("Findings", fmtNum(total), "across " + fmtNum(traces) + " traces"));
    root.appendChild(tonedValue(
      metricCard("Critical", fmtNum(sev.critical), fmtNum(sev.warning) + " warn · " + fmtNum(sev.info) + " info"),
      "crit"
    ));

    if (hasDiff) {
      var nNew = (diffData.new_findings || []).length;
      var nRes = (diffData.resolved_findings || []).length;
      // +N new findings is a regression (red), −N resolved an improvement
      // (green), matching the Diff page tones.
      var dCard = metricCard("Δ baseline", "", "new / resolved");
      var dv = dCard.querySelector(".ps-metric-value");
      dv.appendChild(makeTokenSpan("+" + nNew, "var(--crit-fg)", false));
      dv.appendChild(document.createTextNode(" / "));
      dv.appendChild(makeTokenSpan("" + nRes, "var(--ok-fg)", false));
      root.appendChild(dCard);
    } else {
      root.appendChild(metricCard("Δ baseline", "-", "no baseline"));
    }

    if (hasGreen) {
      var co2 = greenSummary.co2;
      root.appendChild(tonedValue(
        metricCard("Total CO2", formatGco2(co2.total.mid),
          "low " + formatGco2(co2.total.low) + " · high " + formatGco2(co2.total.high)),
        "brand"
      ));
    } else {
      root.appendChild(metricCard("Total CO2", "-", "green disabled"));
    }
  }

  // -------- quality gate --------
  // Gate rules render inside the Overview hero (renderOverviewHero); this
  // shared formatter is used there for the actual / threshold numbers.
  function formatRuleNumber(n) {
    if (!Number.isFinite(n)) return "-";
    if (Number.isInteger(n)) return String(n);
    return n.toFixed(3);
  }

  // Friendly labels for the quality-gate rule keys (see quality_gate.rs).
  // Unknown / forward-rolled keys fall through to a generic humanizer so a
  // future rule still reads sensibly instead of showing a raw snake_case key.
  var GATE_RULE_LABELS = {
    n_plus_one_sql_critical_max: "Max critical N+1 SQL",
    n_plus_one_http_warning_max: "Max N+1 HTTP (warning+)",
    io_waste_ratio_max: "Max I/O waste ratio"
  };
  function humanizeGateRule(key) {
    if (GATE_RULE_LABELS[key]) return GATE_RULE_LABELS[key];
    var s = String(key || "");
    var prefix = "";
    if (s.endsWith("_max")) { prefix = "Max "; s = s.slice(0, -4); }
    else if (s.endsWith("_min")) { prefix = "Min "; s = s.slice(0, -4); }
    s = s.replace(/_/g, " ")
      .replace(/\bn plus one\b/g, "N+1")
      .replace(/\bsql\b/gi, "SQL")
      .replace(/\bhttp\b/gi, "HTTP")
      .replace(/\bio\b/gi, "I/O");
    if (!prefix && s) s = s.charAt(0).toUpperCase() + s.slice(1);
    return prefix + s;
  }

  // -------- overview landing --------
  // Composed entirely from data already present in the payload: the
  // quality-gate hero (which renders the gate rules), the KPI cards
  // (#findings-metrics), the top findings by impact, and a right rail with
  // diff + carbon mini summaries.
  function renderOverviewPanel() {
    renderOverviewHero();
    renderOverviewBody();
  }

  function renderOverviewHero() {
    var host = document.getElementById("overview-hero");
    if (!host) return;
    host.textContent = "";
    var gate = report.quality_gate || { passed: true, rules: [] };
    var rules = gate.rules || [];

    var card = el("section", "ps-card ps-hero");
    var left = el("div", "ps-hero-left");
    setAttr(left, "data-tone", gate.passed ? "ok" : "crit");
    left.appendChild(el("div", "ps-eyebrow", "// quality gate"));
    var verdict = el("div", "ps-hero-verdict");
    setAttr(verdict, "data-tone", gate.passed ? "ok" : "crit");
    verdict.appendChild(el("span", "ps-hero-dot"));
    verdict.appendChild(el("span", "ps-hero-big", gate.passed ? "PASS" : "FAIL"));
    left.appendChild(verdict);
    var failed = rules.filter(function (r) { return !r.passed; }).length;
    left.appendChild(el(
      "p",
      "ps-hero-line",
      gate.passed
        ? "All " + rules.length + " gate rules satisfied."
        : failed + " of " + rules.length + " gate rules failed."
    ));
    card.appendChild(left);

    var right = el("div", "ps-hero-right");
    if (rules.length > 0) {
      var grid = el("div", "ps-hero-rules");
      rules.forEach(function (r) {
        var item = el("div", "ps-hero-rule");
        var chip = el("span", "ps-hero-rule-chip");
        setAttr(chip, "data-sev", r.passed ? "ok" : "crit");
        chip.appendChild(iconSvg(10, r.passed ? "M5 12l4.5 4.5L19 6" : "M6 6l12 12M18 6L6 18"));
        item.appendChild(chip);
        var txt = el("div", "ps-hero-rule-text");
        txt.appendChild(el("span", "ps-hero-rule-name", humanizeGateRule(r.rule)));
        txt.appendChild(
          el("span", "ps-hero-rule-detail",
            formatRuleNumber(r.actual) + " / " + formatRuleNumber(r.threshold))
        );
        item.appendChild(txt);
        grid.appendChild(item);
      });
      right.appendChild(grid);
    }
    var analysis = report.analysis || {};
    var meta = el("div", "ps-hero-meta");
    [
      payload.input_label || "-",
      fmtNum(analysis.traces_analyzed || 0) + " traces",
      fmtNum(analysis.events_processed || 0) + " spans",
      "v" + (payload.version || "")
    ].forEach(function (m) { meta.appendChild(el("span", null, m)); });
    right.appendChild(meta);
    card.appendChild(right);
    host.appendChild(card);
  }

  function renderOverviewBody() {
    var host = document.getElementById("overview-body");
    if (!host) return;
    host.textContent = "";
    if (findings.length === 0) return;

    var grid = el("div", "ps-overview-cols");

    var leftCard = el("div", "ps-card");
    var head = el("div", "ps-overview-card-head");
    head.appendChild(el("span", "ps-overview-card-title", "Top findings by impact"));
    var viewAll = el("button", "ps-overview-link");
    viewAll.appendChild(el("span", "ps-link-txt", "view all"));
    viewAll.appendChild(document.createTextNode(""));
    viewAll.type = "button";
    viewAll.addEventListener("click", function () { switchTab("findings"); });
    head.appendChild(viewAll);
    leftCard.appendChild(head);

    var totalIo = (greenSummary && greenSummary.total_io_ops) || 0;
    var list = el("div", "ps-list");
    findings.slice(0, 5).forEach(function (f) {
      var row = el("div", "ps-row ps-overview-finding");
      // Left column: severity + "type · ×N" then the service / endpoint.
      var left = el("div", "ps-of-left");
      var top = el("div", "ps-fin-topline");
      top.appendChild(sevPill(f.severity));
      var occ = (f.pattern && f.pattern.occurrences) || 0;
      var typeText = typeLabel(f.type || f.finding_type);
      top.appendChild(el("span", "ps-fin-type", occ ? typeText + " · ×" + occ : typeText));
      left.appendChild(top);
      var ovSub = el("span", "ps-fin-service ps-fin-sub");
      highlightEndpoint(ovSub, (f.service || "-") + " · " + (f.source_endpoint || "-"));
      left.appendChild(ovSub);
      row.appendChild(left);
      // Right column: per-finding green impact (IIS + avoidable-I/O share).
      // The prototype showed a co2-per-finding figure, which the pipeline
      // does not compute; green_impact is the real equivalent.
      var gi = f.green_impact || {};
      var right = el("div", "ps-of-right");
      if (Number.isFinite(gi.io_intensity_score)) {
        right.appendChild(el("span", "ps-of-primary", "IIS " + gi.io_intensity_score.toFixed(1)));
      }
      if (totalIo > 0 && Number.isFinite(gi.estimated_extra_io_ops)) {
        right.appendChild(el(
          "span",
          "ps-of-secondary",
          Math.round((gi.estimated_extra_io_ops / totalIo) * 100) + "% of I/O"
        ));
      }
      row.appendChild(right);
      row.addEventListener("click", function () { gotoFinding(f); });
      list.appendChild(row);
    });
    leftCard.appendChild(list);
    grid.appendChild(leftCard);

    var rail = el("div", "ps-overview-rail");
    if (hasDiff) rail.appendChild(buildDiffMini());
    if (hasGreen) rail.appendChild(buildCarbonMini());
    if (rail.childNodes.length > 0) grid.appendChild(rail);

    host.appendChild(grid);
  }

  // Switches to the Findings panel and selects a specific finding,
  // clearing any active filter that would hide it.
  function gotoFinding(f) {
    switchTab("findings");
    var idx = visibleFindings.indexOf(f);
    if (idx < 0) {
      filterState.severity = null;
      filterState.service = null;
      syncFilterChips();
      resetShownCount();
      renderFindingsList();
      idx = visibleFindings.indexOf(f);
    }
    if (idx >= 0) selectFinding(idx);
  }

  // Opens the detail pane for a finding that is NOT in the master list
  // (a diff "new" finding or a synthetic correlation finding). Switches to
  // Findings and clears the master selection so no list row is misleadingly
  // highlighted while the detail shows an off-list finding.
  function openExternalFindingDetail(f) {
    switchTab("findings");
    selectedIndex = -1;
    selectedFinding = null;
    syncSelection();
    openExplain(f);
  }

  function buildDiffMini() {
    var card = el("div", "ps-mini-card");
    card.appendChild(el("span", "ps-mini-title", "Diff vs baseline"));
    var pills = el("div", "ps-mini-pills");
    var nNew = (diffData.new_findings || []).length;
    var nResolved = (diffData.resolved_findings || []).length;
    var nChanged = (diffData.severity_changes || []).length;
    var pNew = el("span", "ps-mini-pill", "+" + nNew + " new");
    setAttr(pNew, "data-sev", "crit");
    var pRes = el("span", "ps-mini-pill", "" + nResolved + " resolved");
    setAttr(pRes, "data-sev", "ok");
    var pChg = el("span", "ps-mini-pill", nChanged + " changed");
    setAttr(pChg, "data-sev", "warn");
    pills.appendChild(pNew);
    pills.appendChild(pRes);
    pills.appendChild(pChg);
    card.appendChild(pills);
    var link = el("button", "ps-mini-link");
    link.appendChild(el("span", "ps-link-txt", "open diff"));
    link.appendChild(document.createTextNode(""));
    link.type = "button";
    link.addEventListener("click", function () { switchTab("diff"); });
    card.appendChild(link);
    return card;
  }

  function buildCarbonMini() {
    var card = el("div", "ps-mini-card");
    var head = el("div", "ps-mini-head");
    head.appendChild(el("span", "ps-mini-title", "Carbon by region"));
    // Header = operational CO2 only (the sum of the per-region bars). Embodied
    // carbon (in co2.total) is hardware manufacturing, not region-attributable,
    // so co2.total here would make the bars never sum to the header.
    var co2 = greenSummary.co2 || {};
    var total = typeof co2.operational_gco2 === "number"
      ? co2.operational_gco2
      : (greenSummary.regions || []).reduce(function (s, r) { return s + (r.co2_gco2 || 0); }, 0);
    head.appendChild(el("span", "ps-mini-total", formatGco2(total)));
    card.appendChild(head);

    var regions = (greenSummary.regions || []).slice();
    regions.sort(function (a, b) { return (b.co2_gco2 || 0) - (a.co2_gco2 || 0); });
    var top = regions.slice(0, 3);
    top.forEach(function (r) {
      var row = el("div", "ps-mini-row");
      var rh = el("div", "ps-mini-row-head");
      rh.appendChild(el("span", null, r.region || "-"));
      rh.appendChild(el("span", null, formatGco2(r.co2_gco2 || 0)));
      row.appendChild(rh);
      var track = el("div", "ps-bar-track");
      var fill = el("div", "ps-bar-fill");
      // Bar = share of the operational total, so the bars decompose the header.
      fill.style.width = percent(r.co2_gco2 || 0, total);
      track.appendChild(fill);
      row.appendChild(track);
      card.appendChild(row);
    });
    return card;
  }

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

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

    // Severity filters double as colored count pills (critical N / warnings
    // N / info N). "All" is the implicit reset chip.
    var counts = countBySeverity();
    appendChip(severityGroup, "All", "all", "radio", "aria-checked");
    if (counts.critical > 0) appendChip(severityGroup, "critical " + counts.critical, "sev:critical", "radio", "aria-checked", "crit");
    if (counts.warning > 0) appendChip(severityGroup, "warnings " + counts.warning, "sev:warning", "radio", "aria-checked", "warn");
    if (counts.info > 0) appendChip(severityGroup, "info " + counts.info, "sev:info", "radio", "aria-checked", "info");

    var counter = el("span", "ps-findings-count");
    setAttr(counter, "id", "findings-count");
    root.appendChild(counter);

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

    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();
    reapplyFindingsSearch();
    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.
  // Initial page size and "Show more" increment. Kept small so a long
  // findings list stays scannable; the rest reveals via #findings-show-more.
  var LIST_CAP = 8;
  var visibleFindings = [];
  var selectedIndex = -1;
  // The selected finding object (not just its index) so the selection and
  // its detail pane survive a list re-render (filter change, "Show more").
  var selectedFinding = null;
  var shownCount = LIST_CAP;

  // Select a finding by its index in visibleFindings: highlight the row and
  // render its detail pane. The single entry point for click + j/k so the
  // master list and the always-visible detail stay in sync.
  function selectFinding(idx) {
    if (idx < 0 || idx >= visibleFindings.length) return;
    // Re-selecting the same finding (same index AND same object) would
    // rebuild an already-correct detail pane. The object check keeps it
    // correct when a re-render shifts which finding sits at this index.
    if (idx === selectedIndex && visibleFindings[idx] === selectedFinding) return;
    selectedIndex = idx;
    selectedFinding = visibleFindings[idx];
    syncSelection();
    openExplain(selectedFinding);
  }

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

    if (visibleFindings.length === 0) {
      selectedFinding = null;
      selectedIndex = -1;
      empty.style.display = "";
      resetDetailPane();
      syncShowMore(filtered.length);
      return;
    }
    empty.style.display = "none";

    visibleFindings.forEach(function (f, idx) {
      root.appendChild(buildFindingRow(f, idx));
    });
    // Preserve the prior selection across "Show more" / re-renders; fall
    // back to the first row when it is gone (e.g. a filter narrowed it out).
    selectedIndex = selectedFinding ? visibleFindings.indexOf(selectedFinding) : -1;
    if (selectedIndex < 0) {
      selectedIndex = 0;
      selectedFinding = visibleFindings[0];
    }
    syncSelection();
    // Render the detail only when the Findings panel is the active route, so
    // landing on Overview does not pay for the trace tree + highlighter of a
    // finding the user has not opened. switchTab() opens it on first visit.
    if (currentTab === "findings") openExplain(selectedFinding);
    syncShowMore(filtered.length);
  }

  // Resets the detail pane to its empty state (no finding selected).
  function resetDetailPane() {
    var emptyState = document.getElementById("explain-empty");
    if (emptyState) emptyState.style.display = "";
    var head = document.getElementById("explain-detail-head");
    if (head) head.textContent = "";
    var content = document.getElementById("explain-content");
    if (content) content.style.display = "none";
    var ne = document.getElementById("explain-not-embedded");
    if (ne) { ne.style.display = "none"; ne.textContent = ""; }
  }

  function syncShowMore(totalMatching) {
    var counter = document.getElementById("findings-count");
    if (counter) {
      counter.textContent = totalMatching + " findings · " + visibleFindings.length + " shown";
    }
    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);
    // Exposed for the live-mode JS so click handlers on the per-row
    // Ack/Revoke buttons can resolve the signature via DOM lookup. The
    // attribute is harmless in static mode (the buttons stay hidden).
    if (f.signature) setAttr(row, "data-sig", f.signature);

    var topLine = el("div", "ps-fin-topline");
    topLine.appendChild(sevPill(f.severity));
    topLine.appendChild(el("span", "ps-fin-type", typeLabel(f.type || f.finding_type)));
    var occ = (f.pattern && f.pattern.occurrences) || 0;
    if (occ) topLine.appendChild(el("span", "ps-fin-right ps-fin-metric", "×" + occ));
    row.appendChild(topLine);

    var finSub = el("span", "ps-fin-service ps-fin-sub");
    highlightEndpoint(finSub, (f.service || "-") + " · " + (f.source_endpoint || "-"));
    row.appendChild(finSub);

    // The normalized template is not shown in the compact row but stays
    // searchable: the text search matches on row.textContent, and the
    // search placeholders advertise template search.
    var tpl = (f.pattern && f.pattern.template) || "";
    if (tpl) row.appendChild(el("span", "ps-sr-only", tpl));

    // Live-mode action container. Always rendered, hidden by CSS in
    // static mode (`.ps-fin-actions { display: none }`). The
    // `body.ps-live` class flipped at boot reveals it.
    var actions = el("div", "ps-fin-actions");
    var btn = el("button", "ps-fin-action-btn", "Ack");
    btn.type = "button";
    setAttr(btn, "data-action", "ack");
    setAttr(btn, "aria-label", "Acknowledge this finding");
    actions.appendChild(btn);
    row.appendChild(actions);

    row.addEventListener("click", function (event) {
      var t = event.target;
      // Bail when the click landed on the live-mode action button so
      // its own handler runs without ALSO opening the detail pane.
      if (t && (t.classList.contains("ps-fin-action-btn") || t.closest && t.closest(".ps-fin-actions"))) {
        return;
      }
      selectFinding(idx);
    });
    return row;
  }

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

  // -------- explain tree --------
  // Finding header for the detail pane: severity pill, type, a one-line
  // description, the service/endpoint/occurrences/trace meta grid, and the
  // normalized template code block. Always rendered when a finding is
  // selected, independently of whether its trace survived the embed cap.
  // One-line plain-language summary for the detail title. Prefers a
  // server-provided message, else derives a sentence from type + count.
  function findingSummary(f) {
    if (f.message) return f.message;
    if (f.description) return f.description;
    var n = (f.pattern && f.pattern.occurrences) || 0;
    switch (f.type || f.finding_type) {
      case "n_plus_one_sql": return n + " near-identical queries fired within a single trace.";
      case "n_plus_one_http": return n + " near-identical HTTP calls fired within a single trace.";
      case "redundant_sql": return n + " duplicate queries with identical parameters.";
      case "redundant_http": return n + " duplicate HTTP calls with identical parameters.";
      case "slow_sql": return "A query exceeding the latency budget.";
      case "slow_http": return "An HTTP call exceeding the latency budget.";
      case "excessive_fanout": return n + " child calls fanned out from one parent span.";
      case "chatty_service": return n + " calls to the same downstream within a single trace.";
      case "pool_saturation": return "Connection pool saturated during the trace.";
      case "serialized_calls": return n + " calls run serially that could overlap.";
      default: return "";
    }
  }

  // "% of report I/O" from a finding's green_impact, IIS as a fallback.
  function ioImpactText(f) {
    var gi = f.green_impact;
    if (!gi) return "-";
    var totalIo = (greenSummary && greenSummary.total_io_ops) || 0;
    if (totalIo > 0 && Number.isFinite(gi.estimated_extra_io_ops)) {
      return Math.round((gi.estimated_extra_io_ops / totalIo) * 100) + "% of I/O";
    }
    return Number.isFinite(gi.io_intensity_score) ? "IIS " + gi.io_intensity_score.toFixed(1) : "-";
  }

  function renderDetailHead(f) {
    var head = document.getElementById("explain-detail-head");
    head.textContent = "";

    var headRow = el("div", "ps-detail-head");
    headRow.appendChild(sevPill(f.severity));
    var titleWrap = el("div", "ps-detail-titlewrap");
    titleWrap.appendChild(el("h2", "ps-detail-h2", typeLabel(f.type || f.finding_type)));
    var sub = findingSummary(f);
    if (sub) titleWrap.appendChild(el("p", "ps-detail-sub", sub));
    headRow.appendChild(titleWrap);
    head.appendChild(headRow);

    var grid = el("div", "ps-meta-grid");
    grid.appendChild(metaCell("service", f.service || "-"));
    grid.appendChild(metaCell("endpoint", f.source_endpoint || "-", true, false, true));
    grid.appendChild(metaCell("i/o impact", ioImpactText(f)));
    var occ = (f.pattern && f.pattern.occurrences) || 0;
    grid.appendChild(metaCell("occurrences", occ ? ("×" + occ) : "-"));
    head.appendChild(grid);

    var tpl = (f.pattern && f.pattern.template) || "";
    if (tpl) {
      var sec = el("div", "ps-section");
      sec.appendChild(el("span", "ps-eyebrow", "// normalized template"));
      var code = el("code", "ps-codeblock");
      highlightInto(code, tpl);
      sec.appendChild(code);
      head.appendChild(sec);
    }
  }

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

    // The finding header renders inline regardless of whether the trace
    // itself survived the embed cap.
    renderDetailHead(f);

    var trace = tracesById[f.trace_id];
    if (!trace) {
      // Trace dropped by the size cap: keep the header, hide the tree.
      content.style.display = "none";
      notEmbedded.style.display = "";
      notEmbedded.textContent =
        "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 = "";
    highlightEndpoint(
      breadcrumb,
      "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 = "";
    var hasFix = !!f.suggested_fix;
    if (hasFix) {
      fix.style.display = "";
      renderSuggestedFix(fix, f.suggested_fix);
    } else {
      fix.style.display = "none";
    }

    var hasPgstat = renderPgStatXref(document.getElementById("explain-pgstat"), f);
    // Two columns when both pg_stat and fix render, one when only one, hidden when neither.
    var cols = document.getElementById("explain-cols");
    cols.style.display = hasFix || hasPgstat ? "" : "none";
    cols.classList.toggle("single", hasFix !== hasPgstat);

    renderDetailFoot(document.getElementById("explain-foot"), f);
  }

  // Cross-reference the finding's query against pg_stat. Returns true when a
  // matching entry was rendered.
  function renderPgStatXref(host, f) {
    host.textContent = "";
    var tpl = f.pattern && f.pattern.template;
    var entry = tpl ? pgStatByTemplate[tpl] : null;
    if (!entry) { host.style.display = "none"; return false; }
    host.style.display = "";
    host.appendChild(el("span", "ps-eyebrow", "// pg_stat"));
    var row = el("div", "ps-pgstat-xref");
    var code = el("code", null);
    highlightInto(code, entry.normalized_template || tpl);
    row.appendChild(code);
    var occ = (f.pattern && f.pattern.occurrences) || 1;
    var mean = Number.isFinite(entry.mean_exec_time_ms) ? fmtNum(entry.mean_exec_time_ms.toFixed(1)) + "ms" : "";
    row.appendChild(el("span", "ps-pgstat-xref-stat", "×" + occ + "  " + mean));
    host.appendChild(row);
    return true;
  }

  // Footer: source location (when code.* attributes were captured) plus the
  // first/last timestamps the pattern was seen at.
  function renderDetailFoot(host, f) {
    host.textContent = "";
    var parts = [];
    var cl = f.code_location;
    if (cl && cl.filepath) {
      parts.push("source " + cl.filepath + (Number.isFinite(cl.lineno) ? ":" + cl.lineno : ""));
    }
    if (f.first_timestamp) parts.push("seen first " + clockTime(f.first_timestamp));
    if (f.last_timestamp) parts.push("last " + clockTime(f.last_timestamp));
    if (parts.length === 0) { host.style.display = "none"; return; }
    host.style.display = "";
    host.textContent = parts.join(" · ");
  }

  function clockTime(iso) {
    return typeof iso === "string" && iso.length >= 19 ? iso.slice(11, 19) + " UTC" : (iso || "");
  }

  /// 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.
  // Collapse key: spans with the same event type and normalized template
  // (e.g. the N near-identical N+1 queries) fold into one row.
  function collapseKey(span) {
    return (span.event_type || "") + "|" + (span.template || span.target || "");
  }
  function isLeafIdx(idx, spans, tree) {
    var kids = tree.childrenByParent[spans[idx].span_id];
    return !(kids && kids.length);
  }
  // Fold a sibling list into groups: runs of consecutive same-key leaf
  // siblings become one multi-member group; everything else stays singleton.
  function groupSiblings(indices, spans, tree) {
    var groups = [];
    var i = 0;
    while (i < indices.length) {
      var idx = indices[i];
      if (isLeafIdx(idx, spans, tree)) {
        var key = collapseKey(spans[idx]);
        var members = [idx];
        var j = i + 1;
        while (j < indices.length && isLeafIdx(indices[j], spans, tree)
          && collapseKey(spans[indices[j]]) === key) {
          members.push(indices[j]);
          j += 1;
        }
        groups.push(members);
        i = j;
      } else {
        groups.push([idx]);
        i += 1;
      }
    }
    return groups;
  }
  // A collapsed leaf row: the first span's content plus a ×N badge and an
  // "N × avg" duration, mirroring the model's folded N+1 rows.
  function buildCollapsedRow(members, spans, depth, targetTpl) {
    var row = buildSpanRow(spans[members[0]], depth, targetTpl);
    var durEl = row.querySelector(".ps-span-dur");
    // Badge sits between the query text and the (right-aligned) duration.
    row.insertBefore(el("span", "ps-span-count", "×" + members.length), durEl);
    var totalUs = members.reduce(function (s, i) { return s + (spans[i].duration_us || 0); }, 0);
    if (durEl) durEl.textContent = members.length + " × " + formatDurationUs(totalUs / members.length);
    return row;
  }

  function emitSpanTreeRows(root, spans, tree, targetTpl) {
    var stack = [];
    function pushGroups(indices, depth) {
      var groups = groupSiblings(indices, spans, tree);
      for (var g = groups.length - 1; g >= 0; g--) {
        stack.push({ group: groups[g], depth: depth });
      }
    }
    pushGroups(tree.roots, 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;
      if (frame.group.length > 1) {
        root.appendChild(buildCollapsedRow(frame.group, spans, frame.depth, targetTpl));
        emitted += 1;
        continue;
      }
      var span = spans[frame.group[0]];
      root.appendChild(buildSpanRow(span, frame.depth, targetTpl));
      emitted += 1;
      var kids = tree.childrenByParent[span.span_id] || [];
      if (kids.length) pushGroups(kids, 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");
    highlightInto(text, 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") {
      // span.template is already the canonical "METHOD /path" form (see
      // normalize/http.rs), so don't prepend the method again. Only the
      // raw-URL fallback (no template) needs the method prefixed.
      if (span.template) return span.template;
      return (span.operation || "GET").toUpperCase() + " " + (span.target || "");
    }
    return span.operation || span.target || "(span)";
  }

  // Display label for a framework id: drop the "_generic" suffix (so
  // "rust_generic" reads "rust") and turn the remaining underscores into
  // spaces ("java_jpa" -> "java jpa"). The eyebrow style upcases it.
  function frameworkLabel(fw) {
    if (!fw) return "-";
    var s = fw.replace(/_generic$/, "").replace(/_/g, " ");
    // Real product names where the framework id differs from the display.
    return s.replace(/^node\b/, "node.js").replace(/^csharp\b/, "c#");
  }

  function renderSuggestedFix(root, fix) {
    root.appendChild(el("span", "ps-eyebrow brand", "// suggested fix · " + frameworkLabel(fix.framework)));
    var prose = el("span", "ps-fix-prose");
    proseInto(prose, fix.recommendation || "");
    root.appendChild(prose);
    var href = safeHttpsHref(fix.reference_url);
    if (href) {
      var a = el("a", "ps-fix-link", "See documentation ↗");
      setAttr(a, "href", href);
      setAttr(a, "target", "_blank");
      setAttr(a, "rel", "noopener noreferrer");
      root.appendChild(a);
    }
  }

  // -------- green panel --------
  // Builds a metric card with a brand-toned value (Carbon panel uses
  // green numbers throughout).
  function greenCard(label, value, sub, tone) {
    var card = metricCard(label, value, sub);
    var v = card.querySelector(".ps-metric-value");
    if (v) setAttr(v, "data-tone", tone || "brand");
    setAttr(card, "data-grad", tone || "brand");
    return card;
  }

  // Map an interpret.rs severity band to a value tone. The bands are computed
  // Rust-side from the documented thresholds (IIS 2/5/10, waste ratio
  // 0.10/0.30/0.50), so the colors track the same levels as the CLI.
  function bandTone(band) {
    if (band === "critical") return "crit";
    if (band === "high") return "warn";
    if (band === "moderate") return "neutral";
    if (band === "healthy") return "ok";
    return "brand";
  }
  // SCI formula banner shown above the regions table.
  function renderCarbonFormula() {
    var host = document.getElementById("green-formula");
    if (!host) return;
    host.textContent = "";
    host.appendChild(el("code", "ps-formula-code", "co2.total = (E × I) + M"));
    var text = el("span", "ps-formula-text");
    // "SCI v1.0" links to the Green Software Foundation (authors of the spec).
    var href = safeHttpsHref("https://greensoftware.foundation/");
    if (href) {
      var a = el("a", "ps-source-link", "SCI v1.0");
      setAttr(a, "href", href);
      setAttr(a, "target", "_blank");
      setAttr(a, "rel", "noopener noreferrer");
      text.appendChild(a);
    } else {
      text.appendChild(document.createTextNode("SCI v1.0"));
    }
    proseInto(
      text,
      " numerator (ISO/IEC 21031:2024): energy used (E) × grid carbon intensity (I), plus embodied hardware (M), summed over analyzed traces. Per-region scoring when spans carry `cloud.region`."
    );
    host.appendChild(text);
    host.style.display = "";
  }
  function renderGreenPanel() {
    if (!hasGreen) return;
    var co2 = greenSummary.co2;

    var metrics = document.getElementById("green-metrics");
    metrics.appendChild(greenCard(
      "Total CO2",
      formatGco2(co2.total.mid),
      "low " + formatGco2(co2.total.low) + " · high " + formatGco2(co2.total.high)
    ));
    metrics.appendChild(greenCard("Operational CO2", formatGco2(co2.operational_gco2), "E × I"));
    metrics.appendChild(greenCard("Embodied CO2", formatGco2(co2.embodied_gco2), "SCI v1.0 · M term"));
    var avoidMid = co2.avoidable.mid;
    metrics.appendChild(greenCard(
      "Avoidable",
      formatGco2(avoidMid),
      percent(avoidMid, co2.operational_gco2) + " of operational"
    ));
    metrics.appendChild(greenCard(
      "I/O waste ratio",
      Math.round((greenSummary.io_waste_ratio || 0) * 100) + "%",
      "avoidable / total ops",
      bandTone(greenSummary.io_waste_ratio_band)
    ));
    var topOff = greenSummary.top_offenders && greenSummary.top_offenders[0];
    metrics.appendChild(greenCard(
      "IIS score",
      topOff && Number.isFinite(topOff.io_intensity_score) ? topOff.io_intensity_score.toFixed(1) : "-",
      "I/O intensity per call",
      bandTone(topOff && topOff.io_intensity_band)
    ));

    renderCarbonFormula();
    renderScoringConfigBandeau(greenSummary.scoring_config);

    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-card").style.display = "";
    var tbody = document.getElementById("green-regions-body");
    regions.forEach(function (r) {
      var tr = document.createElement("tr");
      tr.appendChild(el("td", null, regionLabel(r.region)));
      tr.appendChild(el("td", null, fmtNum((r.grid_intensity_gco2_kwh || 0).toFixed(0))));
      tr.appendChild(el("td", null, fmtNum(r.io_ops || 0)));
      tr.appendChild(el("td", null, formatGco2(r.co2_gco2 || 0)));
      tr.appendChild(buildSourceCell(r));
      tr.appendChild(buildEstimatedCell(r));
      tbody.appendChild(tr);
    });
  }

  // Renders three chips above the green-regions table: API version,
  // emission factor type, temporal granularity. Hidden when the
  // payload carries no scoring_config (Electricity Maps not configured).
  // The 3 fields are bounded enums on the Rust side, no escaping needed.
  function renderScoringConfigBandeau(cfg) {
    var bandeau = document.getElementById("green-scoring-config");
    if (!bandeau) return;
    if (!cfg) {
      bandeau.style.display = "none";
      return;
    }
    bandeau.replaceChildren(
      el("span", "ps-scoring-label", "Carbon scoring:"),
      buildApiVersionChip(cfg.api_version),
      buildEmissionFactorChip(cfg.emission_factor_type),
      buildTemporalGranularityChip(cfg.temporal_granularity)
    );
    bandeau.style.display = "";
  }

  function buildScoringChip(label, modifier, tooltip) {
    var chip = el("span", "ps-scoring-chip ps-scoring-chip-" + modifier, label);
    chip.setAttribute("title", tooltip);
    return chip;
  }

  // The three chip builders below pattern-match on the known wire
  // values and fall through to a verbatim-text neutral chip on
  // anything else. This keeps a forward-rolled enum variant (a
  // future EmissionFactorType added in a later perf-sentinel
  // release) from silently masquerading as the default chip when an
  // older dashboard renders a newer baseline. The bounded-input
  // invariant on the Rust side (typed enum, no #[serde(other)])
  // keeps the textContent path safe for in-version rendering.
  function buildApiVersionChip(version) {
    if (version === "v3") {
      return buildScoringChip(
        "Electricity Maps v3",
        "warning",
        "v3 is in legacy mode. Migrate to v4 to silence the deprecation warning."
      );
    }
    if (version === "v4") {
      return buildScoringChip(
        "Electricity Maps v4",
        "neutral",
        "API v4 is the current default."
      );
    }
    if (version === "custom") {
      return buildScoringChip(
        "Electricity Maps custom",
        "neutral",
        "Custom endpoint without /vN suffix (proxy or mock)."
      );
    }
    return buildScoringChip(
      "Electricity Maps " + String(version),
      "neutral",
      "Unrecognized API version, displayed verbatim."
    );
  }

  function buildEmissionFactorChip(factor) {
    if (factor === "direct") {
      return buildScoringChip(
        "direct",
        "accent",
        "Direct emissions only. Used by some Scope 2 frameworks."
      );
    }
    if (factor === "lifecycle") {
      return buildScoringChip(
        "lifecycle",
        "neutral",
        "Default. Includes upstream emissions (manufacturing, transport)."
      );
    }
    return buildScoringChip(
      String(factor),
      "neutral",
      "Unrecognized emission factor type, displayed verbatim."
    );
  }

  function buildTemporalGranularityChip(granularity) {
    if (granularity === "5_minutes" || granularity === "15_minutes") {
      return buildScoringChip(
        granularity,
        "accent",
        "Sub-hour granularity. Requires a paid Electricity Maps plan."
      );
    }
    if (granularity === "hourly") {
      return buildScoringChip(
        "hourly",
        "neutral",
        "Default. Hourly average carbon intensity."
      );
    }
    return buildScoringChip(
      String(granularity),
      "neutral",
      "Unrecognized temporal granularity, displayed verbatim."
    );
  }

  // Grid location each region's carbon profile models, taken from the
  // comments in score/carbon_profiles.rs (the country/zone of the grid, not
  // the datacenter city: eu-central-1 models the German grid, etc.).
  var REGION_LOCATIONS = {
    "ap-northeast-1": "Japan", "ap-south-1": "India", "ap-southeast-1": "Singapore",
    "ap-southeast-2": "Australia", "ca-central-1": "Canada", "eu-central-1": "Germany",
    "eu-north-1": "Sweden", "eu-south-1": "Italy", "eu-west-1": "Ireland",
    "eu-west-2": "United Kingdom", "eu-west-3": "France", "eu-west-4": "Netherlands",
    "sa-east-1": "Brazil", "us-east-1": "Virginia", "us-east-2": "Ohio",
    "us-west-1": "California", "us-west-2": "Oregon"
  };
  function regionLabel(code) {
    var loc = code && Object.prototype.hasOwnProperty.call(REGION_LOCATIONS, code)
      ? REGION_LOCATIONS[code] : null;
    return loc ? code + " (" + loc + ")" : (code || "-");
  }

  // Source cell: real_time rows link "Electricity Maps" to its live map;
  // other (embedded proxy) sources render as plain text.
  function buildSourceCell(r) {
    var td = document.createElement("td");
    if (r.intensity_source === "real_time") {
      td.appendChild(document.createTextNode("real time ("));
      var href = safeHttpsHref("https://app.electricitymaps.com/map/live/fifteen_minutes");
      if (href) {
        var a = el("a", "ps-source-link", "Electricity Maps");
        setAttr(a, "href", href);
        setAttr(a, "target", "_blank");
        setAttr(a, "rel", "noopener noreferrer");
        td.appendChild(a);
      } else {
        td.appendChild(document.createTextNode("Electricity Maps"));
      }
      td.appendChild(document.createTextNode(")"));
    } else {
      // Embedded-proxy granularity: render "monthly_hourly" as "monthly hourly".
      td.textContent = r.intensity_source ? r.intensity_source.replace(/_/g, " ") : "-";
    }
    return td;
  }

  function buildEstimatedCell(r) {
    var td = document.createElement("td");
    if (r.intensity_estimated === true) {
      var badge = el("span", "ps-badge-estimated", "Estimated");
      var tip = r.intensity_estimation_method
        ? "Method: " + r.intensity_estimation_method +
          ". Estimated by Electricity Maps using their internal model. " +
          "Less precise than measured data but reliable for trend analysis."
        : "Estimated by Electricity Maps. Less precise than measured data " +
          "but reliable for trend analysis.";
      badge.setAttribute("title", tip);
      td.appendChild(badge);
    } else if (r.intensity_estimated === false) {
      var measured = el("span", "ps-badge-measured", "Measured");
      measured.setAttribute("title", "Source data measured directly from the grid operator.");
      td.appendChild(measured);
    } else {
      td.textContent = "-";
    }
    return td;
  }

  // -------- 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);
      var tplTd = el("td", "ps-pg-template");
      highlightInto(tplTd, entry.normalized_template);
      tr.appendChild(tplTd);
      tr.appendChild(el("td", null, fmtNum(entry.calls || 0)));
      tr.appendChild(el("td", null, fmtNum((entry.total_exec_time_ms || 0).toFixed(1))));
      tr.appendChild(el("td", null, fmtNum((entry.mean_exec_time_ms || 0).toFixed(2))));
      body.appendChild(tr);
    });
  }

  // First ranking whose top-N entries contain the template, or -1.
  function rankingIndexWithTemplate(template) {
    for (var i = 0; i < pgStatRankings.length; i++) {
      var entries = pgStatRankings[i].entries || [];
      var hit = entries.some(function (e) {
        return e.normalized_template === template;
      });
      if (hit) return i;
    }
    return -1;
  }
  function showPgStatDrill(template) {
    // The clicked template may sit in another ranking's top-N, not the
    // active one. Switch to a ranking that lists it so the row exists and
    // can be highlighted (else the drill banner shows the SQL but no row).
    var inActive = activePgStatEntries().some(function (e) {
      return e.normalized_template === template;
    });
    if (!inActive) {
      var idx = rankingIndexWithTemplate(template);
      if (idx >= 0) selectPgStatRanking(idx);
    }
    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 ps-diff-row");
    if (kind === "resolved") {
      var fixed = el("span", "ps-sev", "FIXED");
      setAttr(fixed, "data-sev", "ok");
      row.appendChild(fixed);
    } else {
      row.appendChild(sevPill(f.severity));
    }
    row.appendChild(el("span", "ps-diff-type", typeLabel(f.type || f.finding_type)));
    var diffEp = el("span", "ps-diff-endpoint");
    highlightEndpoint(diffEp, f.source_endpoint || "-");
    row.appendChild(diffEp);
    // Keep service + normalized template searchable (the diff search filters
    // on row.textContent and advertises both), without showing them.
    var diffExtra = (f.service || "") + " " + ((f.pattern && f.pattern.template) || "");
    if (diffExtra.trim()) row.appendChild(el("span", "ps-sr-only", diffExtra));
    if (kind === "resolved") {
      // Resolved findings have no trace in the current run, so there is
      // nothing to open. A toast explains why without navigating away from
      // the Diff tab (which would clear the user's active diff filter).
      row.addEventListener("click", function () {
        showToast(
          "",
          "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 () {
        // Off-list finding: switch to Findings, clear the master selection,
        // and render the detail (the detail pane lives in that panel).
        openExternalFindingDetail(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)));
      var epTd = el("td");
      highlightEndpoint(epTd, (f.service || "-") + " · " + (f.source_endpoint || "-"));
      tr.appendChild(epTd);
      var beforeTd = el("td");
      beforeTd.appendChild(sevPill(c.before_severity));
      tr.appendChild(beforeTd);
      var afterTd = el("td");
      afterTd.appendChild(sevPill(c.after_severity));
      tr.appendChild(afterTd);
      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 || "-"));
      var epTd = el("td");
      highlightEndpoint(epTd, d.endpoint || "-");
      tr.appendChild(epTd);
      tr.appendChild(el("td", null, fmtNum(d.before_io_ops || 0)));
      tr.appendChild(el("td", "ps-diff-after", fmtNum(d.after_io_ops || 0)));
      var delta = d.delta || 0;
      var deltaTd = el("td", null, (delta > 0 ? "+" : "") + fmtNum(delta));
      // Tone by sign: more I/O is a regression (crit), fewer is an
      // improvement (ok), unchanged stays neutral.
      if (delta > 0) setAttr(deltaTd, "data-tone", "crit");
      else if (delta < 0) setAttr(deltaTd, "data-tone", "ok");
      tr.appendChild(deltaTd);
      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 || {};
      // One bordered card per correlation: a warn tag, the mono
      // service path, and a right-aligned conf/lag/traces summary.
      var card = el("div", "ps-corr-card ps-correlation-row");
      var tag = el("span", "ps-corr-tag", typeLabel(src.finding_type || "cross-trace").toUpperCase());
      setAttr(tag, "data-sev", "warn");
      card.appendChild(tag);
      card.appendChild(
        el("span", "ps-corr-path", (src.service || "?") + "" + (tgt.service || "?"))
      );
      var conf = Math.round((c.confidence || 0) * 100);
      var lag = (c.median_lag_ms || 0).toFixed(0);
      var n = c.co_occurrence_count || 0;
      card.appendChild(
        el("span", "ps-corr-meta", "conf " + conf + "% · lag " + lag + " ms · " + n + " traces")
      );
      // Daemon-produced correlations carry sample_trace_id. When set,
      // clicking jumps to the finding detail. openExplain falls back to
      // the shared empty state when the trace is not embedded.
      if (c.sample_trace_id) {
        card.classList.add("ps-correlation-clickable");
        card.addEventListener("click", function () {
          // Off-list synthetic finding: open in the Findings detail pane.
          openExternalFindingDetail(syntheticFindingFromCorrelation(c));
        });
      } else {
        card.style.cursor = "default";
      }
      list.appendChild(card);
    });
  }

  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-corr-card"
    }
  };
  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);
        // Mirror back into the always-visible top-bar box so the two search
        // controls stay in sync (the pg_stat filter box is the only
        // per-panel input the user can actually see and type into).
        var ts = document.getElementById("topbar-search");
        if (ts) ts.value = input.value;
        scheduleHashWrite();
      });
    });
    wireTopbarSearch();
  }
  // The always-visible top-bar search box mirrors into the current
  // panel's per-panel input (the filter source of truth) and runs its
  // filter. Panels with no searchable config ignore the keystrokes.
  function wireTopbarSearch() {
    var ts = document.getElementById("topbar-search");
    if (!ts) return;
    ts.addEventListener("input", function () {
      var cfg = SEARCHABLE_TABS[currentTab];
      if (!cfg) return;
      var panelInput = document.getElementById(cfg.inputId);
      if (panelInput) panelInput.value = ts.value;
      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";
    });
  }
  // Re-apply the active findings text search after the list re-renders
  // (filter chips and Show more rebuild the rows with default display).
  function reapplyFindingsSearch() {
    if (SEARCHABLE_TABS && SEARCHABLE_TABS.findings) {
      applySearchFilter(SEARCHABLE_TABS.findings);
    }
  }
  function openSearchForActiveTab() {
    var cfg = SEARCHABLE_TABS[currentTab];
    if (!cfg) return;
    // "/" focuses the always-visible top-bar search, synced from the
    // active panel's current filter value.
    var ts = document.getElementById("topbar-search");
    if (!ts) return;
    var panelInput = document.getElementById(cfg.inputId);
    ts.value = panelInput ? panelInput.value : "";
    ts.focus();
    ts.select();
  }
  function closeSearch(input) {
    var cfg = SEARCHABLE_TABS[currentTab];
    var ts = document.getElementById("topbar-search");
    var panelInput = cfg ? document.getElementById(cfg.inputId) : null;
    if (ts) ts.value = "";
    if (panelInput) panelInput.value = "";
    if (cfg) applySearchFilter(cfg);
    // Visibility is CSS-governed (see clearAllSearchFilters); just blur.
    if (input) input.blur();
  }
  function clearAllSearchFilters() {
    Object.keys(SEARCHABLE_TABS).forEach(function (tabKey) {
      var cfg = SEARCHABLE_TABS[tabKey];
      var input = document.getElementById(cfg.inputId);
      if (!input || !input.value) return;
      // Clear the value only. Visibility is governed by CSS: bare
      // per-panel inputs stay hidden (.ps-search), the pg_stat filter
      // stays shown because it sits inside a .ps-search-box.
      input.value = "";
      applySearchFilter(cfg);
    });
    var ts = document.getElementById("topbar-search");
    if (ts) ts.value = "";
  }

  // -------- trim banner --------
  function renderTrimBanner() {
    var t = payload.trimmed_traces;
    var f = payload.trimmed_findings;
    if (!t && !f) return;
    var parts = [];
    if (f) {
      parts.push("Showing " + f.kept + " of " + f.total +
        " findings (trimmed for file size, critical first; the JSON report keeps the full set).");
    }
    if (t) {
      parts.push("Showing " + t.kept + " of " + t.total +
        " traces (trimmed for file size). Rerun with --max-traces-embedded <higher> to see more.");
    }
    var b = document.getElementById("trim-banner");
    b.style.display = "";
    b.textContent = parts.join(" ");
  }

  // -------- 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). A plain
    // signed number (e.g. a negative delta "-12") is exempt: it is not a
    // formula, and prefixing it would corrupt numeric columns.
    if (s.length > 0 && "=+-@\t".includes(s.charAt(0)) && !/^[+-]?\d*\.?\d+$/.test(s)) {
      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",
      "confidence"
    ];
    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 || "",
        f.confidence ?? ""
      ];
    });
    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);
    // Pure-digit slug only: parseInt would silently accept "2abc" as 2.
    return /^\d+$/.test(slug) ? Number(slug) : -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" || state.severity === "info") {
        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) {
        // The per-panel input is the filter source of truth but stays
        // hidden; the always-visible top-bar box is the one the user sees.
        input.value = state.search;
        applySearchFilter(cfg);
      }
      var ts = document.getElementById("topbar-search");
      if (ts) ts.value = state.search;
    }
    return true;
  }

  // -------- cheatsheet modal --------
  var CHEATSHEET_ROWS = [
    ["j", "Move finding selection down"],
    ["k", "Move finding selection up"],
    ["Enter", "Open the selected finding"],
    ["Esc", "Close help, close search, clear filters"],
    ["/", "Open search for the active tab"],
    ["g o", "Go to Overview"],
    ["g f", "Go to Findings"],
    ["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 Carbon (if available)"],
    ["g a", "Go to Acknowledgments (live mode)"],
    ["?", "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, 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 === "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;
    // In the master/detail layout the detail pane follows selection, so j/k
    // re-open the now-selected finding (not just move the highlight).
    if (ev.key === "j") {
      selectFinding((selectedIndex + 1) % visibleFindings.length);
      scrollSelectedIntoView();
    } else if (ev.key === "k") {
      selectFinding((selectedIndex - 1 + visibleFindings.length) % visibleFindings.length);
      scrollSelectedIntoView();
    } else if (ev.key === "Enter" && selectedIndex >= 0) {
      selectFinding(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 = {
    o: "overview", f: "findings", p: "pgstat",
    d: "diff", c: "correlations", r: "green", a: "acknowledgments"
  };
  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; }
    // Cmd/Ctrl+K focuses the always-visible top-bar search (the ⌘K hint).
    // The modifier keeps it distinct from the bare `k` finding-nav key.
    if ((ev.metaKey || ev.ctrlKey) && (ev.key === "k" || ev.key === "K")) {
      var topbarSearch = document.getElementById("topbar-search");
      if (topbarSearch) { topbarSearch.focus(); topbarSearch.select(); ev.preventDefault(); }
      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("overview", "Overview", null);
    registerTab("findings", "Findings", function () { return findings.length; });
    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", "Carbon", null);
    if (payload.daemon && payload.daemon.url) {
      registerTab("acknowledgments", "Acknowledgments", function () {
        return liveAcksCount();
      });
    }
    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();
    // Gate rules render inside the Overview hero (renderOverviewHero); there
    // is no longer a standalone gate-rules table.
    renderOverviewPanel();
    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();
    });
    var footerBtn = document.getElementById("footer-shortcuts");
    if (footerBtn) footerBtn.addEventListener("click", openCheatsheet);
  }

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

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

  // -------- live mode (since 0.5.23) --------
  // The whole live-mode block stays inside the existing IIFE so it
  // shares scope with `payload`, `findings`, `renderTabs`,
  // `renderFindingsList` and the `el`/`setAttr` helpers. Running
  // outside would re-parse the `<script id="report-data">` block, a
  // pure overhead.
  //
  // Activation: only when the embedded payload carries
  // `payload.daemon.url`. Static reports (the 0.5.22 default) never
  // touch this code path.
  //
  // Security:
  // - The X-API-Key sits in `liveState.apiKey` and `sessionStorage`.
  //   It is never copied into the DOM as text, never logged, never
  //   shipped in a `data-*` attribute.
  // - All user-facing rendering is `textContent`, never `innerHTML`.
  // - `connect-src` in the CSP whitelists only the daemon URL the
  //   operator passed to `--daemon-url`, validated by the CLI.
  var DAEMON_API_KEY_STORAGE = "perf-sentinel.daemon.api-key";
  var DAEMON_ACKS_CAP = 1000;
  var DAEMON_FETCH_TIMEOUT_MS = 10000;

  var liveState = {
    enabled: false,
    daemonUrl: null,
    apiKey: null,
    acks: [],
    acksBySig: Object.create(null),
    pendingAuthRetry: null,
    activeFindingsAbort: null
  };

  function liveAcksCount() {
    return liveState.acks.length;
  }

  function isLiveEnabled() {
    return liveState.enabled;
  }

  function setApiKey(value) {
    // Guard against an empty / whitespace-only value reaching live
    // state. `submitAuthModal` already trims and rejects empty
    // before getting here, but keep this helper safe to call from
    // anywhere; an accidental empty write would put liveState and
    // sessionStorage into an asymmetric state where one side reads
    // truthy and the other falsy.
    if (typeof value !== "string" || value.trim() === "") {
      clearApiKey();
      return;
    }
    liveState.apiKey = value;
    sessionSet(DAEMON_API_KEY_STORAGE, value);
  }

  function clearApiKey() {
    liveState.apiKey = null;
    // Use removeItem rather than `sessionSet(KEY, "")` so a debugger
    // inspecting sessionStorage does not see a stale empty entry that
    // could mistake for "key was set, then someone null'd it".
    try {
      globalThis.sessionStorage.removeItem(DAEMON_API_KEY_STORAGE);
    } catch {
      // sessionStorage can throw on some hardened browsers (Safari
      // Private Browsing pre-15, embedded WebViews). Fall back to the
      // sessionSet pattern so the in-memory state stays consistent.
      sessionSet(DAEMON_API_KEY_STORAGE, "");
    }
  }

  function liveDaemonBase() {
    return liveState.daemonUrl || "";
  }

  function fetchWithAuth(path, opts) {
    var options = opts || {};
    var headers = {};
    if (options.headers) {
      Object.keys(options.headers).forEach(function (k) {
        headers[k] = options.headers[k];
      });
    }
    headers["Accept"] = "application/json";
    if (liveState.apiKey) {
      headers["X-API-Key"] = liveState.apiKey;
    }
    // Bound every request with an AbortController so a hung daemon
    // does not leave a request pending until the browser's default
    // network timeout (which is multi-minute in Chrome).
    var ctrl = (typeof AbortController === "function") ? new AbortController() : null;
    var init = {
      method: options.method || "GET",
      headers: headers,
      credentials: "omit",
      mode: "cors"
    };
    if (options.body !== undefined && options.body !== null) {
      init.body = options.body;
    }
    if (ctrl) {
      init.signal = ctrl.signal;
    } else if (options.signal) {
      init.signal = options.signal;
    }
    var timer = ctrl ? setTimeout(function () { ctrl.abort(); }, DAEMON_FETCH_TIMEOUT_MS) : null;
    return fetch(liveDaemonBase() + path, init).finally(function () {
      if (timer) clearTimeout(timer);
    });
  }

  function setDaemonStatus(state, label) {
    var dot = document.getElementById("ps-daemon-dot");
    var text = document.getElementById("ps-daemon-status-text");
    if (dot) {
      dot.classList.remove("connected", "disconnected", "unauthorized");
      dot.classList.add(state);
    }
    if (text) text.textContent = label;
  }

  function showToast(kind, message) {
    var existing = document.getElementById("ps-toast");
    if (existing) existing.remove();
    var t = el("div", "ps-toast " + (kind || ""), message);
    setAttr(t, "id", "ps-toast");
    setAttr(t, "role", kind === "error" ? "alert" : "status");
    document.body.appendChild(t);
    setTimeout(function () {
      t.remove();
    }, 5000);
  }

  function pingStatus() {
    return fetchWithAuth("/api/status").then(function (r) {
      if (r.status === 200) {
        setDaemonStatus("connected", "Connected");
        return true;
      }
      if (r.status === 401) {
        // Stale key: a daemon-side rotation invalidated whatever we
        // stored. Drop the cached value so the next write call opens
        // the auth modal cleanly instead of retrying with the bad
        // key.
        if (liveState.apiKey) {
          clearApiKey();
          syncLogoutButtonVisibility();
        }
        setDaemonStatus("unauthorized", "Authentication required");
        return false;
      }
      setDaemonStatus("disconnected", "HTTP " + r.status);
      return false;
    }).catch(function () {
      setDaemonStatus("disconnected", "Unreachable");
      return false;
    });
  }

  function clearAcksState() {
    liveState.acks = [];
    liveState.acksBySig = Object.create(null);
  }

  function applyAcksPayload(data) {
    var arr = Array.isArray(data) ? data : [];
    liveState.acks = arr;
    liveState.acksBySig = Object.create(null);
    for (var a of arr) {
      if (a && a.signature) liveState.acksBySig[a.signature] = a;
    }
  }

  function handleAcksResponse(r) {
    if (!r.ok) {
      if (r.status === 401) {
        setDaemonStatus("unauthorized", "Authentication required");
      }
      clearAcksState();
      return null;
    }
    return r.json().then(applyAcksPayload);
  }

  function fetchAcks() {
    return fetchWithAuth("/api/acks").then(handleAcksResponse).catch(clearAcksState);
  }

  function renderAcksPanel() {
    var body = document.getElementById("acks-body");
    var empty = document.getElementById("acks-empty");
    var footer = document.getElementById("acks-footer");
    var card = document.getElementById("acks-card");
    if (!body) return;
    body.textContent = "";
    if (liveState.acks.length === 0) {
      if (empty) empty.style.display = "";
      if (card) card.style.display = "none";
      if (footer) footer.textContent = "";
      return;
    }
    if (empty) empty.style.display = "none";
    if (card) card.style.display = "";
    liveState.acks.forEach(function (a) {
      body.appendChild(buildAckRow(a));
    });
    if (footer) {
      var note = liveState.acks.length + " active";
      if (liveState.acks.length >= DAEMON_ACKS_CAP) {
        note += " (showing up to " + DAEMON_ACKS_CAP + ", consult the daemon for the full list)";
      }
      note += ". TOML CI acks are not listed here, see .perf-sentinel-acknowledgments.toml.";
      footer.textContent = note;
    }
  }

  function buildAckRow(ack) {
    var tr = document.createElement("tr");
    var sig = document.createElement("td");
    sig.textContent = ack.signature || "-";
    tr.appendChild(sig);
    var by = document.createElement("td");
    by.textContent = ack.by || "-";
    tr.appendChild(by);
    var reason = document.createElement("td");
    reason.textContent = ack.reason || "";
    tr.appendChild(reason);
    var expires = document.createElement("td");
    expires.textContent = ack.expires_at ? ack.expires_at : "never";
    tr.appendChild(expires);
    var act = document.createElement("td");
    var btn = el("button", "ps-fin-action-btn revoke", "Revoke");
    btn.type = "button";
    setAttr(btn, "data-sig", ack.signature || "");
    btn.addEventListener("click", function () {
      revokeAck(ack.signature);
    });
    act.appendChild(btn);
    tr.appendChild(act);
    return tr;
  }

  function syncFindingActionButtons() {
    if (!isLiveEnabled()) return;
    var rows = document.querySelectorAll("#findings-list .ps-row[data-sig]");
    rows.forEach(function (row) {
      var sig = row.dataset.sig || "";
      if (!sig) return;
      var btn = row.querySelector(".ps-fin-action-btn");
      if (!btn) return;
      var isAcked = !!liveState.acksBySig[sig];
      btn.textContent = isAcked ? "Revoke" : "Ack";
      setAttr(btn, "data-action", isAcked ? "revoke" : "ack");
      btn.classList.toggle("revoke", isAcked);
      // Replace the listener on each render. Cheaper than a single
      // event-delegation handler that has to walk back up to find the
      // signature, given we only have at most a few hundred rows in
      // the visible window.
      btn.onclick = function (event) {
        event.stopPropagation();
        if (isAcked) revokeAck(sig);
        else openAckModal(sig);
      };
    });
    // Re-honor the `Show acknowledged` toggle once the action buttons
    // (and therefore the latest `acksBySig` mapping) are settled. The
    // boot path otherwise renders acked findings visible until the
    // user toggles the checkbox.
    applyAckedFilter();
  }

  function openAckModal(sig) {
    var dlg = document.getElementById("ack-modal");
    var sigInput = document.getElementById("ack-modal-sig");
    var reasonInput = document.getElementById("ack-modal-reason");
    var byInput = document.getElementById("ack-modal-by");
    var err = document.getElementById("ack-modal-error");
    if (!dlg || !sigInput || !reasonInput) return;
    sigInput.value = sig;
    reasonInput.value = "";
    if (byInput) byInput.value = "";
    if (err) { err.style.display = "none"; err.textContent = ""; }
    if (typeof dlg.showModal === "function") dlg.showModal();
  }

  function closeAckModal() {
    var dlg = document.getElementById("ack-modal");
    if (dlg && typeof dlg.close === "function") dlg.close();
  }

  function expiresIsoFromShortcut(value) {
    if (!value) return null;
    var now = new Date();
    var hours = 0;
    if (value === "24h") hours = 24;
    else if (value === "7d") hours = 24 * 7;
    else if (value === "30d") hours = 24 * 30;
    else return null;
    var dt = new Date(now.getTime() + hours * 3600 * 1000);
    return dt.toISOString();
  }

  function submitAckModal(event) {
    event.preventDefault();
    var sig = (document.getElementById("ack-modal-sig") || {}).value || "";
    var reason = ((document.getElementById("ack-modal-reason") || {}).value || "").trim();
    var expiresValue = (document.getElementById("ack-modal-expires") || {}).value || "";
    var by = ((document.getElementById("ack-modal-by") || {}).value || "").trim();
    var err = document.getElementById("ack-modal-error");
    if (!sig) return;
    if (!reason) {
      if (err) { err.textContent = "Reason is required."; err.style.display = "block"; }
      return;
    }
    var body = { reason: reason };
    if (by) body.by = by;
    var expiresIso = expiresIsoFromShortcut(expiresValue);
    if (expiresIso) body.expires_at = expiresIso;
    postAck(sig, body, err);
  }

  function postAck(sig, body, errEl) {
    var path = "/api/findings/" + encodeURIComponent(sig) + "/ack";
    fetchWithAuth(path, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(body)
    }).then(function (r) {
      if (r.status === 201) {
        closeAckModal();
        showToast("success", "Acknowledged.");
        return refreshLiveState();
      }
      return handleAuthRetry(r, function () { postAck(sig, body, errEl); }, errEl, "create");
    }).catch(function () {
      if (errEl) { errEl.textContent = "Network error reaching the daemon."; errEl.style.display = "block"; }
    });
  }

  function revokeAck(sig) {
    if (!sig) return;
    if (!globalThis.confirm || !globalThis.confirm("Revoke acknowledgment for " + sig + "?")) return;
    var path = "/api/findings/" + encodeURIComponent(sig) + "/ack";
    fetchWithAuth(path, { method: "DELETE" }).then(function (r) {
      if (r.status === 204) {
        showToast("success", "Acknowledgment revoked.");
        return refreshLiveState();
      }
      return handleAuthRetry(r, function () { revokeAck(sig); }, null, "revoke");
    }).catch(function () {
      showToast("error", "Network error reaching the daemon.");
    });
  }

  function handleAuthRetry(response, retry, errEl, opLabel) {
    if (response.status === 401) {
      liveState.pendingAuthRetry = retry;
      // Tell apart the first 401 (no key cached) from a retry-after-
      // wrong-key 401 so the user gets feedback on the second attempt.
      // Drop the bad key on the way so the next request goes out
      // unauthenticated and the auth flow restarts cleanly.
      var hadKey = liveState.apiKey !== null && liveState.apiKey !== "";
      if (hadKey) {
        clearApiKey();
        syncLogoutButtonVisibility();
      }
      openAuthModal(hadKey ? "Invalid API key, please try again." : null);
      return;
    }
    var msg = "HTTP " + response.status + " on " + opLabel;
    if (errEl) { errEl.textContent = msg; errEl.style.display = "block"; }
    else showToast("error", msg);
  }

  function openAuthModal(errorMessage) {
    var dlg = document.getElementById("auth-modal");
    var keyInput = document.getElementById("auth-modal-key");
    var err = document.getElementById("auth-modal-error");
    if (!dlg) return;
    if (keyInput) keyInput.value = "";
    if (err) {
      if (errorMessage) {
        err.textContent = errorMessage;
        err.style.display = "block";
      } else {
        err.style.display = "none";
        err.textContent = "";
      }
    }
    if (typeof dlg.showModal === "function") dlg.showModal();
    if (keyInput) {
      // Defer focus until after the dialog has actually opened.
      setTimeout(function () { keyInput.focus(); }, 0);
    }
  }

  function closeAuthModal() {
    var dlg = document.getElementById("auth-modal");
    if (dlg && typeof dlg.close === "function") dlg.close();
  }

  function submitAuthModal(event) {
    event.preventDefault();
    var keyInput = document.getElementById("auth-modal-key");
    var err = document.getElementById("auth-modal-error");
    var k = ((keyInput || {}).value || "").trim();
    if (!k) {
      if (err) { err.textContent = "API key is required."; err.style.display = "block"; }
      return;
    }
    setApiKey(k);
    syncLogoutButtonVisibility();
    closeAuthModal();
    var retry = liveState.pendingAuthRetry;
    liveState.pendingAuthRetry = null;
    pingStatus();
    if (typeof retry === "function") retry();
  }

  function refreshLiveState() {
    return Promise.all([pingStatus(), fetchAcks()]).then(function () {
      renderAcksPanel();
      syncFindingActionButtons();
      syncAcksTabBadge();
    });
  }

  function syncAcksTabBadge() {
    // The tab badge is rendered once at boot via `renderTabs` from the
    // `countFn` we registered for "acknowledgments". After an
    // ack/revoke that changed `liveState.acks.length`, the badge is
    // stale until the user switches tabs (which would re-trigger
    // nothing since `renderTabs` is not re-run). Patch the DOM
    // directly: the cheapest correct refresh path. Recreate the
    // badge span when missing so a deferred-fetch boot path (badge
    // not created because countFn returned null) still surfaces the
    // count once acks load.
    var btn = document.getElementById("tab-acknowledgments");
    if (!btn) return;
    var count = liveAcksCount();
    if (count === null || count === undefined) return;
    var badge = btn.querySelector(".ps-badge");
    if (badge) {
      badge.textContent = String(count);
    } else {
      btn.appendChild(document.createTextNode(" "));
      btn.appendChild(el("span", "ps-badge", String(count)));
    }
  }

  function wireRefreshButton() {
    var btn = document.getElementById("ps-refresh-btn");
    if (!btn) return;
    btn.addEventListener("click", function () {
      btn.disabled = true;
      refreshLiveState().then(function () { btn.disabled = false; });
    });
  }

  function syncLogoutButtonVisibility() {
    var btn = document.getElementById("ps-logout-btn");
    if (!btn) return;
    if (liveState.apiKey) btn.hidden = false;
    else btn.hidden = true;
  }

  function wireLogoutButton() {
    var btn = document.getElementById("ps-logout-btn");
    if (!btn) return;
    btn.addEventListener("click", function () {
      clearApiKey();
      syncLogoutButtonVisibility();
      showToast("success", "API key cleared from this tab.");
      pingStatus();
    });
  }

  function applyAckedFilter() {
    // Hide acked findings when the toggle is unchecked. Idempotent
    // and called both from the change handler AND from
    // `syncFindingActionButtons` so the initial state is honored at
    // boot (otherwise the user sees acked findings until they click
    // the toggle, even though "Show acknowledged" is unchecked).
    var input = document.getElementById("findings-include-acked");
    if (!input) return;
    var hideAcked = !input.checked;
    var rows = document.querySelectorAll("#findings-list .ps-row[data-sig]");
    rows.forEach(function (row) {
      var sig = row.dataset.sig || "";
      var isAcked = !!liveState.acksBySig[sig];
      if (hideAcked && isAcked) row.style.display = "none";
      else row.style.display = "";
    });
  }

  function wireIncludeAckedToggle() {
    var input = document.getElementById("findings-include-acked");
    if (!input) return;
    input.addEventListener("change", applyAckedFilter);
  }

  function wireAuthModal() {
    var form = document.getElementById("auth-modal-form");
    var cancel = document.getElementById("auth-modal-cancel");
    var close = document.getElementById("auth-modal-close");
    if (form) form.addEventListener("submit", submitAuthModal);
    if (cancel) cancel.addEventListener("click", function () {
      closeAuthModal();
      liveState.pendingAuthRetry = null;
      setDaemonStatus("unauthorized", "Authentication required");
    });
    if (close) close.addEventListener("click", function () {
      closeAuthModal();
      liveState.pendingAuthRetry = null;
    });
  }

  function wireAckModal() {
    var form = document.getElementById("ack-modal-form");
    var cancel = document.getElementById("ack-modal-cancel");
    var close = document.getElementById("ack-modal-close");
    if (form) form.addEventListener("submit", submitAckModal);
    if (cancel) cancel.addEventListener("click", closeAckModal);
    if (close) close.addEventListener("click", closeAckModal);
  }

  function stripTrailingSlashes(s) {
    // Linear scan from the end. The Rust CLI already trims trailing
    // slashes via `validate_url` before embedding the URL in the
    // payload, so this is defense-in-depth against a corrupted
    // artifact, not the primary normalization path. Avoids the regex
    // engine's backtracking surface that SonarCloud flags as ReDoS-
    // adjacent on `/\/+$/`. `codePointAt` is the Unicode-correct
    // counterpart of `charCodeAt` (47 is U+002F SOLIDUS in both).
    var end = s.length;
    while (end > 0 && s.codePointAt(end - 1) === 47) end--;
    return s.substring(0, end);
  }

  function bootLiveMode() {
    if (!payload.daemon || !payload.daemon.url) return;
    liveState.enabled = true;
    liveState.daemonUrl = stripTrailingSlashes(String(payload.daemon.url));
    var stored = sessionGet(DAEMON_API_KEY_STORAGE);
    if (stored) liveState.apiKey = stored;
    document.body.classList.add("ps-live");

    wireRefreshButton();
    wireLogoutButton();
    wireIncludeAckedToggle();
    wireAuthModal();
    wireAckModal();
    syncLogoutButtonVisibility();

    setDaemonStatus("disconnected", "Connecting...");
    refreshLiveState();
  }

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