perf-sentinel-core 0.8.13

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
//! HTML dashboard sink (single-file output, vanilla JS, `textContent`-only).
//!
//! Emits a self-contained HTML file that renders a completed [`Report`]
//! as an interactive dashboard with Findings, Explain and (when green
//! scoring is enabled) `GreenOps` tabs.
//!
//! # Security model
//!
//! All user-controlled data is injected inside a
//! `<script id="report-data" type="application/json">` block and read
//! once at load time via `Element.textContent`. The bundled JS uses
//! `textContent` and `document.createElement()` exclusively and never
//! calls `innerHTML`, `insertAdjacentHTML`, `document.write`, `eval()`
//! or `new Function()`. The unit test
//! [`tests::no_forbidden_apis_in_template`] greps the template on every
//! build to enforce the rule.
//!
//! Additional defense: [`inject`] escapes the substring `</` in the
//! serialized JSON payload to `<\/` so a user-controlled value
//! (SQL template, HTTP URL, service name) cannot close the `<script>`
//! block early. `\/` is a permitted JSON string escape, so
//! `JSON.parse` recovers the original value unchanged.
//!
//! # Trace embedding
//!
//! Only traces that contain at least one finding are embedded (the empty
//! state in the Explain tab makes free navigation pointless). When
//! `max_traces_embedded` is `None`, the sink targets a ~5 MB HTML file
//! size by trimming the lowest-IIS traces first (top-waste fallback
//! reusing the `top_offenders` ordering). When the user sets
//! `max_traces_embedded` explicitly, that cap is honored exactly,
//! regardless of the size target.
//!
//! See `docs/design/07-CLI-CONFIG-RELEASE.md` for the full design
//! rationale.

use crate::correlate::Trace;
use crate::diff::DiffReport;
use crate::event::EventType;
use crate::ingest::pg_stat::PgStatReport;
use crate::normalize::NormalizedEvent;
use crate::report::Report;
use serde::Serialize;
use std::collections::{HashMap, HashSet};
use std::path::Path;

const TEMPLATE: &str = include_str!("html_template.html");
const JSON_PLACEHOLDER: &str = "{{REPORT_JSON}}";
const TITLE_PLACEHOLDER: &str = "{{PAGE_TITLE}}";
const CSP_PLACEHOLDER: &str = "{{CONTENT_SECURITY_POLICY}}";
const BRAND_LOGO_PLACEHOLDER: &str = "{{BRAND_LOGO}}";
const DEFAULT_TITLE: &str = "perf-sentinel report";
// Brand wordmark, embedded so the self-contained report needs no network
// fetch. Light variant for light backgrounds, light-colored variant for
// dark. The template swaps them by `data-theme` in pure CSS. Kept inside this
// crate (not referenced from the repo-root `logo/`) so `cargo publish`
// packages them; an out-of-package `include_str!` would break the published
// crate's compile.
const BRAND_LOGO_LIGHT_SVG: &str = include_str!("Logo-backgroundless.svg");
const BRAND_LOGO_DARK_SVG: &str = include_str!("Logo-light-backgroundless.svg");
const DEFAULT_SIZE_TARGET_BYTES: usize = 5 * 1024 * 1024;
/// Static-mode Content-Security-Policy. See `docs/design/07-CLI-CONFIG-RELEASE.md`
/// § "`STATIC_CSP` compile-time invariant" for the substitution-shadowing
/// guarantee enforced by the const block below.
const STATIC_CSP: &str = "default-src 'none'; script-src 'unsafe-inline'; \
                          style-src 'unsafe-inline'; img-src data:; \
                          base-uri 'none'; form-action 'none'";

/// Compile-time guard: a value substituted into the document before the JSON
/// marker (the CSP, the brand SVGs) must not contain `{{`, which would shadow
/// a later `{{...}}` placeholder during [`inject`].
const fn assert_no_double_brace(s: &str) {
    let bytes = s.as_bytes();
    let mut i = 0;
    while i + 1 < bytes.len() {
        assert!(
            !(bytes[i] == b'{' && bytes[i + 1] == b'{'),
            "embedded asset must not contain `{{{{`, it would shadow placeholder substitution"
        );
        i += 1;
    }
}
const _: () = {
    assert_no_double_brace(STATIC_CSP);
    assert_no_double_brace(BRAND_LOGO_LIGHT_SVG);
    assert_no_double_brace(BRAND_LOGO_DARK_SVG);
};
/// Embedded in every payload as the `version` field. Extracted from the
/// environment at compile time via `env!`, kept as a single constant so
/// the size-trim pass and the final build path cannot drift.
const PAYLOAD_VERSION: &str = env!("CARGO_PKG_VERSION");

/// Options controlling HTML rendering.
#[derive(Debug, Clone)]
pub struct RenderOptions {
    /// Label shown in the top bar (filename, `-` for stdin, etc.).
    pub input_label: String,
    /// Explicit cap on embedded traces. When `None`, the sink trims to
    /// fit [`DEFAULT_SIZE_TARGET_BYTES`] using the top-waste fallback.
    pub max_traces_embedded: Option<usize>,
    /// Optional `pg_stat_statements` report embedded alongside the
    /// analysis. When `Some`, the HTML dashboard exposes a `pg_stat` tab
    /// plus the Explain-to-`pg_stat` cross-navigation for matching SQL
    /// templates.
    pub pg_stat: Option<PgStatReport>,
    /// Optional diff against a baseline run embedded alongside the
    /// analysis. When `Some`, the HTML dashboard exposes a Diff tab
    /// with new/resolved findings, severity changes, and per-endpoint
    /// deltas.
    pub diff: Option<DiffReport>,
    /// When `Some`, the generated HTML enables live mode: the in-page
    /// JavaScript connects to the daemon at this URL for ack/revoke
    /// interactions, fetches the daemon-side acks listing, and shows a
    /// connection-status indicator. Reveals the auth-key prompt modal
    /// on a 401 response. The daemon must have CORS configured (see
    /// `[daemon.cors]` in CONFIGURATION.md) and the document origin
    /// allowed.
    ///
    /// When `None`, the HTML is purely static: no badge, no
    /// ack/revoke buttons, no acknowledgments panel, strict CSP with
    /// no `connect-src` directive.
    ///
    /// The URL is expected to have been validated by the caller. The
    /// renderer trusts it as-is and concatenates it into the
    /// Content-Security-Policy `connect-src` directive. Validation
    /// rejects userinfo, paths, query strings and ASCII control
    /// characters via `crates/sentinel-cli/src/ack.rs::validate_url`.
    /// The browser-side handlers (auth-key prompt, ack/revoke modal,
    /// fetch retry) live in the live-mode IIFE block at the bottom
    /// of `crates/sentinel-core/src/report/html_template.html`.
    pub daemon_url: Option<String>,
}

/// Counters describing how many candidate traces ended up embedded in
/// the rendered HTML. Returned by [`render`] so callers can surface a
/// trim notice to the user when `kept < total`. Field naming mirrors
/// the private `TrimSummary` struct used inside the JSON payload.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RenderStats {
    /// Number of traces actually embedded in the rendered HTML.
    pub kept: usize,
    /// Total candidate traces before the trace-level size or cap trim.
    /// Candidates come from the findings kept in the embed, so when the
    /// findings trim fires this is already conservative versus the full
    /// JSON report (deliberate: every embedded trace has its finding
    /// visible in the dashboard).
    pub total: usize,
}

/// Render a report to a self-contained HTML string and return how many
/// traces were embedded vs. how many were candidates.
///
/// # Panics
///
/// Panics if `serde_json` fails to serialize the payload. The payload
/// is built from `Serialize` types with only string and number keys,
/// so this can only happen on serde internal errors (out-of-memory and
/// similar system-level failures), not on user input.
///
/// # Examples
///
/// ```no_run
/// use sentinel_core::report::html::{render, RenderOptions};
/// use sentinel_core::pipeline::analyze_with_traces;
/// # fn load_events() -> Vec<sentinel_core::event::SpanEvent> { vec![] }
/// let events = load_events();
/// let cfg = sentinel_core::config::Config::default();
/// let (report, traces) = analyze_with_traces(events, &cfg);
/// let (html, _stats) = render(&report, &traces, &RenderOptions {
///     input_label: "traces.json".to_string(),
///     max_traces_embedded: None,
///     pg_stat: None,
///     diff: None,
///     daemon_url: None,
/// });
/// assert!(html.starts_with("<!DOCTYPE html>"));
/// ```
#[must_use]
pub fn render(report: &Report, traces: &[Trace], options: &RenderOptions) -> (String, RenderStats) {
    // Mixed-content guard: an http:// daemon URL on a non-loopback host
    // breaks ack/revoke fetches if the report is later served over https.
    if let Some(url) = options.daemon_url.as_deref()
        && let Some(rest) = url.strip_prefix("http://")
    {
        let host_only = rest.split(['/', ':']).next().unwrap_or("");
        let is_loopback =
            host_only == "localhost" || host_only == "127.0.0.1" || host_only == "[::1]";
        if !is_loopback {
            tracing::warn!(
                daemon_url = url,
                "http:// daemon URL on a non-loopback host: ack/revoke fetches will be blocked when the report is served over https://"
            );
        }
    }
    let sanitized_label = sanitize_input_label(&options.input_label);
    let (report_embed, trimmed_findings) = slim_report_for_embed(report, options);
    // Trace ranking reads the un-slimmed `top_offenders` so the ordering
    // is accurate even past the embed cap; the payload serializes the
    // slim report.
    let payload = build_payload_with_label(
        &report_embed,
        &report.green_summary.top_offenders,
        traces,
        options,
        &sanitized_label,
        trimmed_findings,
    );
    let kept = payload.embedded_traces.len();
    let total = payload.trimmed_traces.as_ref().map_or(kept, |s| s.total);
    // Serialization of our fixed-shape payload cannot fail: all nested
    // types are `Serialize`, every map key is `&'static str`, and there
    // are no non-string map keys anywhere in the tree. If a future
    // refactor introduces a `HashMap<NonStringKey, _>` anywhere under
    // `Payload`, `serde_json` will fail here at runtime. Keep the
    // payload's map keys `&'static str` or `String` only.
    let json = serde_json::to_string(&payload).expect("payload always serializes");
    let title = derive_page_title(&sanitized_label);
    let csp = build_csp(options.daemon_url.as_deref());
    let html = inject(&json, &title, &csp);
    (html, RenderStats { kept, total })
}

/// Render and write a rendered HTML dashboard to `output`.
///
/// # Errors
///
/// Returns the underlying [`std::io::Error`] if the file cannot be
/// created or written.
///
/// # Panics
///
/// Panics if serialization fails for the same reason as [`render`].
pub fn write(
    report: &Report,
    traces: &[Trace],
    options: &RenderOptions,
    output: &Path,
) -> std::io::Result<()> {
    let (html, _stats) = render(report, traces, options);
    std::fs::write(output, html)
}

// --- internal ---

#[derive(Debug, Serialize)]
struct Payload<'a> {
    version: &'static str,
    input_label: &'a str,
    report: &'a Report,
    embedded_traces: Vec<EmbeddedTrace<'a>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    trimmed_traces: Option<TrimSummary>,
    #[serde(skip_serializing_if = "Option::is_none")]
    trimmed_findings: Option<TrimSummary>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pg_stat: Option<&'a PgStatReport>,
    #[serde(skip_serializing_if = "Option::is_none")]
    diff: Option<&'a DiffReport>,
    #[serde(skip_serializing_if = "Option::is_none")]
    daemon: Option<DaemonHandle<'a>>,
}

/// Live-mode handle embedded in the JSON payload. Presence flips the JS
/// boot path from "static" to "live": fetch ack data, reveal the
/// daemon-status badge, attach Ack/Revoke handlers. Field naming kept
/// short on purpose, the JSON is read at boot every time.
#[derive(Debug, Serialize)]
struct DaemonHandle<'a> {
    url: &'a str,
}

#[derive(Debug, Serialize)]
struct EmbeddedTrace<'a> {
    trace_id: &'a str,
    spans: Vec<EmbeddedSpan<'a>>,
}

#[derive(Debug, Serialize)]
struct EmbeddedSpan<'a> {
    span_id: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    parent_span_id: Option<&'a str>,
    service: &'a str,
    endpoint: &'a str,
    event_type: &'static str,
    operation: &'a str,
    target: &'a str,
    template: &'a str,
    duration_us: u64,
    #[serde(skip_serializing_if = "Option::is_none")]
    status_code: Option<u16>,
}

#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
struct TrimSummary {
    kept: usize,
    total: usize,
}

/// Inject the CSP, page title and JSON payload into the template.
///
/// Escapes `</` to `<\/` in the JSON payload so a user-controlled
/// string cannot close the `<script>` block early. `\/` is a permitted
/// JSON string escape, so round-tripping through `JSON.parse` recovers
/// the original value. The title is already HTML-escaped by
/// [`derive_page_title`]. The CSP string is built by [`build_csp`] from
/// a static prefix and the validated daemon URL, no untrusted bytes
/// reach the meta tag.
///
/// Substitution order is critical and verified by
/// `hostile_input_label_with_json_placeholder_does_not_double_substitute`
/// and friends:
/// - the brand SVG is substituted first; it is trusted compile-time content
///   guaranteed `{{`-free (see [`assert_no_double_brace`]), so it cannot lay
///   down a fake placeholder for the later passes to match;
/// - the JSON payload is substituted before the title, so a hostile
///   `input_label` carrying `{{REPORT_JSON}}` (injected only at the title
///   pass) cannot trigger a second JSON substitution;
/// - the CSP and title markers sit in `<head>`, ahead of both the JSON block
///   and the brand marker, so a hostile title or JSON payload cannot shadow
///   the static `replacen(..., 1)` matches.
fn inject(json: &str, title: &str, csp: &str) -> String {
    // Defense-in-depth: a `{{` byte sequence in the CSP would shadow a
    // template placeholder during the title substitution. `validate_url`
    // rejects bytes `hyper::Uri` does not accept in a host so the check
    // holds today; plain `assert!` keeps the safety net in release.
    assert!(
        !csp.contains("{{"),
        "CSP must not contain `{{{{` placeholder bytes, got: {csp}"
    );
    let safe = json.replace("</", "<\\/");
    // Brand wordmark as raw inline SVG (light + dark variants), substituted
    // into the static <span> in the topbar. Server-side substitution, not a
    // runtime `innerHTML`, so the template keeps its textContent-only XSS
    // invariant. The SVG is trusted compile-time content and lives in the
    // body (not a <script>), so no `</` escaping is needed. Substituted
    // before the report JSON so a hostile `{{BRAND_LOGO}}` inside report
    // content cannot shadow this one.
    let brand_logo = format!(
        "<span class=\"ps-logo ps-logo-light\">{BRAND_LOGO_LIGHT_SVG}</span>\
         <span class=\"ps-logo ps-logo-dark\">{BRAND_LOGO_DARK_SVG}</span>"
    );
    TEMPLATE
        .replacen(BRAND_LOGO_PLACEHOLDER, &brand_logo, 1)
        .replacen(JSON_PLACEHOLDER, &safe, 1)
        .replacen(CSP_PLACEHOLDER, csp, 1)
        .replacen(TITLE_PLACEHOLDER, title, 1)
}

/// Build the Content-Security-Policy string for a render call. In
/// static mode, returns the historical strict policy verbatim. In live
/// mode, appends `connect-src 'self' <daemon_url>` so the in-page
/// JavaScript can `fetch()` the daemon AND any same-origin asset (a
/// future template change adding a same-origin fetch will not silently
/// break under the strict CSP). The caller validates the URL upstream
/// (the CLI runs it through `validate_url` and rejects userinfo, paths,
/// query strings, ASCII control characters), so no CSP-breaking byte
/// (single quote, semicolon, whitespace, curly braces) can land in the
/// directive value. The `inject` `debug_assert!(!csp.contains("{{"))`
/// is the load-bearing fallback in case `validate_url` is ever
/// relaxed.
#[must_use]
fn build_csp(daemon_url: Option<&str>) -> String {
    match daemon_url {
        Some(url) => format!("{STATIC_CSP}; connect-src 'self' {url}"),
        None => STATIC_CSP.to_string(),
    }
}

/// Derive the `<title>` text from the user-supplied `input_label`.
///
/// Strips any path components, HTML-escapes the filename, and formats
/// as `perf-sentinel: <filename>`. Falls back to a fixed string when
/// the label is empty or `-` (stdin).
fn derive_page_title(input_label: &str) -> String {
    let trimmed = input_label.trim();
    if trimmed.is_empty() || trimmed == "-" {
        return DEFAULT_TITLE.to_string();
    }
    let filename = Path::new(trimmed)
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or(trimmed);
    format!("perf-sentinel: {}", html_escape_text(filename))
}

/// Strip control and unsafe-format characters from `input_label`
/// before it lands in the JSON payload. The topbar renders the value
/// via `textContent`, so there is no XSS risk, but a leaked `BiDi`
/// override would still flip the visible order of surrounding text.
fn sanitize_input_label(input_label: &str) -> String {
    input_label
        .chars()
        .filter(|c| !c.is_control() && !is_unsafe_format_char(*c))
        .collect()
}

/// Minimal HTML escape for the title text. `<title>` is a raw-text
/// element, so only `&` and `<` strictly need escaping, but we also
/// escape `>` and the two quote characters for belt-and-braces safety.
/// Control characters (Unicode Cc, plus the known `BiDi` and
/// line/paragraph-separator format codes that some terminals and
/// browsers honor) are dropped so a hostile filename cannot inject
/// cosmetic payloads into the browser tab.
fn html_escape_text(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '"' => out.push_str("&quot;"),
            '\'' => out.push_str("&#39;"),
            c if c.is_control() || is_unsafe_format_char(c) => {}
            _ => out.push(c),
        }
    }
    out
}

/// Unicode format characters that carry cosmetic payloads: `BiDi`
/// override and isolate marks, line/paragraph separators, and the
/// byte-order mark. `char::is_control` only catches the `Cc` category,
/// so we filter these `Cf` entries by hand.
fn is_unsafe_format_char(c: char) -> bool {
    matches!(
        c,
        '\u{200E}' // LEFT-TO-RIGHT MARK
        | '\u{200F}' // RIGHT-TO-LEFT MARK
        | '\u{2028}' // LINE SEPARATOR
        | '\u{2029}' // PARAGRAPH SEPARATOR
        | '\u{202A}'..='\u{202E}' // LRE / RLE / PDF / LRO / RLO
        | '\u{2066}'..='\u{2069}' // LRI / RLI / FSI / PDI
        | '\u{FEFF}' // BYTE ORDER MARK
    )
}

fn build_payload_with_label<'a>(
    report: &'a Report,
    full_top_offenders: &[crate::report::TopOffender],
    traces: &'a [Trace],
    options: &'a RenderOptions,
    input_label: &'a str,
    trimmed_findings: Option<TrimSummary>,
) -> Payload<'a> {
    // Candidate set from the embedded findings (so every embedded trace
    // has its finding shown), ranked by the full offender list (so the
    // ordering does not degrade past the embed cap).
    let ordered = order_candidates_by_iis(&report.findings, full_top_offenders, traces);
    let total = ordered.len();

    let (kept_refs, trimmed) = if let Some(cap) = options.max_traces_embedded {
        let take = cap.min(total);
        let summary = if take < total {
            Some(TrimSummary { kept: take, total })
        } else {
            None
        };
        (ordered.into_iter().take(take).collect::<Vec<_>>(), summary)
    } else {
        trim_to_size_target(
            ordered,
            report,
            options,
            input_label,
            trimmed_findings.clone(),
        )
    };

    let embedded_traces = kept_refs.iter().copied().map(embed_trace).collect();

    Payload {
        version: PAYLOAD_VERSION,
        input_label,
        report,
        embedded_traces,
        trimmed_traces: trimmed,
        trimmed_findings,
        pg_stat: options.pg_stat.as_ref(),
        diff: options.diff.as_ref(),
        daemon: options
            .daemon_url
            .as_deref()
            .map(|url| DaemonHandle { url }),
    }
}

/// Filter traces to those referenced by a finding and sort by
/// per-trace IIS (highest first). Lower `top_offenders` index means
/// higher IIS. Traces whose `(service, endpoint)` pairs are absent from
/// `top_offenders` rank as `usize::MAX` and sort last.
fn order_candidates_by_iis<'a>(
    findings: &[crate::detect::Finding],
    top_offenders: &[crate::report::TopOffender],
    traces: &'a [Trace],
) -> Vec<&'a Trace> {
    let finding_trace_ids: HashSet<&str> = findings.iter().map(|f| f.trace_id.as_str()).collect();

    let mut rank: HashMap<(&str, &str), usize> = HashMap::new();
    for (i, off) in top_offenders.iter().enumerate() {
        rank.insert((off.service.as_str(), off.endpoint.as_str()), i);
    }

    let mut scored: Vec<(usize, &'a Trace)> = traces
        .iter()
        .filter(|t| finding_trace_ids.contains(t.trace_id.as_str()))
        .map(|t| (trace_rank(t, &rank), t))
        .collect();
    scored.sort_by_key(|(score, _)| *score);
    scored.into_iter().map(|(_, t)| t).collect()
}

fn trace_rank(trace: &Trace, rank: &HashMap<(&str, &str), usize>) -> usize {
    trace
        .spans
        .iter()
        .map(|s| {
            rank.get(&(s.event.service.as_ref(), s.event.source.endpoint.as_str()))
                .copied()
                .unwrap_or(usize::MAX)
        })
        .min()
        .unwrap_or(usize::MAX)
}

/// Findings share of the JSON budget when the sink targets a file size.
/// Traces get whatever remains; without this bound a large batch (tens of
/// thousands of findings) ships a multi-MB envelope no matter how many
/// traces are trimmed.
const FINDINGS_BUDGET_SHARE_PCT: usize = 70;

/// Cap on `green_summary.top_offenders` embedded in the HTML payload. The
/// dashboard only ever reads `top_offenders[0]` (the "Top offender" card),
/// so a high-endpoint-cardinality report would otherwise embed thousands
/// of rows nothing renders. The full ranking still drives trace ordering
/// (from the un-slimmed report) and stays in `analyze --format json`. The
/// cap leaves headroom for a future top-N table without re-bloating.
const TOP_OFFENDERS_EMBED_CAP: usize = 25;

/// Build the slimmed `Report` embedded in the HTML payload. Three sections
/// the dashboard does not fully render are bounded so a high-volume report
/// does not bloat the self-contained file, while `analyze --format json`
/// keeps every one of them in full:
///   - `findings`: trimmed critical-first when over the size budget
///     (surfaced as a banner), full otherwise;
///   - `per_endpoint_io_ops`: dropped entirely (no dashboard view reads it);
///   - `green_summary.top_offenders`: capped to [`TOP_OFFENDERS_EMBED_CAP`].
fn slim_report_for_embed(
    report: &Report,
    options: &RenderOptions,
) -> (Report, Option<TrimSummary>) {
    let (findings, trimmed_findings) = select_embedded_findings(report, options);
    // Clone-then-truncate: the transient full clone is freed immediately,
    // and a one-shot HTML render is not a hot path. What matters is that
    // the serialized payload carries at most the cap.
    let mut green_summary = report.green_summary.clone();
    green_summary
        .top_offenders
        .truncate(TOP_OFFENDERS_EMBED_CAP);
    // Exhaustive literal, not `report.clone()`: it makes the dropped
    // `per_endpoint_io_ops` explicit (never cloning the big vec) and turns
    // a future new `Report` field into a compile error here.
    let embed = Report {
        analysis: report.analysis.clone(),
        findings,
        green_summary,
        quality_gate: report.quality_gate.clone(),
        per_endpoint_io_ops: Vec::new(),
        correlations: report.correlations.clone(),
        warnings: report.warnings.clone(),
        warning_details: report.warning_details.clone(),
        acknowledged_findings: report.acknowledged_findings.clone(),
        binary_version: report.binary_version.clone(),
        disclosure_waste: report.disclosure_waste.clone(),
    };
    (embed, trimmed_findings)
}

/// Select the findings to embed. Critical findings are kept first, then
/// warning, then info, preserving the canonical report order inside each
/// band. Returns the full set (and no summary) when `--max-traces-embedded`
/// opts out of size targeting or the set already fits; otherwise the
/// critical-first prefix that fits, with a [`TrimSummary`].
fn select_embedded_findings(
    report: &Report,
    options: &RenderOptions,
) -> (Vec<crate::detect::Finding>, Option<TrimSummary>) {
    if options.max_traces_embedded.is_some() {
        return (report.findings.clone(), None);
    }
    let json_budget = DEFAULT_SIZE_TARGET_BYTES.saturating_sub(TEMPLATE.len());
    let findings_budget = json_budget * FINDINGS_BUDGET_SHARE_PCT / 100;
    // Serialize each finding exactly once: the same sizes serve the
    // whole-array early exit (sum + commas + brackets) and the budget
    // loop below, instead of serializing the array a second time.
    let sizes: Vec<usize> = report
        .findings
        .iter()
        .map(|f| serde_json::to_string(f).map_or(usize::MAX, |s| s.len()))
        .collect();
    let total_len = sizes
        .iter()
        .fold(2usize, |acc, len| acc.saturating_add(len.saturating_add(1)));
    if total_len <= findings_budget {
        return (report.findings.clone(), None);
    }

    let mut order: Vec<usize> = (0..report.findings.len()).collect();
    // Stable sort on the derived Severity ordering (Critical < Warning
    // < Info): severity bands first, canonical order within a band.
    order.sort_by_key(|&i| &report.findings[i].severity);

    let mut running = 2usize; // the [] array brackets
    let mut keep: Vec<usize> = Vec::new();
    for &i in &order {
        let next = running.saturating_add(sizes[i].saturating_add(1));
        if next > findings_budget {
            break;
        }
        running = next;
        keep.push(i);
    }
    keep.sort_unstable();

    let summary = TrimSummary {
        kept: keep.len(),
        total: report.findings.len(),
    };
    let kept = keep
        .into_iter()
        .map(|i| report.findings[i].clone())
        .collect();
    (kept, Some(summary))
}

/// Greedy trim-to-size loop: serialize, measure, drop the lowest-ranked
/// trace if over budget. Bounded by the number of input traces. On
/// realistic inputs (few dozen traces, report JSON under ~200 KB) the
/// first iteration usually fits and no trimming happens.
fn trim_to_size_target<'a>(
    ordered: Vec<&'a Trace>,
    report: &Report,
    options: &'a RenderOptions,
    input_label: &'a str,
    trimmed_findings: Option<TrimSummary>,
) -> (Vec<&'a Trace>, Option<TrimSummary>) {
    let total = ordered.len();

    // Two-step approach. The previous implementation re-serialized the
    // entire payload once per trace we shed, giving O(N^2) total work
    // in the number of traces. This one serializes each embedded trace
    // once and the non-trace envelope once, then uses a prefix-sum
    // scan to find the longest trace prefix that fits under the size
    // target. Total serialization volume is O(N * avg_trace_size),
    // linear in the payload.

    // Step 1: per-trace JSON sizes. We account for the surrounding
    // comma and the 2 literal bracket bytes of the JSON array via
    // `separator_overhead` below.
    let per_trace_lens: Vec<usize> = ordered
        .iter()
        .copied()
        .map(|t| serde_json::to_string(&embed_trace(t)).map_or(usize::MAX, |s| s.len()))
        .collect();

    // Step 2: envelope size. Build a payload whose `embedded_traces`
    // is empty, serialize it once, and use its length as the fixed
    // overhead that every kept-trace count shares. `trimmed_traces`
    // is set to a placeholder with realistic digits so its JSON
    // length is not under-reported (the actual value is written back
    // in `build_payload_with_label` after trimming), and the real
    // `trimmed_findings` rides along for the same reason.
    let envelope = Payload {
        version: PAYLOAD_VERSION,
        input_label,
        report,
        embedded_traces: Vec::new(),
        trimmed_traces: Some(TrimSummary { kept: 0, total }),
        trimmed_findings,
        pg_stat: options.pg_stat.as_ref(),
        diff: options.diff.as_ref(),
        daemon: options
            .daemon_url
            .as_deref()
            .map(|url| DaemonHandle { url }),
    };
    let envelope_len = serde_json::to_string(&envelope).map_or(usize::MAX, |s| s.len());

    // Budget for the serialized JSON payload: the template is a fixed
    // cost on every output. If TEMPLATE.len() already exceeds the
    // target (implausible), we return an empty set rather than
    // underflow.
    let json_budget = DEFAULT_SIZE_TARGET_BYTES.saturating_sub(TEMPLATE.len());

    // Find the largest prefix of `ordered` whose combined size fits
    // under the budget. Each trace contributes `len + 1` (for the
    // comma separator); the two empty-array bytes `[]` are already
    // included in `envelope_len`.
    let mut running = envelope_len;
    let mut keep_count: usize = 0;
    for &len in &per_trace_lens {
        let delta = len.saturating_add(1);
        let next = running.saturating_add(delta);
        if next > json_budget {
            break;
        }
        running = next;
        keep_count += 1;
    }

    let kept: Vec<&'a Trace> = ordered.into_iter().take(keep_count).collect();
    let trimmed = if kept.len() < total {
        Some(TrimSummary {
            kept: kept.len(),
            total,
        })
    } else {
        None
    };
    (kept, trimmed)
}

fn embed_trace(t: &Trace) -> EmbeddedTrace<'_> {
    EmbeddedTrace {
        trace_id: t.trace_id.as_str(),
        spans: t.spans.iter().map(embed_span).collect(),
    }
}

fn embed_span(e: &NormalizedEvent) -> EmbeddedSpan<'_> {
    EmbeddedSpan {
        span_id: e.event.span_id.as_str(),
        parent_span_id: e.event.parent_span_id.as_deref(),
        service: e.event.service.as_ref(),
        endpoint: e.event.source.endpoint.as_str(),
        event_type: match e.event.event_type {
            EventType::Sql => "sql",
            EventType::HttpOut => "http_out",
        },
        operation: e.event.operation.as_str(),
        target: e.event.target.as_str(),
        template: e.template.as_ref(),
        duration_us: e.event.duration_us,
        status_code: e.event.status_code,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::correlate::Trace;
    use crate::detect::{Confidence, Finding, FindingType, Pattern, Severity};
    use crate::event::{EventSource, EventType, SpanEvent};
    use crate::ingest::IngestSource;
    use crate::normalize::NormalizedEvent;
    use crate::report::interpret::InterpretationLevel;
    use crate::report::{Analysis, GreenSummary, QualityGate, Report, TopOffender};

    fn span(
        trace_id: &str,
        span_id: &str,
        parent: Option<&str>,
        service: &str,
        endpoint: &str,
        template: &str,
    ) -> NormalizedEvent {
        NormalizedEvent {
            event: SpanEvent {
                timestamp: "2026-04-21T00:00:00Z".into(),
                trace_id: trace_id.into(),
                span_id: span_id.into(),
                parent_span_id: parent.map(ToString::to_string),
                service: service.into(),
                cloud_region: None,
                event_type: EventType::Sql,
                operation: "SELECT".into(),
                target: template.into(),
                duration_us: 1200,
                source: EventSource {
                    endpoint: endpoint.into(),
                    method: "get".into(),
                },
                status_code: None,
                response_size_bytes: None,
                code_function: None,
                code_filepath: None,
                code_lineno: None,
                code_namespace: None,
                instrumentation_scopes: Vec::new(),
            },
            template: template.into(),
            params: vec![],
        }
    }

    fn finding(trace_id: &str, service: &str, endpoint: &str, template: &str) -> Finding {
        Finding {
            finding_type: FindingType::NPlusOneSql,
            severity: Severity::Critical,
            trace_id: trace_id.into(),
            service: service.into(),
            source_endpoint: endpoint.into(),
            pattern: Pattern {
                template: template.into(),
                occurrences: 12,
                window_ms: 100,
                distinct_params: 12,
                ..Default::default()
            },
            suggestion: "use JOIN FETCH".into(),
            first_timestamp: "2026-04-21T00:00:00Z".into(),
            last_timestamp: "2026-04-21T00:00:01Z".into(),
            green_impact: None,
            confidence: Confidence::CiBatch,
            classification_method: None,
            code_location: None,
            instrumentation_scopes: Vec::new(),
            suggested_fix: None,
            signature: String::new(),
        }
    }

    fn minimal_report(findings: Vec<Finding>) -> Report {
        Report {
            analysis: Analysis {
                duration_ms: 10,
                events_processed: 1,
                traces_analyzed: 1,
            },
            findings,
            green_summary: GreenSummary {
                total_io_ops: 10,
                avoidable_io_ops: 4,
                io_waste_ratio: 0.4,
                io_waste_ratio_band: InterpretationLevel::Moderate,
                top_offenders: vec![TopOffender {
                    endpoint: "/api/orders".into(),
                    service: "order-svc".into(),
                    io_intensity_score: 6.4,
                    io_intensity_band: InterpretationLevel::High,
                    co2_grams: Some(0.000_050),
                }],
                ..GreenSummary::disabled(0)
            },
            quality_gate: QualityGate {
                passed: true,
                rules: vec![],
            },
            per_endpoint_io_ops: vec![],
            correlations: vec![],
            warnings: vec![],
            warning_details: vec![],
            acknowledged_findings: vec![],
            binary_version: String::new(),
            disclosure_waste: None,
        }
    }

    fn opts(label: &str, cap: Option<usize>) -> RenderOptions {
        RenderOptions {
            input_label: label.into(),
            max_traces_embedded: cap,
            pg_stat: None,
            diff: None,
            daemon_url: None,
        }
    }

    #[test]
    fn renders_minimal_report_to_valid_html() {
        // Load the shared raw-trace fixture, run the pipeline, render.
        // Exercises end-to-end at the crate boundary without needing
        // the CLI binary. The fixture is deterministic: two findings
        // (one N+1 SQL, one redundant SQL) on a single trace.
        let path = format!(
            "{}/../../tests/fixtures/report_minimal.json",
            env!("CARGO_MANIFEST_DIR")
        );
        let raw = std::fs::read(&path).expect("fixture readable");
        let cfg = crate::config::Config::default();
        let events = crate::ingest::json::JsonIngest::new(cfg.daemon.max_payload_size)
            .ingest(&raw)
            .expect("fixture parses");
        let (report, traces) = crate::pipeline::analyze_with_traces(events, &cfg);

        assert_eq!(report.findings.len(), 3, "fixture must yield 3 findings");
        let types: std::collections::BTreeSet<FindingType> = report
            .findings
            .iter()
            .map(|f| f.finding_type.clone())
            .collect();
        let expected: std::collections::BTreeSet<FindingType> = [
            FindingType::NPlusOneSql,
            FindingType::RedundantSql,
            FindingType::SerializedCalls,
        ]
        .into_iter()
        .collect();
        assert_eq!(
            types, expected,
            "minimal fixture must produce one of each type"
        );

        let (html, _) = render(&report, &traces, &opts("report_minimal.json", None));
        assert!(html.starts_with("<!DOCTYPE html>"));
        assert!(html.contains(r#"<script id="report-data""#));
        assert!(html.contains("trace-report-minimal"));
        assert!(html.contains("order-svc"));
    }

    #[test]
    fn quality_gate_rules_scaffold_and_csv_confidence_present() {
        let report = minimal_report(vec![]);
        let (html, _) = render(&report, &[], &opts("traces.json", None));

        assert!(
            html.contains(r#"id="quality-gate-rules""#),
            "Findings tab must carry the quality gate rules host"
        );
        assert!(
            html.contains("renderQualityGateRules"),
            "renderAllPanels must call renderQualityGateRules"
        );
        // Anchor on the preceding CSV column to distinguish the header
        // array from any other `confidence` mention in the payload.
        assert!(
            html.contains(r#""suggested_fix_recommendation","#) && html.contains(r#""confidence""#),
            "Findings CSV header must include confidence after suggested_fix_recommendation"
        );
    }

    #[test]
    fn escapes_closing_script_tag_in_embedded_json() {
        let hostile = "</script><img src=x onerror=alert(1)>";
        let f = finding("t1", "svc", "/ep", hostile);
        let report = minimal_report(vec![f]);
        let trace = Trace {
            trace_id: "t1".into(),
            spans: vec![span("t1", "s1", None, "svc", "/ep", hostile)],
        };
        let (html, _) = render(&report, &[trace], &opts("-", None));
        // The raw closing tag must not appear anywhere in the payload.
        // Count the occurrences in the entire document: the static shell
        // has one (`</script>` closing the JSON block) and one (`</script>`
        // closing the app JS), so the total must be exactly 2.
        assert_eq!(
            html.matches("</script>").count(),
            2,
            "user-controlled </script> leaked into the document"
        );
        // And the escaped form must appear (proof that the hostile
        // string survived as data, not as markup).
        assert!(html.contains("<\\/script>"));

        // The JSON payload must still round-trip cleanly.
        let start = html.find("<script id=\"report-data\"").expect("script tag");
        let open = html[start..]
            .find('>')
            .expect("script open")
            .saturating_add(1);
        let rest = &html[start + open..];
        let end = rest.find("</script>").expect("script close");
        let json_blob = rest[..end].trim().replace("<\\/", "</");
        let value: serde_json::Value =
            serde_json::from_str(&json_blob).expect("JSON blob parses after <\\/ reversal");
        let finding_tpl = value["report"]["findings"][0]["pattern"]["template"]
            .as_str()
            .expect("template present");
        assert_eq!(finding_tpl, hostile);
    }

    #[test]
    fn escapes_adversarial_control_chars() {
        // Null byte, low control char, DEL, and a 4-byte emoji at a
        // string boundary. serde_json must produce a JSON-safe encoding
        // that parses back losslessly.
        let weird = "a\0b\x01c\x7fd\u{1F600}";
        let f = finding("t1", "svc", "/ep", weird);
        let report = minimal_report(vec![f]);
        let (html, _) = render(&report, &[], &opts("traces.json", None));

        let start = html.find("<script id=\"report-data\"").expect("script tag");
        let open = html[start..]
            .find('>')
            .expect("script open")
            .saturating_add(1);
        let rest = &html[start + open..];
        let end = rest.find("</script>").expect("script close");
        let json_blob = rest[..end].trim().replace("<\\/", "</");
        let value: serde_json::Value = serde_json::from_str(&json_blob).expect("JSON round-trips");
        assert_eq!(
            value["report"]["findings"][0]["pattern"]["template"]
                .as_str()
                .unwrap(),
            weird
        );
    }

    #[test]
    fn applies_max_traces_embedded_cap_via_top_waste_fallback() {
        // 100 synthetic traces, one finding per trace, cap = 10.
        let mut findings = Vec::new();
        let mut traces = Vec::new();
        let mut offenders = Vec::new();
        for i in 0..100 {
            let tid = format!("t{i:03}");
            let svc = format!("svc-{i}");
            let ep = format!("/ep-{i}");
            let tpl = format!("SELECT * FROM t{i} WHERE id = ?");
            findings.push(finding(&tid, &svc, &ep, &tpl));
            traces.push(Trace {
                trace_id: tid.clone(),
                spans: vec![span(&tid, "s", None, &svc, &ep, &tpl)],
            });
            // Feed top_offenders so every trace has a rank (no
            // usize::MAX ties that would leave ordering unspecified).
            offenders.push(TopOffender {
                endpoint: ep.clone(),
                service: svc.clone(),
                io_intensity_score: 100.0 - f64::from(i),
                io_intensity_band: InterpretationLevel::High,
                co2_grams: None,
            });
        }
        let mut report = minimal_report(findings);
        report.green_summary.top_offenders = offenders;

        let (html, stats) = render(&report, &traces, &opts("-", Some(10)));
        let json_blob = extract_payload_json(&html);
        let value: serde_json::Value = serde_json::from_str(&json_blob).unwrap();
        let embedded = value["embedded_traces"].as_array().expect("array");
        assert_eq!(embedded.len(), 10, "exactly 10 traces kept");
        let summary = &value["trimmed_traces"];
        assert_eq!(summary["kept"].as_u64().unwrap(), 10);
        assert_eq!(summary["total"].as_u64().unwrap(), 100);
        assert_eq!(stats.kept, 10);
        assert_eq!(stats.total, 100);
    }

    #[test]
    fn oversized_findings_are_trimmed_critical_first() {
        // Enough large findings to blow the findings budget: ~3000
        // findings with 4 KB templates is ~12 MB of findings JSON
        // against a ~3.5 MB findings budget.
        let big_template = format!("SELECT * FROM t WHERE x = '{}'", "p".repeat(4096));
        let mut findings = Vec::new();
        for i in 0..3000 {
            let mut f = finding(&format!("t{i:04}"), "svc", "/ep", &big_template);
            // Interleave severities: the trim must keep critical first.
            f.severity = match i % 3 {
                0 => Severity::Critical,
                1 => Severity::Warning,
                _ => Severity::Info,
            };
            findings.push(f);
        }
        let report = minimal_report(findings);

        let (html, _) = render(&report, &[], &opts("-", None));
        assert!(
            html.len() <= DEFAULT_SIZE_TARGET_BYTES + 512 * 1024,
            "html is {} bytes, expected near the {} target",
            html.len(),
            DEFAULT_SIZE_TARGET_BYTES
        );
        let json_blob = extract_payload_json(&html);
        let value: serde_json::Value = serde_json::from_str(&json_blob).unwrap();
        let summary = &value["trimmed_findings"];
        let kept = summary["kept"].as_u64().expect("kept") as usize;
        assert_eq!(summary["total"].as_u64().unwrap(), 3000);
        assert!(kept > 0 && kept < 3000, "kept {kept} of 3000");
        // Critical-first: every kept finding must be critical, because
        // the 1000 critical findings alone exceed the budget.
        let embedded = value["report"]["findings"].as_array().expect("findings");
        assert_eq!(embedded.len(), kept);
        assert!(
            embedded
                .iter()
                .all(|f| f["severity"].as_str() == Some("critical")),
            "trim must keep critical findings first"
        );
    }

    #[test]
    fn per_endpoint_io_ops_dropped_from_embed() {
        // The dashboard never reads per_endpoint_io_ops, so it must not
        // ship in the embedded payload regardless of cardinality. The
        // JSON report (analyze --format json) keeps it; this only asserts
        // the HTML embed.
        use crate::report::PerEndpointIoOps;
        let mut report = minimal_report(vec![finding("t0", "svc", "/ep", "SELECT 1")]);
        report.per_endpoint_io_ops = (0..5000)
            .map(|i| PerEndpointIoOps {
                service: format!("svc-{i}"),
                endpoint: format!("/ep-{i}"),
                io_ops: i,
            })
            .collect();

        let (html, _) = render(&report, &[], &opts("-", None));
        let value: serde_json::Value = serde_json::from_str(&extract_payload_json(&html)).unwrap();
        let embedded = &value["report"]["per_endpoint_io_ops"];
        let len = embedded.as_array().map_or(0, Vec::len);
        assert_eq!(
            len, 0,
            "per_endpoint_io_ops must not be embedded, got {len}"
        );
    }

    #[test]
    fn top_offenders_capped_in_embed_but_full_ranking_preserved() {
        // 40 offenders (ranks 0..40); the embed cap is 25. Two candidate
        // traces: one whose endpoint is offender rank 30 (beyond the cap)
        // and one whose endpoint is not an offender at all (rank MAX).
        let mut offenders = Vec::new();
        for i in 0..40 {
            offenders.push(TopOffender {
                endpoint: format!("/ep-{i}"),
                service: "svc".into(),
                io_intensity_score: 100.0 - f64::from(i),
                io_intensity_band: InterpretationLevel::High,
                co2_grams: None,
            });
        }
        let findings = vec![
            finding("t-beyond", "svc", "/ep-30", "SELECT 1"),
            finding("t-none", "svc", "/ep-absent", "SELECT 2"),
        ];
        let mut report = minimal_report(findings);
        report.green_summary.top_offenders = offenders;
        // t-none first on purpose: if ranking wrongly used the capped
        // list, both traces would rank usize::MAX and the stable sort
        // would keep input order, embedding t-none and failing the
        // assertion below. With t-beyond first, the regression would be
        // invisible.
        let traces = vec![
            Trace {
                trace_id: "t-none".into(),
                spans: vec![span("t-none", "s", None, "svc", "/ep-absent", "SELECT 2")],
            },
            Trace {
                trace_id: "t-beyond".into(),
                spans: vec![span("t-beyond", "s", None, "svc", "/ep-30", "SELECT 1")],
            },
        ];

        // Cap embedding at 1 trace: only the better-ranked one survives.
        let (html, _) = render(&report, &traces, &opts("-", Some(1)));
        let value: serde_json::Value = serde_json::from_str(&extract_payload_json(&html)).unwrap();

        let embedded_offenders = value["report"]["green_summary"]["top_offenders"]
            .as_array()
            .expect("top_offenders array");
        assert_eq!(
            embedded_offenders.len(),
            TOP_OFFENDERS_EMBED_CAP,
            "top_offenders must be capped in the embed"
        );

        let embedded_traces = value["embedded_traces"].as_array().expect("traces");
        assert_eq!(embedded_traces.len(), 1);
        assert_eq!(
            embedded_traces[0]["trace_id"].as_str(),
            Some("t-beyond"),
            "ranking must use the full offender list: rank-30 beats a non-offender, \
             which only holds if ranking read past the embed cap"
        );
    }

    #[test]
    fn explicit_trace_cap_keeps_findings_whole() {
        let big_template = format!("SELECT * FROM t WHERE x = '{}'", "p".repeat(4096));
        let findings: Vec<Finding> = (0..2000)
            .map(|i| finding(&format!("t{i:04}"), "svc", "/ep", &big_template))
            .collect();
        let report = minimal_report(findings);
        // --max-traces-embedded opts out of size targeting entirely.
        let (html, _) = render(&report, &[], &opts("-", Some(5)));
        let json_blob = extract_payload_json(&html);
        let value: serde_json::Value = serde_json::from_str(&json_blob).unwrap();
        assert!(value.get("trimmed_findings").is_none());
        assert_eq!(value["report"]["findings"].as_array().unwrap().len(), 2000);
    }

    #[test]
    fn render_stats_match_total_when_no_trim() {
        let mut findings = Vec::new();
        let mut traces = Vec::new();
        for i in 0..3 {
            let tid = format!("t{i}");
            let svc = format!("svc-{i}");
            let ep = format!("/ep-{i}");
            let tpl = format!("SELECT * FROM t{i} WHERE id = ?");
            findings.push(finding(&tid, &svc, &ep, &tpl));
            traces.push(Trace {
                trace_id: tid.clone(),
                spans: vec![span(&tid, "s", None, &svc, &ep, &tpl)],
            });
        }
        let report = minimal_report(findings);
        let (_, stats) = render(&report, &traces, &opts("-", None));
        assert_eq!(stats.kept, stats.total);
        assert_eq!(stats.kept, 3);
    }

    #[test]
    fn omits_greenops_section_when_green_disabled() {
        // A GreenSummary where `co2` is None (green scoring disabled)
        // must hide the GreenOps tab on the client side. We verify by
        // asserting the payload reflects the disabled state; the JS
        // bootstrap checks `report.green_summary.co2` to decide tab
        // visibility.
        let f = finding("t1", "svc", "/ep", "SELECT * FROM t");
        let mut report = minimal_report(vec![f.clone()]);
        report.green_summary = GreenSummary::disabled(1);
        let trace = Trace {
            trace_id: "t1".into(),
            spans: vec![span("t1", "s1", None, "svc", "/ep", "SELECT * FROM t")],
        };
        let (html, _) = render(&report, &[trace], &opts("-", None));
        let json_blob = extract_payload_json(&html);
        let value: serde_json::Value = serde_json::from_str(&json_blob).unwrap();
        assert!(
            value["report"]["green_summary"]["co2"].is_null()
                || value["report"]["green_summary"].get("co2").is_none(),
            "co2 must be absent when green disabled"
        );
        // Sanity: the static panel-green scaffolding is in the template
        // (starts hidden via inline style), and the JS only reveals it
        // when co2 is present. We assert the template still has the
        // scaffolding (regression guard) but not that the client
        // *shows* it (that's a browser-level assertion).
        assert!(html.contains(r#"id="panel-green""#));
    }

    #[test]
    fn no_forbidden_apis_in_template() {
        let forbidden = [
            ".innerHTML",
            ".outerHTML",
            "insertAdjacentHTML",
            "document.write",
            "eval(",
            "new Function(",
            // Attribute-sink parsers. `DOMParser().parseFromString(x,
            // "text/html")` and `Range.createContextualFragment(x)`
            // both interpret their argument as HTML, providing a path
            // around the textContent-only invariant.
            "DOMParser(",
            "createContextualFragment(",
            // We intentionally omit a bare `Function(` check: the string
            // "function (" appears many times as IIFE / callback syntax.
            // `new Function(` is the only constructor shape that
            // executes a string as code, a literal `Function(` without
            // `new` would need `window.Function(` to be callable, which
            // is caught by the same `Function(` heuristic below.
        ];
        for needle in forbidden {
            assert!(
                !TEMPLATE.contains(needle),
                "template contains forbidden API: {needle}"
            );
        }
        // Guard against the two spellings of the string-exec
        // constructor that don't start with `new `.
        assert!(!TEMPLATE.contains("window.Function("));
        assert!(!TEMPLATE.contains("globalThis.Function("));
        // Attribute-name-based event handler injection. A call like
        // `el.setAttribute("onclick", "alert(1)")` is equivalent to
        // writing `innerHTML` with an inline handler: the browser
        // compiles the attribute string as JS. Reject any
        // `setAttribute(` whose first argument starts with `"on` or
        // `'on`, regardless of whitespace around the paren. We strip
        // whitespace entirely so a reformat cannot dodge the check.
        let no_ws: String = TEMPLATE.chars().filter(|c| !c.is_whitespace()).collect();
        assert!(
            !no_ws.contains("setAttribute(\"on"),
            "template contains forbidden attribute-sink: setAttribute(\"on*\", ...)"
        );
        assert!(
            !no_ws.contains("setAttribute('on"),
            "template contains forbidden attribute-sink: setAttribute('on*', ...)"
        );
    }

    /// Find an `on*=` event-handler attribute in raw SVG markup. An attribute
    /// name follows whitespace in well-formed markup, so scan forward from each
    /// whitespace boundary: a letter run starting with `on` followed by `=`
    /// (whitespace allowed before the `=`) is a handler. Scanning from the
    /// boundary avoids fusing a tag name into a following first attribute, the
    /// `<svg onload=...>` case a whitespace-stripping scan would miss.
    fn svg_event_handler(svg: &str) -> Option<String> {
        let lower = svg.to_ascii_lowercase();
        let bytes = lower.as_bytes();
        for k in 0..bytes.len() {
            if !bytes[k].is_ascii_whitespace() {
                continue;
            }
            let start = k + 1;
            let mut p = start;
            while p < bytes.len() && bytes[p].is_ascii_alphabetic() {
                p += 1;
            }
            let attr = &lower[start..p];
            if attr.len() <= 2 || !attr.starts_with("on") {
                continue;
            }
            let mut q = p;
            while q < bytes.len() && bytes[q].is_ascii_whitespace() {
                q += 1;
            }
            if q < bytes.len() && bytes[q] == b'=' {
                return Some(attr.to_string());
            }
        }
        None
    }

    #[test]
    fn brand_svgs_have_no_active_content() {
        // The brand SVGs are injected verbatim into the report body and ship
        // in every render under a CSP that allows inline scripts, so a
        // re-exported logo carrying active content would execute. Guard the
        // embedded assets the way `no_forbidden_apis_in_template` guards the
        // template (which only scans TEMPLATE, not these constants).
        for (name, svg) in [
            ("BRAND_LOGO_LIGHT_SVG", BRAND_LOGO_LIGHT_SVG),
            ("BRAND_LOGO_DARK_SVG", BRAND_LOGO_DARK_SVG),
        ] {
            let lower = svg.to_ascii_lowercase();
            for needle in ["<script", "javascript:", "<foreignobject", "<iframe"] {
                assert!(
                    !lower.contains(needle),
                    "{name} contains disallowed active content: {needle}"
                );
            }
            assert!(
                svg_event_handler(svg).is_none(),
                "{name} contains a forbidden event-handler attribute: {:?}",
                svg_event_handler(svg)
            );
        }
    }

    #[test]
    fn svg_event_handler_scan_catches_first_attribute() {
        // The common XSS form is a handler as the first attribute of an element;
        // the previous whitespace-stripping scan fused the tag name and missed it.
        assert_eq!(
            svg_event_handler(r#"<svg onload="x">"#).as_deref(),
            Some("onload")
        );
        assert_eq!(
            svg_event_handler(r#"<rect onclick="x"/>"#).as_deref(),
            Some("onclick")
        );
        assert_eq!(
            svg_event_handler(r#"<svg width="1" onerror="x">"#).as_deref(),
            Some("onerror")
        );
        assert_eq!(
            svg_event_handler("<svg onload =\"x\">").as_deref(),
            Some("onload")
        );
        // Benign attributes and `on...=` substrings inside values must not trip it.
        assert!(svg_event_handler(r#"<svg width="10" viewBox="0 0 1 1">"#).is_none());
        assert!(svg_event_handler(r#"<a href="https://x/?online=1">"#).is_none());
    }

    /// Visual validation artifact for the 0.5.10 estimation surface.
    /// Loads the 3-state Region fixture, renders the HTML to
    /// `/tmp/perf-sentinel-0.5.10-validation.html`, and exits. Marked
    /// `#[ignore]` so it does not run in CI: the goal is a manual
    /// visual check via the user's browser, not an automated assertion.
    /// Run with `cargo test --release validation_html_for_three_estimation_states -- --ignored --nocapture`.
    #[test]
    #[ignore = "manual visual validation artifact, not run in CI"]
    fn validation_html_for_three_estimation_states() {
        let fixture_path = format!(
            "{}/../../tests/fixtures/report_three_estimation_states.json",
            env!("CARGO_MANIFEST_DIR")
        );
        let raw = std::fs::read_to_string(&fixture_path).expect("fixture readable");
        let report: Report = serde_json::from_str(&raw).expect("fixture parses as Report");
        let traces: Vec<Trace> = vec![];
        let (html, _) = render(
            &report,
            &traces,
            &opts("report_three_estimation_states.json", None),
        );
        let out = "/tmp/perf-sentinel-0.5.10-validation.html";
        std::fs::write(out, &html).expect("/tmp writable");
        eprintln!(
            "Wrote {} bytes to {out} for visual validation. Open in a browser.",
            html.len()
        );
    }

    /// Visual validation artifact for the 0.5.12 scoring config surface.
    /// Loads the 3-state Region fixture (so the `GreenOps` tab renders
    /// with populated `co2` + `regions`), injects 3 different
    /// `scoring_config` shapes (V4 defaults, V3 legacy, all opt-ins),
    /// and writes each to a stand-alone HTML file under
    /// `/tmp/perf-sentinel-0.5.12-*.html`. Marked `#[ignore]` so it
    /// does not run in CI: the goal is a manual visual check via the
    /// user's browser. Run with
    /// `cargo test --release validation_html_for_scoring_config -- --ignored --nocapture`.
    #[test]
    #[ignore = "manual visual validation artifact, not run in CI"]
    fn validation_html_for_scoring_config() {
        use crate::score::carbon::ScoringConfig;
        use crate::score::electricity_maps::config::{
            ApiVersion, EmissionFactorType, TemporalGranularity,
        };
        let cases = [
            ("v4-defaults", ScoringConfig::default()),
            (
                "v3-legacy",
                ScoringConfig {
                    api_version: ApiVersion::V3,
                    ..ScoringConfig::default()
                },
            ),
            (
                "all-optins",
                ScoringConfig {
                    api_version: ApiVersion::V4,
                    emission_factor_type: EmissionFactorType::Direct,
                    temporal_granularity: TemporalGranularity::FifteenMinutes,
                },
            ),
        ];
        let fixture_path = format!(
            "{}/../../tests/fixtures/report_three_estimation_states.json",
            env!("CARGO_MANIFEST_DIR")
        );
        let raw = std::fs::read_to_string(&fixture_path).expect("fixture readable");
        let traces: Vec<Trace> = vec![];
        for (slug, scoring) in cases {
            let mut report: Report = serde_json::from_str(&raw).expect("fixture parses as Report");
            report.green_summary.scoring_config = Some(scoring);
            let (html, _) = render(
                &report,
                &traces,
                &opts(&format!("scoring-config-{slug}"), None),
            );
            let out = format!("/tmp/perf-sentinel-0.5.12-{slug}.html");
            std::fs::write(&out, &html).expect("/tmp writable");
            eprintln!("Wrote {} bytes to {out}", html.len());
        }
    }

    #[test]
    fn template_carries_scoring_config_bandeau_and_helpers() {
        // Locks in the 0.5.12 dashboard surface for the
        // `green_summary.scoring_config` field. The chip rendering is
        // exercised manually via the browser-validation helper above
        // (no JSDOM in the test suite), this assertion guards against
        // accidental removal of the bandeau plumbing.
        for needle in [
            "id=\"green-scoring-config\"",
            "ps-scoring-bandeau",
            "ps-scoring-chip-neutral",
            "ps-scoring-chip-warning",
            "ps-scoring-chip-accent",
            "function renderScoringConfigBandeau",
            "function buildApiVersionChip",
            "function buildEmissionFactorChip",
            "function buildTemporalGranularityChip",
        ] {
            assert!(
                TEMPLATE.contains(needle),
                "template missing scoring_config plumbing: `{needle}`"
            );
        }
    }

    #[test]
    fn template_carries_estimated_column_and_helper() {
        // Locks in the 0.5.10 dashboard surface for the
        // `intensity_estimated` / `intensity_estimation_method` fields.
        // The actual JS-rendered cell is exercised manually via
        // browser validation (no JSDOM in the test suite).
        for needle in [
            "<th>Estimated</th>",
            "function buildEstimatedCell",
            "ps-badge-estimated",
            "ps-badge-measured",
        ] {
            assert!(
                TEMPLATE.contains(needle),
                "template missing required 0.5.10 artifact: {needle}"
            );
        }
    }

    /// Description fragments that must appear in the cheatsheet modal.
    /// Each entry is a substring (not an exact line) so minor wording
    /// tweaks around each fragment do not break the test. If you
    /// re-word the user-visible cheatsheet text in the template, update
    /// the corresponding fragment here in the same commit.
    const CHEATSHEET_DESCRIPTION_FRAGMENTS: &[&str] = &[
        "Move finding selection down",
        "Move finding selection up",
        "Open selected finding in Explain",
        "close search",
        "back from Explain",
        "Open filter search for active tab",
        "Go to Findings",
        "Go to Explain",
        "Go to pg_stat",
        "Go to Diff",
        "Go to Correlations",
        "Go to GreenOps",
        "Show this cheatsheet",
    ];

    #[test]
    fn cheatsheet_shortcuts_listed_in_template() {
        // The modal scaffolding must be present...
        assert!(
            TEMPLATE.contains("id=\"cheatsheet\""),
            "cheatsheet modal scaffolding missing"
        );
        assert!(
            TEMPLATE.contains("Keyboard shortcuts"),
            "cheatsheet title missing"
        );
        // ...and every shortcut description must appear. We match the
        // user-visible description rather than the key literal because
        // keys may be rewritten (single vs double quotes, aliasing,
        // reorder) during cosmetic refactors, but descriptions are the
        // contract the user sees and the documentation guarantees.
        for description in CHEATSHEET_DESCRIPTION_FRAGMENTS {
            assert!(
                TEMPLATE.contains(description),
                "cheatsheet missing description fragment: {description:?}"
            );
        }
    }

    #[test]
    fn export_button_rendered_for_listable_tabs_only() {
        // Each listable panel gets its own Export CSV button keyed by
        // `<tab>-export`. Explain and GreenOps stay button-less.
        for tab in ["findings", "pgstat", "diff", "correlations"] {
            let needle = format!("id=\"{tab}-export\"");
            assert!(
                TEMPLATE.contains(&needle),
                "expected export button for listable tab: {tab}"
            );
        }
        // Count-based guard against future drift: every export button
        // carries `data-export-tab="..."`, so the total occurrence
        // count must equal the four listable tabs, no more, no less.
        // This catches both accidental drop (count < 4) and rogue
        // addition to Explain / GreenOps (count > 4) without relying
        // on negative substring matches that could over-match suffixed
        // future IDs like `pre-explain-export`. If a future listable
        // tab lands, update both the positive assertion above and
        // this count in the same commit.
        let export_count = TEMPLATE.matches("data-export-tab=\"").count();
        assert_eq!(
            export_count, 4,
            "expected exactly 4 export buttons (findings, pgstat, diff, correlations), found {export_count}. \
             If you added a new listable tab, update this assertion and the positive loop above."
        );
        // The CSS class backing every export button must also exist.
        assert!(
            TEMPLATE.contains(".ps-export-btn"),
            ".ps-export-btn CSS class missing"
        );
    }

    // CSV escape correctness is verified end-to-end in
    // crates/sentinel-cli/tests/browser/tests/dashboard.spec.ts,
    // where the JS csvEscape runs in a real browser. The hand-written
    // Rust twin was removed to avoid drift between the two
    // implementations.

    #[test]
    fn sessionstorage_access_is_guarded_by_try_catch() {
        // Load-bearing invariant: the two wrapper functions exist,
        // every caller inherits their guard. A refactor that removes
        // or renames the wrappers trips this check immediately.
        assert!(
            TEMPLATE.contains("function sessionGet("),
            "sessionGet helper missing"
        );
        assert!(
            TEMPLATE.contains("function sessionSet("),
            "sessionSet helper missing"
        );
        // Structural check: every raw `sessionStorage.{get,set}Item`
        // access must appear inside a function body whose nearest
        // enclosing block carries `try { ... } catch`. We locate each
        // occurrence and scan backwards up to 5 lines for a `try {`
        // opener. If the scan fails to find one, the access is
        // considered unguarded.
        let lines: Vec<&str> = TEMPLATE.lines().collect();
        let mut hits = 0;
        for (idx, line) in lines.iter().enumerate() {
            let touches =
                line.contains("sessionStorage.getItem") || line.contains("sessionStorage.setItem");
            if !touches {
                continue;
            }
            hits += 1;
            let start = idx.saturating_sub(5);
            let window_has_try = lines[start..=idx].iter().any(|l| l.contains("try {"));
            assert!(
                window_has_try,
                "sessionStorage access on line {} has no `try {{` opener within 5 lines above: {}",
                idx + 1,
                line.trim()
            );
        }
        assert!(
            hits >= 2,
            "expected at least one sessionGet and one sessionSet access, found {hits}"
        );
    }

    /// Extract the raw JSON text from the `<script id="report-data">`
    /// block and un-escape `<\/` back to `</` so it parses as JSON.
    fn extract_payload_json(html: &str) -> String {
        let start = html.find("<script id=\"report-data\"").expect("script tag");
        let open = html[start..]
            .find('>')
            .expect("script open")
            .saturating_add(1);
        let rest = &html[start + open..];
        let end = rest.find("</script>").expect("script close");
        rest[..end].trim().replace("<\\/", "</")
    }

    fn synthetic_pg_stat() -> PgStatReport {
        use crate::ingest::pg_stat::{PgStatEntry, PgStatRanking, PgStatReport};
        let entries = vec![
            PgStatEntry {
                query: "SELECT * FROM order_item WHERE order_id = 42".into(),
                normalized_template: "SELECT * FROM order_item WHERE order_id = ?".into(),
                calls: 120,
                total_exec_time_ms: 840.0,
                mean_exec_time_ms: 7.0,
                rows: 500,
                shared_blks_hit: 1000,
                shared_blks_read: 0,
                seen_in_traces: true,
            },
            PgStatEntry {
                query: "SELECT id FROM orders WHERE id = 7".into(),
                normalized_template: "SELECT id FROM orders WHERE id = ?".into(),
                calls: 30,
                total_exec_time_ms: 60.0,
                mean_exec_time_ms: 2.0,
                rows: 30,
                shared_blks_hit: 120,
                shared_blks_read: 0,
                seen_in_traces: false,
            },
        ];
        PgStatReport {
            total_entries: 2,
            top_n: 2,
            rankings: vec![PgStatRanking {
                label: "top by total_exec_time".into(),
                entries,
            }],
        }
    }

    #[test]
    fn embeds_pg_stat_when_provided() {
        let f = finding("t1", "svc", "/ep", "SELECT * FROM t");
        let report = minimal_report(vec![f]);
        let mut options = opts("-", None);
        options.pg_stat = Some(synthetic_pg_stat());
        let (html, _) = render(&report, &[], &options);
        let blob = extract_payload_json(&html);
        let value: serde_json::Value = serde_json::from_str(&blob).unwrap();
        let entries = value["pg_stat"]["rankings"][0]["entries"]
            .as_array()
            .expect("entries array");
        assert_eq!(entries.len(), 2);
        assert_eq!(
            entries[0]["normalized_template"].as_str().unwrap(),
            "SELECT * FROM order_item WHERE order_id = ?"
        );
    }

    #[test]
    fn omits_pg_stat_when_absent() {
        let f = finding("t1", "svc", "/ep", "SELECT * FROM t");
        let report = minimal_report(vec![f]);
        let (html, _) = render(&report, &[], &opts("-", None));
        let blob = extract_payload_json(&html);
        let value: serde_json::Value = serde_json::from_str(&blob).unwrap();
        assert!(
            value.get("pg_stat").is_none(),
            "pg_stat must be absent when not provided (skip_serializing_if)"
        );
        // The static panel-pgstat scaffolding stays in the template; the
        // JS hides it at runtime based on payload presence. Assert the
        // scaffolding is there so the cross-nav wiring has an anchor to
        // reach even before the tab is registered.
        assert!(html.contains(r#"id="panel-pgstat""#));
    }

    #[test]
    fn embeds_diff_report_when_before_provided() {
        // before: 1 finding. after: 2 findings (same first one + one new).
        let before_finding = finding("t1", "svc", "/ep", "SELECT * FROM t");
        let before = minimal_report(vec![before_finding.clone()]);
        let after_extra = finding("t2", "svc", "/ep2", "SELECT * FROM u");
        let after = minimal_report(vec![before_finding, after_extra]);

        let diff = crate::diff::diff_runs(&before, &after);
        let mut options = opts("-", None);
        options.diff = Some(diff);
        let (html, _) = render(&after, &[], &options);
        let blob = extract_payload_json(&html);
        let value: serde_json::Value = serde_json::from_str(&blob).unwrap();
        let new = value["diff"]["new_findings"].as_array().expect("new array");
        assert_eq!(new.len(), 1, "one new finding introduced in 'after'");
        let resolved = value["diff"]["resolved_findings"]
            .as_array()
            .expect("resolved array");
        assert_eq!(resolved.len(), 0, "nothing was removed");
    }

    #[test]
    fn omits_diff_when_absent() {
        let f = finding("t1", "svc", "/ep", "SELECT * FROM t");
        let report = minimal_report(vec![f]);
        let (html, _) = render(&report, &[], &opts("-", None));
        let blob = extract_payload_json(&html);
        let value: serde_json::Value = serde_json::from_str(&blob).unwrap();
        assert!(value.get("diff").is_none());
        assert!(html.contains(r#"id="panel-diff""#));
    }

    #[test]
    fn cross_nav_pgstat_link_added_only_when_pg_stat_present() {
        // Build a trace whose SQL span's normalized template matches a
        // pg_stat row. The ps-span-pgstat-link class is added by the JS
        // at render time, not by the Rust sink; what we verify here is
        // that the Rust payload carries everything the JS needs for the
        // link to fire, i.e. a `pg_stat` section with the same
        // `normalized_template` the span carries.
        let tpl = "SELECT * FROM order_item WHERE order_id = ?";
        let f = finding("abc", "svc", "/ep", tpl);
        let report = minimal_report(vec![f]);
        let trace = Trace {
            trace_id: "abc".into(),
            spans: vec![span("abc", "s1", None, "svc", "/ep", tpl)],
        };

        // With pg_stat: the template appears in both the span list and
        // the pg_stat rankings.
        let mut with_pg = opts("-", None);
        with_pg.pg_stat = Some(synthetic_pg_stat());
        let (html_with, _) = render(&report, std::slice::from_ref(&trace), &with_pg);
        let blob_with = extract_payload_json(&html_with);
        let v_with: serde_json::Value = serde_json::from_str(&blob_with).unwrap();
        let pg_templates: Vec<&str> = v_with["pg_stat"]["rankings"][0]["entries"]
            .as_array()
            .unwrap()
            .iter()
            .map(|e| e["normalized_template"].as_str().unwrap())
            .collect();
        assert!(
            pg_templates.contains(&tpl),
            "pg_stat carries the span template"
        );
        let span_templates: Vec<&str> = v_with["embedded_traces"][0]["spans"]
            .as_array()
            .unwrap()
            .iter()
            .map(|s| s["template"].as_str().unwrap())
            .collect();
        assert!(
            span_templates.contains(&tpl),
            "trace carries the same template"
        );

        // The template file also carries the ps-span-pgstat-link class
        // (the JS adds it to rows with matching templates). The grep is
        // on the static template, not on the per-render output, since
        // class assignment happens at DOM construction time in the JS.
        assert!(
            TEMPLATE.contains("ps-span-pgstat-link"),
            "template contains the cross-nav class"
        );

        // Without pg_stat: the embedded JSON has no pg_stat key, so
        // `hasPgStat` in the JS is false and no cross-nav handler ever
        // attaches.
        let without_pg = opts("-", None);
        let (html_without, _) = render(&report, &[trace], &without_pg);
        let blob_without = extract_payload_json(&html_without);
        let v_without: serde_json::Value = serde_json::from_str(&blob_without).unwrap();
        assert!(v_without.get("pg_stat").is_none());
    }

    #[test]
    fn pg_stat_sub_switcher_exposes_all_ranking_labels() {
        // The sub-switcher is built client-side from `payload.pg_stat.rankings`,
        // so a server-side render on its own does not produce the chip
        // <button> elements. What we assert here is the contract the JS
        // depends on: the static template still carries the four human
        // labels, the sub-switcher sets `data-ranking-index` via
        // `setAttribute` (not as an inline HTML attribute), and the
        // payload exposes all four rankings in the stable order.
        let labels = [
            "\"Total time\"",
            "\"Calls\"",
            "\"Mean time\"",
            "\"I/O blocks\"",
        ];
        for needle in labels {
            assert!(
                TEMPLATE.contains(needle),
                "template is missing sub-switcher label {needle}"
            );
        }
        // `data-ranking-index` must only appear via `setAttr(..., "data-ranking-index", ...)`.
        // A literal HTML attribute `data-ranking-index="..."` would bypass
        // textContent-only guarantees for attributes carrying dynamic data,
        // so guard against it.
        assert!(
            TEMPLATE.contains("\"data-ranking-index\""),
            "setAttr path must use the attribute name as a string literal"
        );
        assert!(
            !TEMPLATE.contains("data-ranking-index=\""),
            "template must not hard-code a literal data-ranking-index attribute"
        );

        // Payload exposes all four rankings when a full PgStatReport is
        // embedded. Verify against the real `rank_pg_stat` output rather
        // than a hand-built synthetic, so test output matches production.
        let entries = crate::ingest::pg_stat::parse_pg_stat(
            b"query,calls,total_exec_time,mean_exec_time,rows,shared_blks_hit,shared_blks_read\n\
              SELECT a FROM t1,10,100.0,10.0,10,20,5\n\
              SELECT b FROM t2,20,50.0,2.5,20,100,0\n\
              SELECT c FROM t3,5,200.0,40.0,5,200,50\n",
            1_048_576,
        )
        .expect("fixture parses");
        let pg_stat = crate::ingest::pg_stat::rank_pg_stat(&entries, 10);
        let f = finding("t1", "svc", "/ep", "SELECT * FROM t");
        let report = minimal_report(vec![f]);
        let mut options = opts("-", None);
        options.pg_stat = Some(pg_stat);
        let (html, _) = render(&report, &[], &options);
        let blob = extract_payload_json(&html);
        let value: serde_json::Value = serde_json::from_str(&blob).unwrap();
        let rankings = value["pg_stat"]["rankings"].as_array().unwrap();
        assert_eq!(rankings.len(), 4, "payload carries all four rankings");
        assert_eq!(
            rankings[0]["label"].as_str().unwrap(),
            "top by total_exec_time"
        );
        assert_eq!(
            rankings[3]["label"].as_str().unwrap(),
            "top by shared_blks_total"
        );
    }

    #[test]
    fn theme_mode_defaults_to_auto_with_tri_state_cycle() {
        // New sessions must default to "auto" (follows OS preference).
        // Assert via the source strings that make up the cycle: the
        // modes array, the matchMedia wiring, and the cycle.
        assert!(
            TEMPLATE.contains("\"auto\", \"dark\", \"light\""),
            "THEME_MODES tri-state ordering must be auto -> dark -> light"
        );
        assert!(
            TEMPLATE.contains("prefers-color-scheme: dark"),
            "matchMedia query for prefers-color-scheme missing"
        );
        assert!(
            TEMPLATE.contains("function applyTheme("),
            "applyTheme helper missing"
        );
        assert!(
            TEMPLATE.contains("function currentThemeMode("),
            "currentThemeMode helper missing"
        );
        // The `<html>` element must not hardcode `data-theme="dark"`
        // anymore, or the OS preference is ignored until JS runs.
        assert!(
            TEMPLATE.contains("data-theme=\"\""),
            "<html> data-theme must start empty so applyTheme runs before paint"
        );
        assert!(
            !TEMPLATE.contains("data-theme=\"dark\">"),
            "<html> must not force dark at boot time"
        );
    }

    #[test]
    fn explain_empty_helper_is_shared_across_call_sites() {
        // The helper must be defined once and consumed by both the
        // cap-reached path inside openExplain and the resolved-diff
        // click handler. Assertion on the function signature plus
        // substring checks on the two user-visible messages is enough
        // to catch a silent drop.
        assert!(
            TEMPLATE.contains("function renderExplainEmpty("),
            "renderExplainEmpty helper missing"
        );
        assert!(
            TEMPLATE.contains("Trace not embedded (cap reached)"),
            "cap-reached message missing"
        );
        assert!(
            TEMPLATE.contains("This finding was resolved."),
            "resolved-diff empty-state message missing"
        );
        // Every inline empty-state message must route through the
        // helper. Floor of 3 = definition + openExplain + resolved-
        // diff, leaving room for future listable tabs to plug in.
        let use_count = TEMPLATE.matches("renderExplainEmpty(").count();
        assert!(
            use_count >= 3,
            "expected at least 3 renderExplainEmpty uses, found {use_count}"
        );
    }

    #[test]
    fn tabs_and_panels_carry_aria_roles() {
        // Static shell assertions: the tablist container and every
        // tabpanel carry the WAI-ARIA roles expected by screen readers.
        // Individual tab buttons are rendered client-side via
        // `renderTabs`, so their roles are set via setAttr and only
        // visible to a live DOM test (see Playwright spec). We verify
        // the attribute names are present in the template source so a
        // refactor can't drop them silently.
        assert!(
            TEMPLATE.contains("role=\"tablist\""),
            "tablist role missing from template"
        );
        for panel in [
            "panel-findings",
            "panel-explain",
            "panel-pgstat",
            "panel-diff",
            "panel-correlations",
            "panel-green",
            "panel-acknowledgments",
        ] {
            let needle = format!("id=\"{panel}\"");
            assert!(TEMPLATE.contains(&needle), "{panel} id missing");
        }
        // Each tabpanel carries `role="tabpanel"` and
        // `aria-labelledby="tab-<name>"` with its matching tab id.
        // The acknowledgments panel was added in 0.5.23 (live mode),
        // bumping the count from 6 to 7.
        let tabpanel_count = TEMPLATE.matches("role=\"tabpanel\"").count();
        assert_eq!(
            tabpanel_count, 7,
            "expected 7 tabpanels, found {tabpanel_count}"
        );
        for tab in [
            "findings",
            "explain",
            "pgstat",
            "diff",
            "correlations",
            "green",
            "acknowledgments",
        ] {
            let needle = format!("aria-labelledby=\"tab-{tab}\"");
            assert!(
                TEMPLATE.contains(&needle),
                "aria-labelledby link missing for {tab}"
            );
        }
        // The setAttr calls that wire `role="tab"` / `aria-selected` /
        // `aria-controls` / `tabindex` on each button must be present
        // in the JS source so the client-side render produces the
        // right shape.
        assert!(TEMPLATE.contains("\"role\", \"tab\""));
        assert!(TEMPLATE.contains("\"aria-selected\""));
        assert!(TEMPLATE.contains("\"aria-controls\""));
    }

    #[test]
    fn chips_carry_aria_radio_and_pressed_states() {
        // pg_stat rankings form a radiogroup. Findings filters split
        // into a severity radiogroup and a service toggle group where
        // every service chip carries `aria-pressed`.
        assert!(
            TEMPLATE.contains("\"role\", \"radiogroup\""),
            "radiogroup role setter missing"
        );
        assert!(
            TEMPLATE.contains("\"aria-label\", \"pg_stat ranking\""),
            "pg_stat ranking radiogroup label missing"
        );
        assert!(
            TEMPLATE.contains("\"aria-label\", \"Finding severity\""),
            "Finding severity radiogroup label missing"
        );
        assert!(
            TEMPLATE.contains("\"aria-label\", \"Finding service\""),
            "Finding service group label missing"
        );
        assert!(
            TEMPLATE.contains("\"aria-checked\""),
            "aria-checked setter missing"
        );
        assert!(
            TEMPLATE.contains("\"aria-pressed\""),
            "aria-pressed setter missing"
        );
    }

    #[test]
    fn copy_link_button_present_on_listable_tabs_only() {
        for tab in ["findings", "pgstat", "diff", "correlations"] {
            let needle = format!("id=\"{tab}-copy-link\"");
            assert!(
                TEMPLATE.contains(&needle),
                "expected copy-link button for listable tab: {tab}"
            );
        }
        // Count-based guard mirroring the export-button test: exactly
        // four `data-copy-link-tab="..."` attributes across the
        // template. Adding a new listable tab must update both the loop
        // above and this assertion in the same commit.
        let copy_link_count = TEMPLATE.matches("data-copy-link-tab=\"").count();
        assert_eq!(
            copy_link_count, 4,
            "expected exactly 4 copy-link buttons, found {copy_link_count}"
        );
        // Explain and GreenOps stay button-less (no toolbar, no
        // copy-link). Check by scanning for their panel IDs and
        // asserting no copy-link id sits in the same rendered HTML
        // produced for a minimal report.
        let f = finding("t1", "svc", "/ep", "SELECT 1");
        let report = minimal_report(vec![f]);
        let (html, _) = render(&report, &[], &opts("-", None));
        assert!(!html.contains("id=\"explain-copy-link\""));
        assert!(!html.contains("id=\"green-copy-link\""));
        // The CSS class backing every copy-link button must exist.
        assert!(
            TEMPLATE.contains(".ps-copy-link-btn"),
            ".ps-copy-link-btn CSS class missing"
        );
    }

    #[test]
    fn template_ships_a_strict_content_security_policy() {
        // Defense-in-depth. The dashboard is fully self-contained, so
        // a CSP that forbids every non-inline origin plus external
        // requests blocks accidental regressions (e.g. a future edit
        // that introduces an <img src="https://..."> via the JSON
        // payload). Since 0.5.23 the CSP value is built per render
        // (static vs live mode), so the assertion targets the
        // <meta http-equiv="Content-Security-Policy" content="..."/>
        // tag specifically rather than the whole HTML, since the JS
        // body legitimately mentions "connect-src" inside live-mode
        // helper comments and string literals.
        let f = finding("t1", "svc", "/ep", "SELECT 1");
        let report = minimal_report(vec![f]);
        let (html, _) = render(&report, &[], &opts("normal.json", None));
        let meta_marker = r#"<meta http-equiv="Content-Security-Policy" content=""#;
        let start = html
            .find(meta_marker)
            .expect("CSP meta tag missing in rendered HTML");
        let after_marker = &html[start + meta_marker.len()..];
        let close = after_marker
            .find('"')
            .expect("CSP meta tag content attribute is unclosed");
        let csp_value = &after_marker[..close];
        assert!(csp_value.contains("default-src 'none'"));
        assert!(csp_value.contains("base-uri 'none'"));
        assert!(csp_value.contains("form-action 'none'"));
        assert!(
            !csp_value.contains("connect-src"),
            "static mode must not advertise connect-src in the CSP, got: {csp_value}"
        );
    }

    #[test]
    fn template_carries_csp_placeholder() {
        let csp_pos = TEMPLATE
            .find(CSP_PLACEHOLDER)
            .expect("CSP placeholder missing");
        let title_pos = TEMPLATE.find(TITLE_PLACEHOLDER).expect("title placeholder");
        let json_pos = TEMPLATE.find(JSON_PLACEHOLDER).expect("JSON placeholder");
        assert!(
            csp_pos < title_pos,
            "CSP placeholder must precede title placeholder so replacen order stays stable"
        );
        assert!(
            csp_pos < json_pos,
            "CSP placeholder must precede JSON placeholder so replacen order stays stable"
        );
    }

    #[test]
    fn build_csp_static_mode_returns_strict_policy() {
        let csp = build_csp(None);
        assert!(csp.contains("default-src 'none'"));
        assert!(csp.contains("base-uri 'none'"));
        assert!(
            !csp.contains("connect-src"),
            "static mode must not include connect-src"
        );
    }

    #[test]
    fn build_csp_live_mode_appends_connect_src() {
        let csp = build_csp(Some("http://localhost:4318"));
        assert!(csp.contains("default-src 'none'"));
        assert!(
            csp.contains("connect-src 'self' http://localhost:4318"),
            "live mode must whitelist 'self' plus the daemon URL: {csp}"
        );
    }

    #[test]
    fn build_csp_live_mode_only_whitelists_provided_url() {
        let csp = build_csp(Some("https://daemon.example.com"));
        // Wildcard `connect-src *` would defeat the purpose; the
        // directive must only allow same-origin and the daemon.
        assert!(!csp.contains("connect-src *"));
        assert!(csp.contains("connect-src 'self' https://daemon.example.com"));
    }

    #[test]
    fn rendered_html_in_static_mode_does_not_carry_daemon_field() {
        let f = finding("t1", "svc", "/ep", "SELECT 1");
        let report = minimal_report(vec![f]);
        let (html, _) = render(&report, &[], &opts("normal.json", None));
        assert!(
            !html.contains(r#""daemon":"#),
            "static mode payload must omit the daemon field"
        );
    }

    #[test]
    fn rendered_html_in_live_mode_with_ipv6_literal_preserves_brackets() {
        // IPv6 authorities embed `[`/`]` brackets per RFC 3986. Verify
        // they survive both the JSON payload (where they are not
        // escape-meaningful) and the CSP directive (where the brackets
        // are valid host-literal syntax). `validate_url` upstream
        // accepts the form, the renderer must not corrupt it.
        let f = finding("t1", "svc", "/ep", "SELECT 1");
        let report = minimal_report(vec![f]);
        let mut options = opts("normal.json", None);
        options.daemon_url = Some("http://[::1]:4318".to_string());
        let (html, _) = render(&report, &[], &options);
        assert!(
            html.contains(r#""daemon":{"url":"http://[::1]:4318"}"#),
            "JSON payload must round-trip the IPv6 literal verbatim"
        );
        assert!(
            html.contains("connect-src 'self' http://[::1]:4318"),
            "CSP must whitelist the IPv6 literal verbatim"
        );
    }

    #[test]
    fn rendered_html_in_live_mode_carries_daemon_field_and_connect_src() {
        let f = finding("t1", "svc", "/ep", "SELECT 1");
        let report = minimal_report(vec![f]);
        let mut options = opts("normal.json", None);
        options.daemon_url = Some("http://localhost:4318".to_string());
        let (html, _) = render(&report, &[], &options);
        assert!(
            html.contains(r#""daemon":{"url":"http://localhost:4318"}"#),
            "live-mode payload must serialize the DaemonHandle"
        );
        assert!(
            html.contains("connect-src 'self' http://localhost:4318"),
            "live-mode CSP must whitelist 'self' plus the daemon URL"
        );
    }

    #[cfg(any(feature = "daemon", feature = "tempo"))]
    #[test]
    fn template_propagates_api_key_header_constant() {
        // Cross-surface drift guard. The daemon's `check_ack_auth` reads
        // the header named by `http_client::API_KEY_HEADER`. Live-mode
        // HTML is the *other* side of that wire: its `fetchWithAuth`
        // helper must attach the same header name. Asserting on the
        // constant (not the literal `"X-API-Key"`) means a rename of the
        // constant either updates the template at the same time, or
        // fails this test loudly.
        let header = crate::http_client::API_KEY_HEADER;
        assert!(
            TEMPLATE.contains(header),
            "live-mode JS must propagate `{header}` on authenticated requests; \
             template contains no occurrence of the constant"
        );
        assert!(
            TEMPLATE.contains("function fetchWithAuth"),
            "fetchWithAuth helper missing from the template; \
             without it the header above is never attached"
        );
    }

    #[cfg(feature = "daemon")]
    #[test]
    fn live_mode_acks_cap_matches_daemon_constant() {
        // The HTML JS hardcodes `DAEMON_ACKS_CAP = N` as the limit before the
        // footer note kicks in. The daemon caps `/api/acks` at
        // `MAX_ACKS_RESPONSE`. Both must stay in lockstep — drift means the JS
        // either truncates findings the daemon would have served, or claims a
        // larger window than the daemon backs. Parse N out of the template and
        // assert equality against the daemon constant; do not check a literal
        // here.
        let needle = "var DAEMON_ACKS_CAP = ";
        let start = TEMPLATE
            .find(needle)
            .expect("template must define DAEMON_ACKS_CAP");
        let after = &TEMPLATE[start + needle.len()..];
        let end = after.find(';').expect("DAEMON_ACKS_CAP must end with ';'");
        let parsed: usize = after[..end]
            .trim()
            .parse()
            .expect("DAEMON_ACKS_CAP value must be a usize");
        assert_eq!(
            parsed,
            crate::daemon::query_api::MAX_ACKS_RESPONSE,
            "HTML DAEMON_ACKS_CAP drift vs daemon MAX_ACKS_RESPONSE"
        );
    }

    #[test]
    fn template_finding_action_button_default_label_is_ack() {
        // The per-row action container is always rendered. In static
        // mode CSS keeps it hidden. In live mode, the JS swaps the
        // label to "Revoke" for already-acked signatures.
        assert!(TEMPLATE.contains("ps-fin-action-btn"));
        assert!(TEMPLATE.contains("\"Ack\""));
    }

    #[test]
    fn template_does_not_leak_session_storage_to_local_storage() {
        // The X-API-Key is sessionStorage-scoped: `localStorage.setItem`
        // would persist it across tab restarts and across browser
        // restarts, which is not the threat model we accept.
        assert!(
            !TEMPLATE.contains("localStorage.setItem"),
            "do not persist the X-API-Key beyond the tab session"
        );
        assert!(
            !TEMPLATE.contains("localStorage.set"),
            "do not persist the X-API-Key beyond the tab session"
        );
    }

    #[test]
    fn hostile_input_label_with_json_placeholder_does_not_double_substitute() {
        // An input_label carrying the literal `{{REPORT_JSON}}` must
        // not trigger a second substitution. `replacen(..., 1)` already
        // consumed the only JSON placeholder in the template, so the
        // title injection only sees the title placeholder.
        let f = finding("t1", "svc", "/ep", "SELECT 1");
        let report = minimal_report(vec![f]);
        let (html, _) = render(&report, &[], &opts("{{REPORT_JSON}}.json", None));
        // The title text is HTML-escaped, so `{` and `}` survive as
        // literal bytes. There must be no injection into the JSON
        // block (which would appear as a trailing stray `}` outside
        // the `<script id="report-data">` block).
        assert!(
            html.contains("<title>perf-sentinel: {{REPORT_JSON}}.json</title>"),
            "placeholder literal must survive as data"
        );
    }

    #[test]
    fn hostile_template_containing_title_placeholder_survives_as_data() {
        // A SQL template carrying `{{PAGE_TITLE}}` inside a Finding
        // payload ends up in the JSON block. The title substitution
        // runs on TEMPLATE, whose first `{{PAGE_TITLE}}` occurrence
        // is the static `<title>` tag, so the user-controlled one is
        // never consumed.
        let f = finding("t1", "svc", "/ep", "SELECT '{{PAGE_TITLE}}'");
        let report = minimal_report(vec![f]);
        let (html, _) = render(&report, &[], &opts("normal.json", None));
        assert!(
            html.contains("SELECT '{{PAGE_TITLE}}'"),
            "user-controlled placeholder literal must survive in the JSON payload"
        );
    }

    #[test]
    fn page_title_strips_control_characters() {
        // ANSI escape sequences, `BiDi` marks, null bytes, and other
        // control codes must not survive into the rendered title,
        // otherwise a hostile filename could render an OSC hyperlink
        // in the browser tab on some platforms. Dropping the ESC byte
        // defangs the sequence even though the remaining printable
        // bytes (`[31m`) pass through as plain text.
        let f = finding("t1", "svc", "/ep", "SELECT 1");
        let report = minimal_report(vec![f]);
        let (html, _) = render(&report, &[], &opts("a\x1b[31mb\x00c\u{202e}d.json", None));
        assert!(!html.contains('\x1b'), "ESC must not leak into the title");
        assert!(
            !html.contains('\x00'),
            "null byte must not leak into the title"
        );
        assert!(
            !html.contains('\u{202e}'),
            "`BiDi` override must not leak into the title"
        );
        // Sanity on the visible fragment after stripping: the printable
        // remains of the ANSI sequence plus the non-control letters
        // survive as literal text, which is safe in a `<title>`.
        assert!(html.contains("<title>perf-sentinel: a[31mbcd.json</title>"));
    }

    #[test]
    fn page_title_uses_filename_from_input_label() {
        let f = finding("t1", "svc", "/ep", "SELECT 1");
        let report = minimal_report(vec![f]);

        let (html_with_path, _) = render(
            &report,
            &[],
            &opts("/tmp/reports/prod-2026-04-21.json", None),
        );
        assert!(
            html_with_path.contains("<title>perf-sentinel: prod-2026-04-21.json</title>"),
            "title should show the filename without path components"
        );

        let (html_stdin, _) = render(&report, &[], &opts("-", None));
        assert!(
            html_stdin.contains("<title>perf-sentinel report</title>"),
            "stdin label falls back to the default title"
        );

        let (html_empty, _) = render(&report, &[], &opts("", None));
        assert!(
            html_empty.contains("<title>perf-sentinel report</title>"),
            "empty label falls back to the default title"
        );

        // HTML-unsafe characters in the filename are escaped.
        let (html_hostile, _) = render(&report, &[], &opts("/tmp/<hack>&.json", None));
        assert!(
            html_hostile.contains("<title>perf-sentinel: &lt;hack&gt;&amp;.json</title>"),
            "unsafe characters in the filename are HTML-escaped"
        );
        assert!(
            !html_hostile.contains("<title>perf-sentinel: <hack>"),
            "raw < must not leak into the title"
        );
    }

    #[test]
    fn embeds_correlations_when_report_carries_them() {
        // Daemon-produced Reports can carry cross-trace correlations.
        // The template's Correlations tab is guarded on
        // `report.correlations?.length > 0`, so the tab lights up
        // automatically when the field is non-empty. Assert the
        // serialized payload carries the field with the expected shape
        // so the JS sees what it expects.
        use crate::detect::FindingType;
        use crate::detect::correlate_cross::{CorrelationEndpoint, CrossTraceCorrelation};

        let correlation = CrossTraceCorrelation {
            source: CorrelationEndpoint {
                finding_type: FindingType::NPlusOneSql,
                service: "order-svc".to_string(),
                template: "SELECT * FROM o WHERE id = ?".to_string(),
            },
            target: CorrelationEndpoint {
                finding_type: FindingType::SlowHttp,
                service: "payment-svc".to_string(),
                template: "POST /api/charge".to_string(),
            },
            co_occurrence_count: 8,
            source_total_occurrences: 10,
            confidence: 0.8,
            median_lag_ms: 120.0,
            first_seen: "2026-04-21T10:00:00Z".to_string(),
            last_seen: "2026-04-21T10:05:00Z".to_string(),
            sample_trace_id: None,
        };

        let f = finding("t1", "svc", "/ep", "SELECT * FROM t");
        let mut report = minimal_report(vec![f]);
        report.correlations = vec![correlation];
        let (html, _) = render(&report, &[], &opts("-", None));
        let blob = extract_payload_json(&html);
        let value: serde_json::Value = serde_json::from_str(&blob).unwrap();

        let corrs = value["report"]["correlations"].as_array().unwrap();
        assert_eq!(corrs.len(), 1);
        assert_eq!(corrs[0]["source"]["service"].as_str().unwrap(), "order-svc");
        assert_eq!(
            corrs[0]["target"]["service"].as_str().unwrap(),
            "payment-svc"
        );
        assert_eq!(corrs[0]["co_occurrence_count"].as_u64().unwrap(), 8);

        // The Correlations panel scaffolding must exist in the static
        // shell so the JS can reveal it without touching innerHTML.
        assert!(html.contains(r#"id="panel-correlations""#));
    }
}