fp-frankentui 0.2.0

FrankenTUI terminal interface for interactive fp-frame / frankenpandas workflows.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
#![forbid(unsafe_code)]
#![warn(rustdoc::broken_intra_doc_links)]

//! FrankenTUI — terminal-UI snapshot model + E2E scenario harness
//! for interactive `fp-frame` / `frankenpandas` workflows.
//!
//! The TUI itself (rendering, key handling, event loop) lives in a
//! separate consumer; this crate provides the **value-type
//! snapshots** the TUI binds onto and the **E2E scenario harness**
//! that exercises the snapshot pipeline end-to-end against
//! fp-conformance fixtures.
//!
//! ## Snapshot families
//!
//! Each family is a serializable struct the TUI reads to render
//! one screen / panel. Snapshots are produced by background work
//! (conformance harness runs, decision-ledger ticks, policy
//! audits) and consumed by the TUI's render loop.
//!
//! - **Conformance dashboards**:
//!   [`ConformanceDashboardSnapshot`] — top-level pass/fail with
//!   per-suite drilldown. [`PacketSnapshot`] +
//!   [`PacketTrendSnapshot`] for individual packet replay state
//!   and historical drift. [`DriftHistorySnapshot`] tracks
//!   numeric drift over time so authors can see when a kernel
//!   started slipping.
//!
//! - **Decision dashboards**:
//!   [`DecisionDashboardSnapshot`] / [`DecisionCardSnapshot`] —
//!   bridges fp-runtime's decision recording into a TUI view of
//!   "what choices did the runtime make this hour". Backed by
//!   [`PolicySnapshot`] for the active runtime policy.
//!
//! - **Conformal guard state**: [`ConformalSnapshot`] surfaces
//!   the fp-runtime conformal guard's calibration window and
//!   prediction set health.
//!
//! - **Final evidence packs**: [`FinalEvidencePackSnapshot`] +
//!   [`FinalEvidencePacketSnapshot`] for the bundled-evidence
//!   summary at the end of a long-running pipeline.
//!
//! - **Differential validation**:
//!   [`DifferentialValidationSnapshot`] +
//!   [`DifferentialValidationSummary`] +
//!   [`DifferentialValidationLogEntry`] for parallel-implementation
//!   comparison runs (e.g. comparing two frankenpandas builds, or
//!   frankenpandas vs pandas).
//!
//! - **Artifact issues**: [`ArtifactIssue`] / [`ArtifactIssueKind`]
//!   for problems detected in on-disk artifacts that the TUI
//!   should surface to the operator.
//!
//! ## E2E scenario harness
//!
//! - [`FrankentuiE2eScenario`]: one end-to-end test scenario
//!   declaration. Tagged with [`FrankentuiE2eScenarioKind`].
//! - [`FrankentuiE2eReplayBundleEntry`]: an item in the replay
//!   bundle a scenario needs to seed before exercising the
//!   snapshot pipeline.
//! - [`FrankentuiE2eScenarioReport`]: the verdict of running one
//!   scenario.
//!
//! ## Error reporting
//!
//! [`FtuiError`] enumerates structural failures (missing snapshot
//! file, malformed entry, replay-bundle integrity mismatch).
//!
//! ## Cross-crate relationships
//!
//! Built on top of fp-conformance (re-uses its `CaseStatus` /
//! `DriftLevel` / `FixtureOracleSource` types) and fp-runtime
//! (decision policy + conformal guard primitives that snapshot
//! into the `Decision*` / `ConformalSnapshot` families).

use std::{
    collections::{BTreeMap, HashMap},
    fs::{self, File},
    io::{BufRead, BufReader},
    path::{Path, PathBuf},
};

use fp_conformance::{
    CaseStatus, DecodeProofArtifact, DecodeProofStatus, DifferentialReport, DifferentialResult,
    DriftLevel, E2eConfig, E2eReport, FailureForensicsReport, FixtureOracleSource, ForensicEvent,
    ForensicEventKind, HarnessConfig, HarnessError, NoopHooks, OracleMode, PacketDriftHistoryEntry,
    PacketGateResult, PacketParityReport, SidecarIntegrityResult, SuiteOptions,
    build_failure_forensics, run_differential_by_id, run_differential_suite, run_e2e_suite,
    verify_packet_sidecar_integrity,
};
use fp_runtime::{ConformalGuard, EvidenceLedger, RuntimeMode, RuntimePolicy, decision_to_card};
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use thiserror::Error;

const PHASE2C_DIR: &str = "artifacts/phase2c";
const DRIFT_HISTORY_FILE: &str = "drift_history.jsonl";
const DIFFERENTIAL_REPORT_FILE: &str = "differential_report.json";
const CI_DIR: &str = "ci";
const GOVERNANCE_GATE_REPORT_FILE: &str = "governance_gate_report.json";

#[derive(Debug, Error)]
pub enum FtuiError {
    #[error("artifact root is not accessible: {path}")]
    ArtifactRootMissing { path: PathBuf },
    #[error("invalid packet id: {packet_id}")]
    InvalidPacketId { packet_id: String },
    #[error("failed to read {path}: {source}")]
    Io {
        path: PathBuf,
        source: std::io::Error,
    },
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ArtifactIssueKind {
    MissingFile,
    ParseError,
    IoError,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ArtifactIssue {
    pub path: PathBuf,
    pub kind: ArtifactIssueKind,
    pub detail: String,
}

#[derive(Debug, Clone, PartialEq)]
pub struct PacketSnapshot {
    pub packet_id: String,
    pub parity_report: Option<PacketParityReport>,
    pub gate_result: Option<PacketGateResult>,
    pub decode_status: Option<DecodeProofStatus>,
    pub mismatch_count: Option<usize>,
    pub differential_report: Option<DifferentialReport>,
    pub differential_validation: Option<DifferentialValidationSummary>,
    pub issues: Vec<ArtifactIssue>,
}

impl PacketSnapshot {
    #[must_use]
    pub fn is_green(&self) -> bool {
        self.parity_report
            .as_ref()
            .is_some_and(PacketParityReport::is_green)
            && self.gate_result.as_ref().is_some_and(|gate| gate.pass)
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct FinalEvidencePacketSnapshot {
    pub packet_id: String,
    pub gate_pass: Option<bool>,
    pub parity_green: bool,
    pub decode_status: Option<DecodeProofStatus>,
    pub sidecar_integrity_ok: bool,
    pub sidecar_integrity_errors: Vec<String>,
    pub artifact_issues: Vec<ArtifactIssue>,
    pub risk_notes: Vec<String>,
}

impl FinalEvidencePacketSnapshot {
    #[must_use]
    pub fn is_green(&self) -> bool {
        self.gate_pass == Some(true)
            && self.parity_green
            && self.decode_status == Some(DecodeProofStatus::Recovered)
            && self.sidecar_integrity_ok
            && self.artifact_issues.is_empty()
            && self.risk_notes.is_empty()
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct FinalEvidencePackSnapshot {
    pub phase2c_root: PathBuf,
    pub packets: Vec<FinalEvidencePacketSnapshot>,
    pub total_packets: usize,
    pub parity_gate_passed: usize,
    pub parity_gate_failed: usize,
    pub parity_gate_missing: usize,
    pub sidecar_integrity_passed: usize,
    pub sidecar_integrity_failed: usize,
    pub decode_recovered: usize,
    pub decode_failed_or_missing: usize,
    pub all_checks_passed: bool,
    pub risk_notes: Vec<String>,
}

impl FinalEvidencePackSnapshot {
    #[must_use]
    pub fn render_plain(&self) -> String {
        let mut out = String::new();
        out.push_str(&format!(
            "FinalEvidence packets={} all_checks_passed={} parity[pass={},fail={},missing={}] sidecar[pass={},fail={}] decode[recovered={},failed_or_missing={}] risk_notes={}\n",
            self.total_packets,
            self.all_checks_passed,
            self.parity_gate_passed,
            self.parity_gate_failed,
            self.parity_gate_missing,
            self.sidecar_integrity_passed,
            self.sidecar_integrity_failed,
            self.decode_recovered,
            self.decode_failed_or_missing,
            self.risk_notes.len(),
        ));
        out.push_str(&format!("phase2c_root={}\n", self.phase2c_root.display()));
        for packet in &self.packets {
            out.push_str(&format!(
                "- {} gate={} parity_green={} decode_status={} sidecar_ok={} artifact_issues={} risk_notes={}\n",
                packet.packet_id,
                packet
                    .gate_pass
                    .map_or_else(|| "missing".to_owned(), |pass| pass.to_string()),
                packet.parity_green,
                packet
                    .decode_status
                    .as_ref()
                    .map_or_else(|| "missing".to_owned(), ToString::to_string),
                packet.sidecar_integrity_ok,
                packet.artifact_issues.len(),
                packet.risk_notes.len(),
            ));
        }
        out
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct DriftHistorySnapshot {
    pub entries: Vec<PacketDriftHistoryEntry>,
    pub malformed_lines: usize,
    pub missing: bool,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PolicySnapshot {
    pub mode: RuntimeMode,
    pub fail_closed_unknown_features: bool,
    pub hardened_join_row_cap: Option<usize>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct ConformalSnapshot {
    pub calibrated: bool,
    pub calibration_count: usize,
    pub quantile_threshold: Option<f64>,
    pub empirical_coverage: f64,
    pub coverage_alert: bool,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DecisionCardSnapshot {
    pub mode: RuntimeMode,
    pub card: String,
    pub evidence_terms_total: usize,
    pub evidence_terms_shown: usize,
}

#[derive(Debug, Clone, PartialEq)]
pub struct DecisionDashboardSnapshot {
    pub total_records: usize,
    pub strict_records: usize,
    pub hardened_records: usize,
    pub policy: PolicySnapshot,
    pub cards: Vec<DecisionCardSnapshot>,
    pub evidence_term_cap: usize,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PacketTrendSnapshot {
    pub packet_id: String,
    pub samples: usize,
    pub latest_gate_pass: Option<bool>,
    pub latest_failed_cases: Option<usize>,
}

fn build_packet_trends(
    packets: &[PacketSnapshot],
    entries: &[PacketDriftHistoryEntry],
) -> Vec<PacketTrendSnapshot> {
    if packets.is_empty() {
        return Vec::new();
    }

    let mut by_packet =
        HashMap::<&str, (usize, Option<&PacketDriftHistoryEntry>)>::with_capacity(packets.len());
    for packet in packets {
        by_packet
            .entry(packet.packet_id.as_str())
            .or_insert((0, None));
    }
    for entry in entries {
        if let Some(trend) = by_packet.get_mut(entry.packet_id.as_str()) {
            trend.0 += 1;
            if trend
                .1
                .is_none_or(|latest| entry.ts_unix_ms >= latest.ts_unix_ms)
            {
                trend.1 = Some(entry);
            }
        }
    }

    packets
        .iter()
        .map(|packet| {
            let (samples, latest) = by_packet
                .get(packet.packet_id.as_str())
                .map_or((0, None), |(samples, latest)| (*samples, *latest));
            PacketTrendSnapshot {
                packet_id: packet.packet_id.clone(),
                samples,
                latest_gate_pass: latest.map(|entry| entry.gate_pass),
                latest_failed_cases: latest.map(|entry| entry.failed),
            }
        })
        .collect()
}

#[derive(Debug, Clone, PartialEq)]
pub struct ConformanceDashboardSnapshot {
    pub packets: Vec<PacketSnapshot>,
    pub drift_history: DriftHistorySnapshot,
    pub packet_trends: Vec<PacketTrendSnapshot>,
    pub total_packets: usize,
    pub green_packets: usize,
    pub failing_packets: usize,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DifferentialValidationSummary {
    pub total_cases: usize,
    pub strict_critical_violations: usize,
    pub hardened_critical_violations: usize,
    pub hardened_allowlisted_divergence: usize,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DifferentialValidationLogEntry {
    pub packet_id: String,
    pub case_id: String,
    pub mode: RuntimeMode,
    pub trace_id: String,
    pub oracle_source: FixtureOracleSource,
    pub mismatch_class: String,
    pub replay_key: String,
}

#[derive(Debug, Clone, PartialEq)]
pub struct DifferentialValidationSnapshot {
    pub report: DifferentialReport,
    pub summary: DifferentialValidationSummary,
    pub logs: Vec<DifferentialValidationLogEntry>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FrankentuiE2eScenarioKind {
    Golden,
    Regression,
    FailureInjection,
}

impl FrankentuiE2eScenarioKind {
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Golden => "golden",
            Self::Regression => "regression",
            Self::FailureInjection => "failure_injection",
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FrankentuiE2eScenario {
    pub scenario_id: String,
    pub kind: FrankentuiE2eScenarioKind,
    pub packet_filter: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FrankentuiE2eReplayBundleEntry {
    pub scenario_id: String,
    pub packet_id: String,
    pub case_id: String,
    pub mode: RuntimeMode,
    pub trace_id: String,
    pub step_id: String,
    pub decision_action: String,
    pub latency_ms: u64,
    pub replay_key: String,
    pub replay_cmd: String,
    pub mismatch_class: Option<String>,
    pub failure_diagnostics: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FrankentuiE2eScenarioReport {
    pub scenario: FrankentuiE2eScenario,
    pub report: E2eReport,
    pub forensics: FailureForensicsReport,
    pub replay_bundles: Vec<FrankentuiE2eReplayBundleEntry>,
}

impl ConformanceDashboardSnapshot {
    #[must_use]
    pub fn is_green(&self) -> bool {
        self.total_packets > 0 && self.failing_packets == 0
    }

    #[must_use]
    pub fn render_plain(&self) -> String {
        let mut out = String::new();
        out.push_str(&format!(
            "Conformance packets={} green={} failing={} drift_entries={} malformed_drift_lines={}\n",
            self.total_packets,
            self.green_packets,
            self.failing_packets,
            self.drift_history.entries.len(),
            self.drift_history.malformed_lines
        ));
        for packet in &self.packets {
            out.push_str(&format!(
                "- {} gate={} parity={} mismatches={} issues={}\n",
                packet.packet_id,
                packet.gate_result.as_ref().map(|g| g.pass).unwrap_or(false),
                packet
                    .parity_report
                    .as_ref()
                    .is_some_and(PacketParityReport::is_green),
                packet.mismatch_count.unwrap_or(0),
                packet.issues.len()
            ));
        }
        out
    }
}

#[must_use]
pub fn build_differential_validation_snapshot(
    report: DifferentialReport,
) -> DifferentialValidationSnapshot {
    let summary = summarize_differential_validation(&report);
    let logs = differential_validation_log_entries(&report);
    DifferentialValidationSnapshot {
        report,
        summary,
        logs,
    }
}

pub fn run_differential_validation_suite(
    config: &HarnessConfig,
    options: &SuiteOptions,
) -> Result<DifferentialValidationSnapshot, HarnessError> {
    let report = run_differential_suite(config, options)?;
    Ok(build_differential_validation_snapshot(report))
}

pub fn run_differential_validation_by_packet(
    config: &HarnessConfig,
    packet_id: &str,
    oracle_mode: OracleMode,
) -> Result<DifferentialValidationSnapshot, HarnessError> {
    let report = run_differential_by_id(config, packet_id, oracle_mode)?;
    Ok(build_differential_validation_snapshot(report))
}

#[must_use]
pub fn harness_config_from_repo_root(repo_root: impl AsRef<Path>) -> HarnessConfig {
    let repo_root = repo_root.as_ref().to_path_buf();
    HarnessConfig {
        repo_root: repo_root.clone(),
        oracle_root: repo_root.join("legacy_pandas_code/pandas"),
        fixture_root: repo_root.join("crates/fp-conformance/fixtures"),
        strict_mode: true,
        python_bin: "python3".to_owned(),
        allow_system_pandas_fallback: false,
        require_live_oracle: false,
    }
}

#[must_use]
pub fn default_frankentui_e2e_scenarios() -> Vec<FrankentuiE2eScenario> {
    vec![
        FrankentuiE2eScenario {
            scenario_id: "frankentui_e2e_golden".to_owned(),
            kind: FrankentuiE2eScenarioKind::Golden,
            packet_filter: Some("FP-P2C-001".to_owned()),
        },
        FrankentuiE2eScenario {
            scenario_id: "frankentui_e2e_regression".to_owned(),
            kind: FrankentuiE2eScenarioKind::Regression,
            packet_filter: Some("FP-P2C-001".to_owned()),
        },
        FrankentuiE2eScenario {
            scenario_id: "frankentui_e2e_failure_injection".to_owned(),
            kind: FrankentuiE2eScenarioKind::FailureInjection,
            packet_filter: Some("FP-P2C-001".to_owned()),
        },
    ]
}

pub fn run_frankentui_e2e_matrix(
    config: &HarnessConfig,
    scenarios: &[FrankentuiE2eScenario],
) -> Result<Vec<FrankentuiE2eScenarioReport>, HarnessError> {
    let mut reports = Vec::with_capacity(scenarios.len());
    for scenario in scenarios {
        reports.push(run_frankentui_e2e_scenario(config, scenario)?);
    }
    Ok(reports)
}

pub fn run_frankentui_e2e_scenario(
    config: &HarnessConfig,
    scenario: &FrankentuiE2eScenario,
) -> Result<FrankentuiE2eScenarioReport, HarnessError> {
    let mut hooks = NoopHooks;
    let e2e_config = E2eConfig {
        harness: config.clone(),
        options: SuiteOptions {
            packet_filter: scenario.packet_filter.clone(),
            oracle_mode: OracleMode::FixtureExpected,
        },
        write_artifacts: false,
        enforce_gates: false,
        append_drift_history: false,
        forensic_log_path: None,
    };
    let mut report = run_e2e_suite(&e2e_config, &mut hooks)?;
    if matches!(scenario.kind, FrankentuiE2eScenarioKind::FailureInjection) {
        inject_synthetic_failure_case(&mut report, &scenario.scenario_id);
    }
    let forensics = build_failure_forensics(&report);
    let replay_bundles = build_frankentui_e2e_replay_bundles(&report, &forensics);
    Ok(FrankentuiE2eScenarioReport {
        scenario: scenario.clone(),
        report,
        forensics,
        replay_bundles,
    })
}

#[must_use]
pub fn build_frankentui_e2e_replay_bundles(
    e2e: &E2eReport,
    forensics: &FailureForensicsReport,
) -> Vec<FrankentuiE2eReplayBundleEntry> {
    let mode_index = build_case_mode_index(e2e);
    build_frankentui_e2e_replay_bundles_with_mode_lookup(e2e, forensics, |packet_id, case_id| {
        mode_index.get(&(packet_id, case_id)).copied()
    })
}

fn build_case_mode_index(e2e: &E2eReport) -> HashMap<(&str, &str), RuntimeMode> {
    let mut mode_index = HashMap::<(&str, &str), RuntimeMode>::new();
    for packet in &e2e.packet_reports {
        for result in &packet.results {
            mode_index
                .entry((result.packet_id.as_str(), result.case_id.as_str()))
                .or_insert(result.mode);
        }
    }
    mode_index
}

fn build_frankentui_e2e_replay_bundles_with_mode_lookup<F>(
    e2e: &E2eReport,
    forensics: &FailureForensicsReport,
    mut fallback_mode_lookup: F,
) -> Vec<FrankentuiE2eReplayBundleEntry>
where
    F: FnMut(&str, &str) -> Option<RuntimeMode>,
{
    let mut failure_diagnostics = BTreeMap::<(String, String, String), String>::new();
    for failure in &forensics.failures {
        failure_diagnostics.insert(
            (
                failure.packet_id.clone(),
                failure.case_id.clone(),
                runtime_mode_slug(failure.mode).to_owned(),
            ),
            failure.mismatch_summary.clone(),
        );
    }

    let mut bundles = Vec::new();
    for event in &e2e.forensic_log.events {
        if let ForensicEventKind::CaseEnd {
            scenario_id,
            packet_id,
            case_id,
            trace_id,
            step_id,
            result: _,
            replay_cmd,
            decision_action,
            replay_key,
            mismatch_class,
            status: _,
            evidence_records: _,
            elapsed_us,
            seed: _,
            assertion_path: _,
        } = &event.event
        {
            let Some(mode) = mode_from_replay_key(replay_key)
                .or_else(|| fallback_mode_lookup(packet_id, case_id))
            else {
                continue;
            };

            let diagnostics = failure_diagnostics
                .get(&(
                    packet_id.clone(),
                    case_id.clone(),
                    runtime_mode_slug(mode).to_owned(),
                ))
                .cloned()
                .unwrap_or_else(|| "(none)".to_owned());

            bundles.push(FrankentuiE2eReplayBundleEntry {
                scenario_id: scenario_id.clone(),
                packet_id: packet_id.clone(),
                case_id: case_id.clone(),
                mode,
                trace_id: trace_id.clone(),
                step_id: step_id.clone(),
                decision_action: decision_action.clone(),
                latency_ms: elapsed_us_to_latency_ms(*elapsed_us),
                replay_key: replay_key.clone(),
                replay_cmd: replay_cmd.clone(),
                mismatch_class: mismatch_class.clone(),
                failure_diagnostics: diagnostics,
            });
        }
    }

    bundles.sort_by(|left, right| {
        left.scenario_id
            .cmp(&right.scenario_id)
            .then(left.packet_id.cmp(&right.packet_id))
            .then(left.case_id.cmp(&right.case_id))
            .then(mode_sort_key(left.mode).cmp(&mode_sort_key(right.mode)))
    });
    bundles
}

#[cfg(test)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
struct ReplayBundleBuildStats {
    mode_lookup_steps: usize,
}

#[cfg(test)]
fn resolve_mode_by_linear_scan(
    e2e: &E2eReport,
    packet_id: &str,
    case_id: &str,
    stats: &mut ReplayBundleBuildStats,
) -> Option<RuntimeMode> {
    for packet in &e2e.packet_reports {
        for result in &packet.results {
            stats.mode_lookup_steps += 1;
            if result.packet_id == packet_id && result.case_id == case_id {
                return Some(result.mode);
            }
        }
    }
    None
}

#[cfg(test)]
fn build_frankentui_e2e_replay_bundles_baseline_with_stats(
    e2e: &E2eReport,
    forensics: &FailureForensicsReport,
) -> (Vec<FrankentuiE2eReplayBundleEntry>, ReplayBundleBuildStats) {
    let mut stats = ReplayBundleBuildStats::default();
    let bundles = build_frankentui_e2e_replay_bundles_with_mode_lookup(
        e2e,
        forensics,
        |packet_id, case_id| resolve_mode_by_linear_scan(e2e, packet_id, case_id, &mut stats),
    );
    (bundles, stats)
}

#[cfg(test)]
fn build_frankentui_e2e_replay_bundles_optimized_with_stats(
    e2e: &E2eReport,
    forensics: &FailureForensicsReport,
) -> (Vec<FrankentuiE2eReplayBundleEntry>, ReplayBundleBuildStats) {
    let mode_index = build_case_mode_index(e2e);
    let mut stats = ReplayBundleBuildStats::default();
    let bundles = build_frankentui_e2e_replay_bundles_with_mode_lookup(
        e2e,
        forensics,
        |packet_id, case_id| {
            stats.mode_lookup_steps += 1;
            mode_index.get(&(packet_id, case_id)).copied()
        },
    );
    (bundles, stats)
}

fn elapsed_us_to_latency_ms(elapsed_us: u64) -> u64 {
    elapsed_us.saturating_add(999).saturating_div(1_000).max(1)
}

fn mode_from_replay_key(replay_key: &str) -> Option<RuntimeMode> {
    if replay_key.ends_with("/strict") {
        Some(RuntimeMode::Strict)
    } else if replay_key.ends_with("/hardened") {
        Some(RuntimeMode::Hardened)
    } else {
        None
    }
}

fn inject_synthetic_failure_case(report: &mut E2eReport, scenario_id: &str) {
    let mut injected_case: Option<(String, String, RuntimeMode)> = None;

    if let Some(packet_report) = report.packet_reports.first_mut() {
        if let Some(case) = packet_report.results.first_mut() {
            case.status = CaseStatus::Fail;
            case.mismatch = Some(format!("synthetic failure injection for {scenario_id}"));
            case.mismatch_class = Some("synthetic_failure_injection".to_owned());
            if case.trace_id.is_empty() {
                case.trace_id =
                    deterministic_differential_trace_id(&case.packet_id, &case.case_id, case.mode);
            }
            if case.replay_key.is_empty() {
                case.replay_key = deterministic_differential_replay_key(
                    &case.packet_id,
                    &case.case_id,
                    case.mode,
                );
            }
            injected_case = Some((case.packet_id.clone(), case.case_id.clone(), case.mode));
        }

        packet_report.failed = packet_report
            .results
            .iter()
            .filter(|result| matches!(result.status, CaseStatus::Fail))
            .count();
        packet_report.passed = packet_report
            .results
            .len()
            .saturating_sub(packet_report.failed);
    }

    report.total_fixtures = report
        .packet_reports
        .iter()
        .map(|entry| entry.fixture_count)
        .sum();
    report.total_passed = report.packet_reports.iter().map(|entry| entry.passed).sum();
    report.total_failed = report.packet_reports.iter().map(|entry| entry.failed).sum();
    report.gates_pass = false;

    if let Some((packet_id, case_id, mode)) = injected_case {
        if let Some(gate) = report
            .gate_results
            .iter_mut()
            .find(|gate| gate.packet_id == packet_id)
        {
            gate.pass = false;
            if !gate
                .reasons
                .iter()
                .any(|reason| reason.contains("synthetic failure injection"))
            {
                gate.reasons
                    .push(format!("synthetic failure injection: {scenario_id}"));
            }
            match mode {
                RuntimeMode::Strict => gate.strict_failed = gate.strict_failed.max(1),
                RuntimeMode::Hardened => gate.hardened_failed = gate.hardened_failed.max(1),
            }
        }

        for event in &mut report.forensic_log.events {
            if let ForensicEventKind::CaseEnd {
                packet_id: event_packet_id,
                case_id: event_case_id,
                decision_action,
                result,
                mismatch_class,
                status,
                ..
            } = &mut event.event
                && *event_packet_id == packet_id
                && *event_case_id == case_id
            {
                *decision_action = "repair".to_owned();
                *result = "fail".to_owned();
                *mismatch_class = Some("synthetic_failure_injection".to_owned());
                *status = CaseStatus::Fail;
                break;
            }
        }
    }
}

#[must_use]
pub fn summarize_differential_validation(
    report: &DifferentialReport,
) -> DifferentialValidationSummary {
    let mut strict_critical_violations = 0_usize;
    let mut hardened_critical_violations = 0_usize;
    let mut hardened_allowlisted_divergence = 0_usize;

    for result in &report.differential_results {
        let has_critical = result
            .drift_records
            .iter()
            .any(|drift| matches!(drift.level, DriftLevel::Critical));
        let has_non_critical_or_info = result.drift_records.iter().any(|drift| {
            matches!(
                drift.level,
                DriftLevel::NonCritical | DriftLevel::Informational
            )
        });

        match result.mode {
            RuntimeMode::Strict => {
                if has_critical {
                    strict_critical_violations += 1;
                }
            }
            RuntimeMode::Hardened => {
                if has_critical {
                    hardened_critical_violations += 1;
                } else if has_non_critical_or_info {
                    hardened_allowlisted_divergence += 1;
                }
            }
        }
    }

    DifferentialValidationSummary {
        total_cases: report.differential_results.len(),
        strict_critical_violations,
        hardened_critical_violations,
        hardened_allowlisted_divergence,
    }
}

#[must_use]
pub fn differential_validation_log_entries(
    report: &DifferentialReport,
) -> Vec<DifferentialValidationLogEntry> {
    let mut entries = report
        .differential_results
        .iter()
        .map(differential_log_entry_from_result)
        .collect::<Vec<_>>();

    entries.sort_by(|left, right| {
        left.packet_id
            .cmp(&right.packet_id)
            .then(left.case_id.cmp(&right.case_id))
            .then(mode_sort_key(left.mode).cmp(&mode_sort_key(right.mode)))
    });

    entries
}

fn differential_log_entry_from_result(
    result: &DifferentialResult,
) -> DifferentialValidationLogEntry {
    DifferentialValidationLogEntry {
        packet_id: result.packet_id.clone(),
        case_id: result.case_id.clone(),
        mode: result.mode,
        trace_id: if result.trace_id.is_empty() {
            deterministic_differential_trace_id(&result.packet_id, &result.case_id, result.mode)
        } else {
            result.trace_id.clone()
        },
        oracle_source: result.oracle_source,
        mismatch_class: mismatch_class_for_differential_result(result),
        replay_key: if result.replay_key.is_empty() {
            deterministic_differential_replay_key(&result.packet_id, &result.case_id, result.mode)
        } else {
            result.replay_key.clone()
        },
    }
}

fn mismatch_class_for_differential_result(result: &DifferentialResult) -> String {
    result
        .drift_records
        .iter()
        .find(|drift| matches!(drift.level, DriftLevel::Critical))
        .or_else(|| result.drift_records.first())
        .map(|drift| drift.mismatch_class.clone())
        .unwrap_or_else(|| {
            if matches!(result.status, CaseStatus::Fail) {
                "execution_critical".to_owned()
            } else {
                "none".to_owned()
            }
        })
}

fn runtime_mode_slug(mode: RuntimeMode) -> &'static str {
    match mode {
        RuntimeMode::Strict => "strict",
        RuntimeMode::Hardened => "hardened",
    }
}

fn deterministic_differential_trace_id(
    packet_id: &str,
    case_id: &str,
    mode: RuntimeMode,
) -> String {
    format!("{packet_id}:{case_id}:{}", runtime_mode_slug(mode))
}

fn deterministic_differential_replay_key(
    packet_id: &str,
    case_id: &str,
    mode: RuntimeMode,
) -> String {
    format!("{packet_id}/{case_id}/{}", runtime_mode_slug(mode))
}

fn mode_sort_key(mode: RuntimeMode) -> u8 {
    match mode {
        RuntimeMode::Strict => 0,
        RuntimeMode::Hardened => 1,
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct ForensicLogSnapshot {
    pub events: Vec<ForensicEvent>,
    pub malformed_lines: usize,
    pub missing: bool,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GovernanceGateSnapshot {
    pub path: PathBuf,
    pub all_passed: bool,
    pub violation_count: usize,
    pub generated_unix_ms: u128,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DashboardView {
    Conformance,
    Decision,
    Forensics,
    Policy,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FtuiAppState {
    pub active_view: DashboardView,
    pub packet_cursor: usize,
    pub packet_ids: Vec<String>,
}

impl FtuiAppState {
    #[must_use]
    pub fn new(mut packet_ids: Vec<String>) -> Self {
        packet_ids.sort();
        Self {
            active_view: DashboardView::Conformance,
            packet_cursor: 0,
            packet_ids,
        }
    }

    pub fn cycle_next_view(&mut self) {
        self.active_view = match self.active_view {
            DashboardView::Conformance => DashboardView::Decision,
            DashboardView::Decision => DashboardView::Forensics,
            DashboardView::Forensics => DashboardView::Policy,
            DashboardView::Policy => DashboardView::Conformance,
        };
    }

    pub fn select_next_packet(&mut self) {
        if self.packet_ids.is_empty() {
            self.packet_cursor = 0;
            return;
        }
        self.packet_cursor = (self.packet_cursor + 1) % self.packet_ids.len();
    }

    #[must_use]
    pub fn selected_packet(&self) -> Option<&str> {
        self.packet_ids.get(self.packet_cursor).map(String::as_str)
    }
}

pub trait FtuiDataSource {
    fn discover_packet_ids(&self) -> Result<Vec<String>, FtuiError>;
    fn load_packet_snapshot(&self, packet_id: &str) -> Result<PacketSnapshot, FtuiError>;
    fn load_final_evidence_pack(&self) -> Result<FinalEvidencePackSnapshot, FtuiError>;
    fn load_drift_history(&self) -> Result<DriftHistorySnapshot, FtuiError>;
    fn load_conformance_dashboard(&self) -> Result<ConformanceDashboardSnapshot, FtuiError>;
    fn load_forensic_log(&self, path: &Path) -> Result<ForensicLogSnapshot, FtuiError>;
    fn load_governance_gate_snapshot(&self) -> Result<Option<GovernanceGateSnapshot>, FtuiError>;
}

#[derive(Debug, Clone)]
pub struct FsFtuiDataSource {
    phase2c_root: PathBuf,
}

impl FsFtuiDataSource {
    #[must_use]
    pub fn from_repo_root(repo_root: impl AsRef<Path>) -> Self {
        Self {
            phase2c_root: repo_root.as_ref().join(PHASE2C_DIR),
        }
    }

    #[must_use]
    pub fn from_phase2c_root(phase2c_root: impl Into<PathBuf>) -> Self {
        Self {
            phase2c_root: phase2c_root.into(),
        }
    }

    #[must_use]
    pub fn phase2c_root(&self) -> &Path {
        &self.phase2c_root
    }

    fn ensure_root_exists(&self) -> Result<(), FtuiError> {
        if self.phase2c_root.is_dir() {
            Ok(())
        } else {
            Err(FtuiError::ArtifactRootMissing {
                path: self.phase2c_root.clone(),
            })
        }
    }
}

impl FtuiDataSource for FsFtuiDataSource {
    fn discover_packet_ids(&self) -> Result<Vec<String>, FtuiError> {
        self.ensure_root_exists()?;
        let mut packet_ids = Vec::new();
        let entries = fs::read_dir(&self.phase2c_root).map_err(|source| FtuiError::Io {
            path: self.phase2c_root.clone(),
            source,
        })?;
        for entry in entries {
            let entry = entry.map_err(|source| FtuiError::Io {
                path: self.phase2c_root.clone(),
                source,
            })?;
            if !entry
                .file_type()
                .map_err(|source| FtuiError::Io {
                    path: entry.path(),
                    source,
                })?
                .is_dir()
            {
                continue;
            }
            let name = entry.file_name();
            let packet_id = name.to_string_lossy();
            if is_valid_packet_id(packet_id.as_ref()) {
                packet_ids.push(packet_id.into_owned());
            }
        }
        packet_ids.sort();
        Ok(packet_ids)
    }

    fn load_packet_snapshot(&self, packet_id: &str) -> Result<PacketSnapshot, FtuiError> {
        self.ensure_root_exists()?;
        if !is_valid_packet_id(packet_id) {
            return Err(FtuiError::InvalidPacketId {
                packet_id: packet_id.to_owned(),
            });
        }

        let packet_root = self.phase2c_root.join(packet_id);
        let mut issues = Vec::new();

        let parity_report: Option<PacketParityReport> =
            read_json_optional(&packet_root.join("parity_report.json"), &mut issues);
        let gate_result: Option<PacketGateResult> =
            read_json_optional(&packet_root.join("parity_gate_result.json"), &mut issues);
        let decode_status = read_json_optional::<DecodeProofArtifact>(
            &packet_root.join("parity_report.decode_proof.json"),
            &mut issues,
        )
        .map(|artifact| artifact.status);
        let mismatch_count = read_json_optional::<MismatchCorpus>(
            &packet_root.join("parity_mismatch_corpus.json"),
            &mut issues,
        )
        .map(|corpus| corpus.mismatch_count);
        let differential_report = read_json_if_present::<DifferentialReport>(
            &packet_root.join(DIFFERENTIAL_REPORT_FILE),
            &mut issues,
        );
        let differential_validation = differential_report
            .as_ref()
            .map(summarize_differential_validation);

        Ok(PacketSnapshot {
            packet_id: packet_id.to_owned(),
            parity_report,
            gate_result,
            decode_status,
            mismatch_count,
            differential_report,
            differential_validation,
            issues,
        })
    }

    fn load_final_evidence_pack(&self) -> Result<FinalEvidencePackSnapshot, FtuiError> {
        self.ensure_root_exists()?;
        let mut packet_ids = self.discover_packet_ids()?;
        packet_ids.sort();

        let mut packets = Vec::with_capacity(packet_ids.len());
        let mut risk_notes = Vec::new();
        for packet_id in packet_ids {
            let packet = self.load_packet_snapshot(&packet_id)?;
            let integrity =
                verify_packet_sidecar_integrity(&self.phase2c_root.join(&packet_id), &packet_id);
            let evidence_packet = build_final_evidence_packet_snapshot(packet, integrity);
            risk_notes.extend(
                evidence_packet
                    .risk_notes
                    .iter()
                    .map(|note| format!("{packet_id}: {note}")),
            );
            packets.push(evidence_packet);
        }

        packets.sort_by(|left, right| left.packet_id.cmp(&right.packet_id));
        risk_notes.sort();
        risk_notes.dedup();

        let total_packets = packets.len();
        let parity_gate_passed = packets
            .iter()
            .filter(|packet| packet.gate_pass == Some(true))
            .count();
        let parity_gate_failed = packets
            .iter()
            .filter(|packet| packet.gate_pass == Some(false))
            .count();
        let parity_gate_missing = packets
            .iter()
            .filter(|packet| packet.gate_pass.is_none())
            .count();
        let sidecar_integrity_passed = packets
            .iter()
            .filter(|packet| packet.sidecar_integrity_ok)
            .count();
        let sidecar_integrity_failed = total_packets.saturating_sub(sidecar_integrity_passed);
        let decode_recovered = packets
            .iter()
            .filter(|packet| packet.decode_status == Some(DecodeProofStatus::Recovered))
            .count();
        let decode_failed_or_missing = total_packets.saturating_sub(decode_recovered);
        let all_checks_passed =
            total_packets > 0 && packets.iter().all(FinalEvidencePacketSnapshot::is_green);

        Ok(FinalEvidencePackSnapshot {
            phase2c_root: self.phase2c_root.clone(),
            packets,
            total_packets,
            parity_gate_passed,
            parity_gate_failed,
            parity_gate_missing,
            sidecar_integrity_passed,
            sidecar_integrity_failed,
            decode_recovered,
            decode_failed_or_missing,
            all_checks_passed,
            risk_notes,
        })
    }

    fn load_drift_history(&self) -> Result<DriftHistorySnapshot, FtuiError> {
        self.ensure_root_exists()?;
        let path = self.phase2c_root.join(DRIFT_HISTORY_FILE);
        let file = match File::open(&path) {
            Ok(file) => file,
            Err(source) if source.kind() == std::io::ErrorKind::NotFound => {
                return Ok(DriftHistorySnapshot {
                    entries: Vec::new(),
                    malformed_lines: 0,
                    missing: true,
                });
            }
            Err(source) => return Err(FtuiError::Io { path, source }),
        };

        let mut entries = Vec::new();
        let mut malformed_lines = 0;

        for line in BufReader::new(file).lines() {
            let line = line.map_err(|source| FtuiError::Io {
                path: path.clone(),
                source,
            })?;
            if line.trim().is_empty() {
                continue;
            }
            match serde_json::from_str::<PacketDriftHistoryEntry>(&line) {
                Ok(entry) => entries.push(entry),
                Err(_) => malformed_lines += 1,
            }
        }

        Ok(DriftHistorySnapshot {
            entries,
            malformed_lines,
            missing: false,
        })
    }

    fn load_conformance_dashboard(&self) -> Result<ConformanceDashboardSnapshot, FtuiError> {
        let packet_ids = self.discover_packet_ids()?;
        let packets = packet_ids
            .iter()
            .map(|packet_id| self.load_packet_snapshot(packet_id))
            .collect::<Result<Vec<_>, _>>()?;
        let drift_history = self.load_drift_history()?;

        let green_packets = packets.iter().filter(|packet| packet.is_green()).count();
        let total_packets = packets.len();
        let failing_packets = total_packets.saturating_sub(green_packets);

        let packet_trends = build_packet_trends(&packets, &drift_history.entries);

        Ok(ConformanceDashboardSnapshot {
            packets,
            drift_history,
            packet_trends,
            total_packets,
            green_packets,
            failing_packets,
        })
    }

    fn load_forensic_log(&self, path: &Path) -> Result<ForensicLogSnapshot, FtuiError> {
        let file = match File::open(path) {
            Ok(file) => file,
            Err(source) if source.kind() == std::io::ErrorKind::NotFound => {
                return Ok(ForensicLogSnapshot {
                    events: Vec::new(),
                    malformed_lines: 0,
                    missing: true,
                });
            }
            Err(source) => {
                return Err(FtuiError::Io {
                    path: path.to_path_buf(),
                    source,
                });
            }
        };

        let mut events = Vec::new();
        let mut malformed_lines = 0;
        for line in BufReader::new(file).lines() {
            let line = line.map_err(|source| FtuiError::Io {
                path: path.to_path_buf(),
                source,
            })?;
            if line.trim().is_empty() {
                continue;
            }
            match serde_json::from_str::<ForensicEvent>(&line) {
                Ok(event) => events.push(event),
                Err(_) => malformed_lines += 1,
            }
        }

        Ok(ForensicLogSnapshot {
            events,
            malformed_lines,
            missing: false,
        })
    }

    fn load_governance_gate_snapshot(&self) -> Result<Option<GovernanceGateSnapshot>, FtuiError> {
        let Some(artifacts_root) = self.phase2c_root.parent() else {
            return Ok(None);
        };
        let path = artifacts_root
            .join(CI_DIR)
            .join(GOVERNANCE_GATE_REPORT_FILE);
        let payload = match fs::read_to_string(&path) {
            Ok(payload) => payload,
            Err(source) if source.kind() == std::io::ErrorKind::NotFound => return Ok(None),
            Err(source) => return Err(FtuiError::Io { path, source }),
        };

        let report: GovernanceGateReport =
            serde_json::from_str(&payload).map_err(|source| FtuiError::Io {
                path: path.clone(),
                source: std::io::Error::new(std::io::ErrorKind::InvalidData, source),
            })?;

        Ok(Some(GovernanceGateSnapshot {
            path,
            all_passed: report.all_passed,
            violation_count: report.violation_count,
            generated_unix_ms: report.generated_unix_ms,
        }))
    }
}

#[derive(Debug, Deserialize)]
struct MismatchCorpus {
    mismatch_count: usize,
}

#[derive(Debug, Deserialize)]
struct GovernanceGateReport {
    generated_unix_ms: u128,
    all_passed: bool,
    violation_count: usize,
}

fn build_final_evidence_packet_snapshot(
    packet: PacketSnapshot,
    sidecar_integrity: SidecarIntegrityResult,
) -> FinalEvidencePacketSnapshot {
    let risk_notes = collect_packet_risk_notes(&packet, &sidecar_integrity);
    let PacketSnapshot {
        packet_id,
        parity_report,
        gate_result,
        decode_status,
        mismatch_count: _,
        differential_report: _,
        differential_validation: _,
        issues,
    } = packet;

    let parity_green = parity_report
        .as_ref()
        .is_some_and(PacketParityReport::is_green);
    let gate_pass = gate_result.as_ref().map(|gate| gate.pass);
    FinalEvidencePacketSnapshot {
        packet_id,
        gate_pass,
        parity_green,
        decode_status,
        sidecar_integrity_ok: sidecar_integrity.is_ok(),
        sidecar_integrity_errors: sidecar_integrity.errors,
        artifact_issues: issues,
        risk_notes,
    }
}

fn collect_packet_risk_notes(
    packet: &PacketSnapshot,
    sidecar_integrity: &SidecarIntegrityResult,
) -> Vec<String> {
    let mut notes = Vec::new();
    match packet.gate_result.as_ref() {
        Some(gate) if !gate.pass => {
            if gate.reasons.is_empty() {
                notes.push("parity gate failed without explicit reasons".to_owned());
            } else {
                notes.push(format!("parity gate failed: {}", gate.reasons.join("; ")));
            }
        }
        None => notes.push("missing parity gate result".to_owned()),
        Some(_) => {}
    }

    match packet.parity_report.as_ref() {
        Some(report) if !report.is_green() => {
            notes.push(format!(
                "parity report not green: passed={} failed={}",
                report.passed, report.failed
            ));
        }
        None => notes.push("missing or unreadable parity report".to_owned()),
        Some(_) => {}
    }

    match packet.decode_status.as_ref() {
        Some(DecodeProofStatus::Recovered) => {}
        Some(status) => notes.push(format!("decode proof status is {status}")),
        None => notes.push("missing decode proof status".to_owned()),
    }

    if !sidecar_integrity.is_ok() {
        notes.extend(sidecar_integrity.errors.iter().cloned());
    }
    notes.extend(packet.issues.iter().map(|issue| {
        format!(
            "artifact issue ({:?}) {}: {}",
            issue.kind,
            issue.path.display(),
            issue.detail
        )
    }));

    notes.sort();
    notes.dedup();
    notes
}

fn read_json_optional<T: DeserializeOwned>(
    path: &Path,
    issues: &mut Vec<ArtifactIssue>,
) -> Option<T> {
    match fs::read_to_string(path) {
        Ok(content) => match serde_json::from_str::<T>(&content) {
            Ok(parsed) => Some(parsed),
            Err(error) => {
                issues.push(ArtifactIssue {
                    path: path.to_path_buf(),
                    kind: ArtifactIssueKind::ParseError,
                    detail: error.to_string(),
                });
                None
            }
        },
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
            issues.push(ArtifactIssue {
                path: path.to_path_buf(),
                kind: ArtifactIssueKind::MissingFile,
                detail: "file not found".to_owned(),
            });
            None
        }
        Err(error) => {
            issues.push(ArtifactIssue {
                path: path.to_path_buf(),
                kind: ArtifactIssueKind::IoError,
                detail: error.to_string(),
            });
            None
        }
    }
}

fn read_json_if_present<T: DeserializeOwned>(
    path: &Path,
    issues: &mut Vec<ArtifactIssue>,
) -> Option<T> {
    match fs::read_to_string(path) {
        Ok(content) => match serde_json::from_str::<T>(&content) {
            Ok(parsed) => Some(parsed),
            Err(error) => {
                issues.push(ArtifactIssue {
                    path: path.to_path_buf(),
                    kind: ArtifactIssueKind::ParseError,
                    detail: error.to_string(),
                });
                None
            }
        },
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
        Err(error) => {
            issues.push(ArtifactIssue {
                path: path.to_path_buf(),
                kind: ArtifactIssueKind::IoError,
                detail: error.to_string(),
            });
            None
        }
    }
}

#[must_use]
pub fn is_valid_packet_id(packet_id: &str) -> bool {
    let Some(rest) = packet_id.strip_prefix("FP-P2C-") else {
        return false;
    };
    rest.len() == 3 && rest.as_bytes().iter().all(u8::is_ascii_digit)
}

#[must_use]
pub fn summarize_conformal_guard(guard: &ConformalGuard) -> ConformalSnapshot {
    ConformalSnapshot {
        calibrated: guard.is_calibrated(),
        calibration_count: guard.calibration_count(),
        quantile_threshold: guard.conformal_quantile(),
        empirical_coverage: guard.empirical_coverage(),
        coverage_alert: guard.coverage_alert(),
    }
}

#[must_use]
pub fn summarize_decision_dashboard(
    ledger: &EvidenceLedger,
    policy: &RuntimePolicy,
    evidence_term_cap: usize,
) -> DecisionDashboardSnapshot {
    let mut strict_records = 0;
    let mut hardened_records = 0;
    let mut cards = Vec::with_capacity(ledger.records().len());

    for record in ledger.records() {
        match record.mode {
            RuntimeMode::Strict => strict_records += 1,
            RuntimeMode::Hardened => hardened_records += 1,
        }
        let evidence_terms_total = record.evidence.len();
        cards.push(DecisionCardSnapshot {
            mode: record.mode,
            card: decision_to_card(record).render_plain(),
            evidence_terms_total,
            evidence_terms_shown: evidence_terms_total.min(evidence_term_cap),
        });
    }

    DecisionDashboardSnapshot {
        total_records: strict_records + hardened_records,
        strict_records,
        hardened_records,
        policy: PolicySnapshot {
            mode: policy.mode,
            fail_closed_unknown_features: policy.fail_closed_unknown_features,
            hardened_join_row_cap: policy.hardened_join_row_cap,
        },
        cards,
        evidence_term_cap,
    }
}

#[cfg(test)]
mod tests {
    use std::{fs, hint::black_box, path::Path, time::Instant};

    use fp_conformance::{
        CaseStatus, ComparisonCategory, DecodeProofArtifact, DecodeProofStatus, DifferentialReport,
        DifferentialResult, DriftLevel, DriftRecord, E2eReport, FixtureOperation,
        FixtureOracleSource, ForensicEventKind, HarnessConfig, OracleMode, PacketDriftHistoryEntry,
        generate_raptorq_sidecar, run_raptorq_decode_recovery_drill,
    };
    use fp_runtime::{EvidenceLedger, RuntimePolicy};
    use proptest::prelude::*;
    use serde_json::json;
    use tempfile::tempdir;

    use super::{
        ArtifactIssueKind, DashboardView, FsFtuiDataSource, FtuiAppState, FtuiDataSource,
        build_frankentui_e2e_replay_bundles_baseline_with_stats,
        build_frankentui_e2e_replay_bundles_optimized_with_stats, default_frankentui_e2e_scenarios,
        differential_validation_log_entries, is_valid_packet_id,
        run_differential_validation_by_packet, run_frankentui_e2e_scenario,
        summarize_decision_dashboard, summarize_differential_validation,
    };

    fn emit_test_log(
        packet_id: &str,
        case_id: &str,
        mode: &str,
        seed: u64,
        assertion_path: &str,
        result: &str,
    ) {
        let trace_id = format!("{packet_id}::{case_id}::seed-{seed}");
        println!(
            "{}",
            json!({
                "packet_id": packet_id,
                "case_id": case_id,
                "mode": mode,
                "seed": seed,
                "trace_id": trace_id,
                "assertion_path": assertion_path,
                "result": result
            })
        );
    }

    fn emit_differential_validation_log(entry: &super::DifferentialValidationLogEntry) {
        println!(
            "{}",
            json!({
                "packet_id": entry.packet_id,
                "case_id": entry.case_id,
                "mode": entry.mode,
                "trace_id": entry.trace_id,
                "oracle_source": entry.oracle_source,
                "mismatch_class": entry.mismatch_class,
                "replay_key": entry.replay_key
            })
        );
    }

    fn emit_e2e_replay_log(entry: &super::FrankentuiE2eReplayBundleEntry) {
        println!(
            "{}",
            json!({
                "scenario_id": entry.scenario_id,
                "packet_id": entry.packet_id,
                "mode": entry.mode,
                "trace_id": entry.trace_id,
                "step_id": entry.step_id,
                "decision_action": entry.decision_action,
                "latency_ms": entry.latency_ms,
                "failure_diagnostics": entry.failure_diagnostics,
                "replay_key": entry.replay_key
            })
        );
    }

    fn force_replay_bundle_mode_fallback(report: &mut E2eReport) {
        for event in &mut report.forensic_log.events {
            if let ForensicEventKind::CaseEnd {
                packet_id,
                case_id,
                replay_key,
                ..
            } = &mut event.event
            {
                *replay_key = format!("{packet_id}/{case_id}/mode_unknown");
            }
        }
    }

    fn amplify_replay_bundle_mode_lookups(report: &mut E2eReport, repeats: usize) {
        let Some(packet_report) = report.packet_reports.first_mut() else {
            return;
        };
        let base_results = packet_report.results.clone();
        let base_case_end_events: Vec<_> = report
            .forensic_log
            .events
            .iter()
            .filter(|event| matches!(event.event, ForensicEventKind::CaseEnd { .. }))
            .cloned()
            .collect();

        for repeat in 0..repeats {
            for template in &base_results {
                let mut result = template.clone();
                let new_case_id = format!("{}::amp{repeat}", result.case_id);
                result.case_id = new_case_id.clone();
                result.trace_id = format!("{}::amp{repeat}", result.trace_id);
                result.replay_key = format!("{}/{new_case_id}/mode_unknown", result.packet_id);
                packet_report.results.push(result);
            }
            for template in &base_case_end_events {
                let mut event = template.clone();
                if let ForensicEventKind::CaseEnd {
                    packet_id,
                    case_id,
                    trace_id,
                    step_id,
                    replay_key,
                    ..
                } = &mut event.event
                {
                    let new_case_id = format!("{case_id}::amp{repeat}");
                    *case_id = new_case_id.clone();
                    *trace_id = format!("{trace_id}::amp{repeat}");
                    *step_id = format!("{step_id}::amp{repeat}");
                    *replay_key = format!("{packet_id}/{new_case_id}/mode_unknown");
                }
                report.forensic_log.events.push(event);
            }
        }
    }

    fn quantile_from_sorted(samples: &[u128], pct: usize) -> u128 {
        let len = samples.len();
        assert!(len > 0);
        let idx = (len.saturating_sub(1) * pct) / 100;
        samples[idx]
    }

    fn latency_quantiles(mut samples_ns: Vec<u128>) -> (u128, u128, u128) {
        samples_ns.sort_unstable();
        (
            quantile_from_sorted(&samples_ns, 50),
            quantile_from_sorted(&samples_ns, 95),
            quantile_from_sorted(&samples_ns, 99),
        )
    }

    fn packet_trends_former_for_profile(
        packets: &[super::PacketSnapshot],
        entries: &[PacketDriftHistoryEntry],
    ) -> Vec<super::PacketTrendSnapshot> {
        packets
            .iter()
            .map(|packet| {
                let mut samples = 0_usize;
                let mut latest: Option<&PacketDriftHistoryEntry> = None;
                for entry in entries {
                    if entry.packet_id == packet.packet_id {
                        samples += 1;
                        if latest.is_none_or(|current| entry.ts_unix_ms >= current.ts_unix_ms) {
                            latest = Some(entry);
                        }
                    }
                }
                super::PacketTrendSnapshot {
                    packet_id: packet.packet_id.clone(),
                    samples,
                    latest_gate_pass: latest.map(|entry| entry.gate_pass),
                    latest_failed_cases: latest.map(|entry| entry.failed),
                }
            })
            .collect()
    }

    fn packet_snapshot_for_trend_test(packet_id: &str) -> super::PacketSnapshot {
        super::PacketSnapshot {
            packet_id: packet_id.to_owned(),
            parity_report: None,
            gate_result: None,
            decode_status: None,
            mismatch_count: None,
            differential_report: None,
            differential_validation: None,
            issues: Vec::new(),
        }
    }

    fn drift_entry_for_trend_test(
        packet_id: &str,
        ts_unix_ms: u64,
        gate_pass: bool,
        failed: usize,
    ) -> PacketDriftHistoryEntry {
        PacketDriftHistoryEntry {
            ts_unix_ms,
            packet_id: packet_id.to_owned(),
            suite: "phase2c_packets".to_owned(),
            fixture_count: 16,
            passed: 16_usize.saturating_sub(failed),
            failed,
            strict_failed: failed,
            hardened_failed: 0,
            gate_pass,
            report_hash: format!("sha256:{packet_id}:{ts_unix_ms}:{failed}"),
        }
    }

    #[test]
    fn packet_trends_index_preserves_former_order_and_latest_semantics() {
        let packets = [
            packet_snapshot_for_trend_test("FP-P2C-B"),
            packet_snapshot_for_trend_test("FP-P2C-A"),
            packet_snapshot_for_trend_test("FP-P2C-MISSING"),
        ];
        let entries = [
            drift_entry_for_trend_test("FP-P2C-A", 10, false, 4),
            drift_entry_for_trend_test("FP-P2C-IRRELEVANT", 999, false, 9),
            drift_entry_for_trend_test("FP-P2C-A", 5, false, 8),
            drift_entry_for_trend_test("FP-P2C-B", 7, false, 3),
            drift_entry_for_trend_test("FP-P2C-A", 10, true, 1),
        ];

        let former = packet_trends_former_for_profile(&packets, &entries);
        let indexed = super::build_packet_trends(&packets, &entries);
        assert_eq!(indexed, former);
        assert_eq!(
            indexed,
            vec![
                super::PacketTrendSnapshot {
                    packet_id: "FP-P2C-B".to_owned(),
                    samples: 1,
                    latest_gate_pass: Some(false),
                    latest_failed_cases: Some(3),
                },
                super::PacketTrendSnapshot {
                    packet_id: "FP-P2C-A".to_owned(),
                    samples: 3,
                    latest_gate_pass: Some(true),
                    latest_failed_cases: Some(1),
                },
                super::PacketTrendSnapshot {
                    packet_id: "FP-P2C-MISSING".to_owned(),
                    samples: 0,
                    latest_gate_pass: None,
                    latest_failed_cases: None,
                },
            ]
        );

        let empty = super::build_packet_trends(&packets, &[]);
        assert!(
            empty
                .iter()
                .all(|trend| trend.samples == 0 && trend.latest_gate_pass.is_none())
        );
        assert!(super::build_packet_trends(&[], &entries).is_empty());
    }

    #[test]
    #[ignore = "manual normal-release performance attribution"]
    fn packet_trends_index_profile_snapshot() {
        const PACKETS: usize = 11;
        const DISTINCT_HISTORY_IDS: usize = 437;
        const HISTORY_ROWS: usize = 105_486;
        const SAMPLES: usize = 16;

        let packets = (0..PACKETS)
            .map(|index| super::PacketSnapshot {
                packet_id: format!("FP-P2C-{index:03}"),
                parity_report: None,
                gate_result: None,
                decode_status: None,
                mismatch_count: None,
                differential_report: None,
                differential_validation: None,
                issues: Vec::new(),
            })
            .collect::<Vec<_>>();
        let entries = (0..HISTORY_ROWS)
            .map(|index| PacketDriftHistoryEntry {
                ts_unix_ms: index as u64,
                packet_id: format!("FP-P2C-{:03}", index % DISTINCT_HISTORY_IDS),
                suite: "phase2c_packets".to_owned(),
                fixture_count: 16,
                passed: 15,
                failed: index % 7,
                strict_failed: index % 3,
                hardened_failed: index % 5,
                gate_pass: index % 7 == 0,
                report_hash: "sha256:packet-trend-profile".to_owned(),
            })
            .collect::<Vec<_>>();

        let former = packet_trends_former_for_profile(&packets, &entries);
        let indexed = super::build_packet_trends(&packets, &entries);
        assert_eq!(indexed, former);
        for _ in 0..2 {
            black_box(packet_trends_former_for_profile(
                black_box(&packets),
                black_box(&entries),
            ));
            black_box(super::build_packet_trends(
                black_box(&packets),
                black_box(&entries),
            ));
        }

        let mut former_ns = Vec::with_capacity(SAMPLES);
        let mut indexed_ns = Vec::with_capacity(SAMPLES);
        for sample in 0..SAMPLES {
            let measure_former = || {
                let started = Instant::now();
                black_box(packet_trends_former_for_profile(
                    black_box(&packets),
                    black_box(&entries),
                ));
                started.elapsed().as_nanos()
            };
            let measure_indexed = || {
                let started = Instant::now();
                black_box(super::build_packet_trends(
                    black_box(&packets),
                    black_box(&entries),
                ));
                started.elapsed().as_nanos()
            };
            if sample % 2 == 0 {
                former_ns.push(measure_former());
                indexed_ns.push(measure_indexed());
            } else {
                indexed_ns.push(measure_indexed());
                former_ns.push(measure_former());
            }
        }

        let former_quantiles = latency_quantiles(former_ns.clone());
        let indexed_quantiles = latency_quantiles(indexed_ns.clone());
        former_ns.sort_unstable();
        indexed_ns.sort_unstable();
        println!(
            "packet_trends_index_profile_snapshot former_ns[p50={},p95={},p99={};samples={former_ns:?}] indexed_ns[p50={},p95={},p99={};samples={indexed_ns:?}] history_rows={HISTORY_ROWS} packets={PACKETS} distinct_history_ids={DISTINCT_HISTORY_IDS}",
            former_quantiles.0,
            former_quantiles.1,
            former_quantiles.2,
            indexed_quantiles.0,
            indexed_quantiles.1,
            indexed_quantiles.2,
        );
    }

    fn write_packet_with_raptorq_artifacts(packet_root: &Path, packet_id: &str, gate_pass: bool) {
        let parity_payload = json!({
            "suite": "phase2c_packets",
            "packet_id": packet_id,
            "oracle_present": true,
            "fixture_count": 1,
            "passed": if gate_pass { 1 } else { 0 },
            "failed": if gate_pass { 0 } else { 1 },
            "results": []
        })
        .to_string();
        fs::write(packet_root.join("parity_report.json"), &parity_payload).expect("write parity");
        fs::write(
            packet_root.join("parity_gate_result.json"),
            json!({
                "packet_id": packet_id,
                "pass": gate_pass,
                "fixture_count": 1,
                "strict_total": 1,
                "strict_failed": if gate_pass { 0 } else { 1 },
                "hardened_total": 0,
                "hardened_failed": 0,
                "reasons": if gate_pass {
                    Vec::<String>::new()
                } else {
                    vec!["forced gate failure".to_owned()]
                }
            })
            .to_string(),
        )
        .expect("write gate");
        fs::write(
            packet_root.join("parity_mismatch_corpus.json"),
            json!({
                "packet_id": packet_id,
                "mismatch_count": if gate_pass { 0 } else { 1 },
                "mismatches": []
            })
            .to_string(),
        )
        .expect("write mismatch corpus");

        let parity_bytes = parity_payload.as_bytes();
        let mut sidecar = generate_raptorq_sidecar(
            &format!("{packet_id}/parity_report"),
            "conformance",
            parity_bytes,
            8,
        )
        .expect("generate sidecar");
        let proof =
            run_raptorq_decode_recovery_drill(&sidecar, parity_bytes).expect("decode drill");
        sidecar.envelope.decode_proofs = vec![proof.clone()];
        sidecar.envelope.scrub.status = "ok".to_owned();
        sidecar.scrub_report.status = "ok".to_owned();
        sidecar.scrub_report.source_hash_verified = true;
        sidecar.scrub_report.invalid_packets = 0;
        fs::write(
            packet_root.join("parity_report.raptorq.json"),
            serde_json::to_string_pretty(&sidecar).expect("serialize sidecar"),
        )
        .expect("write sidecar");

        let proof_artifact = DecodeProofArtifact {
            packet_id: packet_id.to_owned(),
            decode_proofs: vec![proof],
            status: DecodeProofStatus::Recovered,
        };
        fs::write(
            packet_root.join("parity_report.decode_proof.json"),
            serde_json::to_string_pretty(&proof_artifact).expect("serialize proof"),
        )
        .expect("write decode proof");
    }

    fn tamper_decode_proof_hash(packet_root: &Path) {
        let proof_path = packet_root.join("parity_report.decode_proof.json");
        let mut proof: DecodeProofArtifact =
            serde_json::from_str(&fs::read_to_string(&proof_path).expect("read decode proof"))
                .expect("parse decode proof");
        assert!(
            !proof.decode_proofs.is_empty(),
            "expected decode proof entries"
        );
        proof.decode_proofs[0].proof_hash = "sha256:deadbeef".to_owned();
        fs::write(
            proof_path,
            serde_json::to_string_pretty(&proof).expect("serialize tampered decode proof"),
        )
        .expect("write tampered decode proof");
    }

    #[test]
    fn packet_id_validation_accepts_expected_shape() {
        emit_test_log(
            "FRANKENTUI-E",
            "packet_id_validation_accepts_expected_shape",
            "n/a",
            1,
            "is_valid_packet_id static examples",
            "pass",
        );
        assert!(is_valid_packet_id("FP-P2C-001"));
        assert!(is_valid_packet_id("FP-P2C-999"));
        assert!(!is_valid_packet_id("FP-P2C-12"));
        assert!(!is_valid_packet_id("FP-P2C-1000"));
        assert!(!is_valid_packet_id("fp-p2c-001"));
        assert!(!is_valid_packet_id("../FP-P2C-001"));
    }

    #[test]
    fn discover_packet_ids_filters_non_packet_entries() {
        let dir = tempdir().expect("tempdir");
        let root = dir.path().join("artifacts/phase2c");
        fs::create_dir_all(root.join("FP-P2C-001")).expect("packet dir");
        fs::create_dir_all(root.join("scratch")).expect("scratch dir");
        fs::write(root.join("drift_history.jsonl"), "").expect("history file");
        let source = FsFtuiDataSource::from_repo_root(dir.path());
        let ids = source.discover_packet_ids().expect("discover ids");
        assert_eq!(ids, vec!["FP-P2C-001".to_owned()]);
    }

    #[test]
    fn load_drift_history_handles_missing_file() {
        let dir = tempdir().expect("tempdir");
        let root = dir.path().join("artifacts/phase2c");
        fs::create_dir_all(&root).expect("phase2c root");
        let source = FsFtuiDataSource::from_repo_root(dir.path());
        let history = source.load_drift_history().expect("load history");
        assert!(history.missing);
        assert_eq!(history.malformed_lines, 0);
        assert!(history.entries.is_empty());
    }

    #[test]
    fn load_drift_history_skips_malformed_lines() {
        let dir = tempdir().expect("tempdir");
        let root = dir.path().join("artifacts/phase2c");
        fs::create_dir_all(&root).expect("phase2c root");
        let entry = PacketDriftHistoryEntry {
            ts_unix_ms: 1,
            packet_id: "FP-P2C-001".to_owned(),
            suite: "phase2c_packets".to_owned(),
            fixture_count: 2,
            passed: 2,
            failed: 0,
            strict_failed: 0,
            hardened_failed: 0,
            gate_pass: true,
            report_hash: "sha256:abc".to_owned(),
        };
        let line = serde_json::to_string(&entry).expect("serialize entry");
        let history_path = root.join("drift_history.jsonl");
        fs::write(&history_path, format!("{line}\nnot-json\n{{\"partial\":"))
            .expect("write history");

        let source = FsFtuiDataSource::from_repo_root(dir.path());
        let history = source.load_drift_history().expect("load history");
        assert!(!history.missing);
        assert_eq!(history.entries.len(), 1);
        assert_eq!(history.malformed_lines, 2);
    }

    #[test]
    fn packet_snapshot_collects_missing_and_parse_issues() {
        let dir = tempdir().expect("tempdir");
        let packet_root = dir.path().join("artifacts/phase2c/FP-P2C-001");
        fs::create_dir_all(&packet_root).expect("packet root");
        fs::write(packet_root.join("parity_report.json"), "{\"bad\":").expect("bad json");
        fs::write(
            packet_root.join("parity_mismatch_corpus.json"),
            "{\"packet_id\":\"FP-P2C-001\",\"mismatch_count\":7,\"mismatches\":[]}",
        )
        .expect("mismatch corpus");
        fs::write(
            packet_root.join("parity_report.decode_proof.json"),
            "{\"packet_id\":\"FP-P2C-001\",\"decode_proofs\":[],\"status\":\"recovered\"}",
        )
        .expect("decode proof");

        let source = FsFtuiDataSource::from_repo_root(dir.path());
        let snapshot = source
            .load_packet_snapshot("FP-P2C-001")
            .expect("packet snapshot");

        assert!(snapshot.parity_report.is_none());
        assert!(snapshot.gate_result.is_none());
        assert_eq!(snapshot.mismatch_count, Some(7));
        assert!(snapshot.decode_status.is_some());
        assert!(
            snapshot
                .issues
                .iter()
                .any(|i| i.kind == ArtifactIssueKind::ParseError),
            "expected parse issue"
        );
        assert!(
            snapshot
                .issues
                .iter()
                .any(|i| i.kind == ArtifactIssueKind::MissingFile),
            "expected missing-file issue"
        );
        assert!(snapshot.differential_report.is_none());
        assert!(snapshot.differential_validation.is_none());
    }

    #[test]
    fn packet_snapshot_flags_truncated_differential_report() {
        let dir = tempdir().expect("tempdir");
        let packet_root = dir.path().join("artifacts/phase2c/FP-P2C-001");
        fs::create_dir_all(&packet_root).expect("packet root");
        fs::write(
            packet_root.join("parity_report.json"),
            json!({
                "suite": "phase2c_packets",
                "packet_id": "FP-P2C-001",
                "oracle_present": true,
                "fixture_count": 1,
                "passed": 1,
                "failed": 0,
                "results": []
            })
            .to_string(),
        )
        .expect("parity");
        fs::write(
            packet_root.join("parity_gate_result.json"),
            json!({
                "packet_id": "FP-P2C-001",
                "pass": true,
                "fixture_count": 1,
                "strict_total": 1,
                "strict_failed": 0,
                "hardened_total": 0,
                "hardened_failed": 0,
                "reasons": []
            })
            .to_string(),
        )
        .expect("gate");
        fs::write(
            packet_root.join("parity_mismatch_corpus.json"),
            "{\"packet_id\":\"FP-P2C-001\",\"mismatch_count\":0,\"mismatches\":[]}",
        )
        .expect("mismatch");
        fs::write(
            packet_root.join("parity_report.decode_proof.json"),
            "{\"packet_id\":\"FP-P2C-001\",\"decode_proofs\":[],\"status\":\"recovered\"}",
        )
        .expect("decode proof");
        fs::write(packet_root.join("differential_report.json"), "{\"report\":")
            .expect("truncated diff");

        let source = FsFtuiDataSource::from_repo_root(dir.path());
        let snapshot = source
            .load_packet_snapshot("FP-P2C-001")
            .expect("packet snapshot");

        assert!(snapshot.differential_report.is_none());
        assert!(snapshot.differential_validation.is_none());
        assert!(
            snapshot.issues.iter().any(|issue| {
                issue.kind == ArtifactIssueKind::ParseError
                    && issue.path.ends_with("differential_report.json")
            }),
            "expected parse error for differential report"
        );
    }

    #[test]
    fn differential_validation_separates_strict_vs_hardened_taxonomy() {
        let report = DifferentialReport {
            report: fp_conformance::PacketParityReport {
                suite: "phase2c_packets:FP-P2C-001".to_owned(),
                packet_id: Some("FP-P2C-001".to_owned()),
                oracle_present: true,
                fixture_count: 3,
                passed: 1,
                failed: 2,
                results: Vec::new(),
            },
            differential_results: vec![
                DifferentialResult {
                    case_id: "strict_critical".to_owned(),
                    packet_id: "FP-P2C-001".to_owned(),
                    operation: FixtureOperation::SeriesAdd,
                    mode: fp_runtime::RuntimeMode::Strict,
                    replay_key: String::new(),
                    trace_id: String::new(),
                    oracle_source: FixtureOracleSource::Fixture,
                    status: CaseStatus::Fail,
                    drift_records: vec![DriftRecord {
                        category: ComparisonCategory::Value,
                        level: DriftLevel::Critical,
                        mismatch_class: "value_critical".to_owned(),
                        location: "series.values[0]".to_owned(),
                        message: "forced strict drift".to_owned(),
                    }],
                    evidence_records: 0,
                },
                DifferentialResult {
                    case_id: "hardened_allowlisted".to_owned(),
                    packet_id: "FP-P2C-001".to_owned(),
                    operation: FixtureOperation::SeriesAdd,
                    mode: fp_runtime::RuntimeMode::Hardened,
                    replay_key: String::new(),
                    trace_id: String::new(),
                    oracle_source: FixtureOracleSource::LiveLegacyPandas,
                    status: CaseStatus::Pass,
                    drift_records: vec![DriftRecord {
                        category: ComparisonCategory::Index,
                        level: DriftLevel::NonCritical,
                        mismatch_class: "index_non_critical".to_owned(),
                        location: "series.index".to_owned(),
                        message: "forced hardened allowlist drift".to_owned(),
                    }],
                    evidence_records: 0,
                },
                DifferentialResult {
                    case_id: "hardened_critical".to_owned(),
                    packet_id: "FP-P2C-001".to_owned(),
                    operation: FixtureOperation::SeriesAdd,
                    mode: fp_runtime::RuntimeMode::Hardened,
                    replay_key: String::new(),
                    trace_id: String::new(),
                    oracle_source: FixtureOracleSource::Fixture,
                    status: CaseStatus::Fail,
                    drift_records: vec![DriftRecord {
                        category: ComparisonCategory::Shape,
                        level: DriftLevel::Critical,
                        mismatch_class: "shape_critical".to_owned(),
                        location: "series.len".to_owned(),
                        message: "forced hardened hard failure".to_owned(),
                    }],
                    evidence_records: 0,
                },
            ],
            drift_summary: fp_conformance::DriftSummary {
                total_drift_records: 3,
                critical_count: 2,
                non_critical_count: 1,
                informational_count: 0,
                categories: Vec::new(),
            },
        };

        let summary = summarize_differential_validation(&report);
        let entries = differential_validation_log_entries(&report);

        assert_eq!(summary.total_cases, 3);
        assert_eq!(summary.strict_critical_violations, 1);
        assert_eq!(summary.hardened_allowlisted_divergence, 1);
        assert_eq!(summary.hardened_critical_violations, 1);
        assert_eq!(entries.len(), 3);
        for entry in &entries {
            emit_differential_validation_log(entry);
        }

        let strict_entry = entries
            .iter()
            .find(|entry| entry.case_id == "strict_critical")
            .expect("strict entry");
        assert_eq!(strict_entry.trace_id, "FP-P2C-001:strict_critical:strict");
        assert_eq!(strict_entry.replay_key, "FP-P2C-001/strict_critical/strict");
        assert_eq!(strict_entry.mismatch_class, "value_critical");
    }

    #[test]
    fn differential_validation_workflow_is_deterministic_for_packet() {
        let cfg = HarnessConfig::default_paths();
        let first =
            run_differential_validation_by_packet(&cfg, "FP-P2C-001", OracleMode::FixtureExpected)
                .expect("first differential validation");
        let second =
            run_differential_validation_by_packet(&cfg, "FP-P2C-001", OracleMode::FixtureExpected)
                .expect("second differential validation");

        assert_eq!(first.logs, second.logs);
        assert_eq!(first.summary, second.summary);
        assert!(!first.logs.is_empty());
        for entry in &first.logs {
            assert!(!entry.trace_id.is_empty());
            assert!(!entry.replay_key.is_empty());
            assert!(!entry.mismatch_class.is_empty());
            emit_differential_validation_log(entry);
        }
    }

    #[test]
    fn e2e_scenario_matrix_covers_golden_regression_and_failure_injection() {
        let scenarios = default_frankentui_e2e_scenarios();
        assert_eq!(scenarios.len(), 3);
        assert!(
            scenarios
                .iter()
                .any(|scenario| matches!(scenario.kind, super::FrankentuiE2eScenarioKind::Golden))
        );
        assert!(
            scenarios.iter().any(|scenario| matches!(
                scenario.kind,
                super::FrankentuiE2eScenarioKind::Regression
            ))
        );
        assert!(scenarios.iter().any(|scenario| matches!(
            scenario.kind,
            super::FrankentuiE2eScenarioKind::FailureInjection
        )));
    }

    #[test]
    fn e2e_regression_scenario_emits_replay_bundle_fields() {
        let cfg = HarnessConfig::default_paths();
        let scenario = super::FrankentuiE2eScenario {
            scenario_id: "frankentui_e2e_regression".to_owned(),
            kind: super::FrankentuiE2eScenarioKind::Regression,
            packet_filter: Some("FP-P2C-001".to_owned()),
        };
        let report = run_frankentui_e2e_scenario(&cfg, &scenario).expect("run e2e scenario");

        assert!(!report.replay_bundles.is_empty());
        for entry in &report.replay_bundles {
            assert!(!entry.scenario_id.is_empty());
            assert!(!entry.packet_id.is_empty());
            assert!(!entry.trace_id.is_empty());
            assert!(!entry.step_id.is_empty());
            assert!(!entry.decision_action.is_empty());
            assert!(!entry.replay_key.is_empty());
            assert!(!entry.replay_cmd.is_empty());
            assert!(entry.latency_ms >= 1);
            emit_e2e_replay_log(entry);
        }
    }

    #[test]
    fn e2e_failure_injection_scenario_produces_repair_forensics_bundle() {
        let cfg = HarnessConfig::default_paths();
        let scenario = super::FrankentuiE2eScenario {
            scenario_id: "frankentui_e2e_failure_injection".to_owned(),
            kind: super::FrankentuiE2eScenarioKind::FailureInjection,
            packet_filter: Some("FP-P2C-001".to_owned()),
        };
        let report = run_frankentui_e2e_scenario(&cfg, &scenario).expect("run e2e scenario");

        assert!(report.report.total_failed >= 1);
        assert!(!report.report.gates_pass);
        assert!(!report.forensics.failures.is_empty());
        let injected = report
            .replay_bundles
            .iter()
            .find(|entry| entry.mismatch_class.as_deref() == Some("synthetic_failure_injection"))
            .expect("synthetic failure replay bundle");
        assert_eq!(injected.decision_action, "repair");
        assert!(
            injected
                .failure_diagnostics
                .contains("synthetic failure injection"),
            "expected synthetic failure diagnostic"
        );
        emit_e2e_replay_log(injected);
    }

    #[test]
    fn e2e_replay_bundle_optimized_path_is_isomorphic_to_baseline() {
        let cfg = HarnessConfig::default_paths();
        let scenario = super::FrankentuiE2eScenario {
            scenario_id: "frankentui_e2e_profile_probe".to_owned(),
            kind: super::FrankentuiE2eScenarioKind::Regression,
            packet_filter: Some("FP-P2C-001".to_owned()),
        };
        let mut scenario_report =
            run_frankentui_e2e_scenario(&cfg, &scenario).expect("run e2e profile probe");
        force_replay_bundle_mode_fallback(&mut scenario_report.report);
        amplify_replay_bundle_mode_lookups(&mut scenario_report.report, 512);

        let (baseline, baseline_stats) = build_frankentui_e2e_replay_bundles_baseline_with_stats(
            &scenario_report.report,
            &scenario_report.forensics,
        );
        let (optimized, optimized_stats) = build_frankentui_e2e_replay_bundles_optimized_with_stats(
            &scenario_report.report,
            &scenario_report.forensics,
        );

        assert_eq!(optimized, baseline);
        assert!(
            baseline_stats.mode_lookup_steps > optimized_stats.mode_lookup_steps,
            "expected indexed lookup to reduce fallback steps"
        );
    }

    #[test]
    fn e2e_replay_bundle_profile_snapshot_reports_lookup_delta() {
        const ITERATIONS: usize = 64;
        let cfg = HarnessConfig::default_paths();
        let scenario = super::FrankentuiE2eScenario {
            scenario_id: "frankentui_e2e_profile_snapshot".to_owned(),
            kind: super::FrankentuiE2eScenarioKind::Regression,
            packet_filter: Some("FP-P2C-001".to_owned()),
        };
        let mut scenario_report =
            run_frankentui_e2e_scenario(&cfg, &scenario).expect("run e2e profile snapshot");
        force_replay_bundle_mode_fallback(&mut scenario_report.report);
        amplify_replay_bundle_mode_lookups(&mut scenario_report.report, 512);

        let mut baseline_ns = Vec::with_capacity(ITERATIONS);
        let mut optimized_ns = Vec::with_capacity(ITERATIONS);
        let mut baseline_mode_lookup_steps_total = 0_usize;
        let mut optimized_mode_lookup_steps_total = 0_usize;

        for _ in 0..ITERATIONS {
            let baseline_start = Instant::now();
            let (baseline, baseline_stats) =
                build_frankentui_e2e_replay_bundles_baseline_with_stats(
                    &scenario_report.report,
                    &scenario_report.forensics,
                );
            baseline_ns.push(baseline_start.elapsed().as_nanos());
            baseline_mode_lookup_steps_total += baseline_stats.mode_lookup_steps;

            let optimized_start = Instant::now();
            let (optimized, optimized_stats) =
                build_frankentui_e2e_replay_bundles_optimized_with_stats(
                    &scenario_report.report,
                    &scenario_report.forensics,
                );
            optimized_ns.push(optimized_start.elapsed().as_nanos());
            optimized_mode_lookup_steps_total += optimized_stats.mode_lookup_steps;

            assert_eq!(optimized, baseline);
            black_box(optimized.len());
        }

        let (baseline_p50_ns, baseline_p95_ns, baseline_p99_ns) = latency_quantiles(baseline_ns);
        let (optimized_p50_ns, optimized_p95_ns, optimized_p99_ns) =
            latency_quantiles(optimized_ns);
        assert!(baseline_mode_lookup_steps_total > optimized_mode_lookup_steps_total);

        println!(
            "frankentui_e2e_replay_bundle_profile_snapshot baseline_ns[p50={baseline_p50_ns},p95={baseline_p95_ns},p99={baseline_p99_ns}] optimized_ns[p50={optimized_p50_ns},p95={optimized_p95_ns},p99={optimized_p99_ns}] mode_lookup_steps_baseline={baseline_mode_lookup_steps_total} mode_lookup_steps_optimized={optimized_mode_lookup_steps_total}"
        );
    }

    #[test]
    fn decision_summary_counts_modes_and_caps_evidence() {
        let mut ledger = EvidenceLedger::new();
        let strict = RuntimePolicy::strict();
        let hardened = RuntimePolicy::hardened(Some(8));
        strict.decide_unknown_feature("feature_x", "unsupported", &mut ledger);
        hardened.decide_join_admission(42, &mut ledger);

        let summary = summarize_decision_dashboard(&ledger, &hardened, 1);
        emit_test_log(
            "FRANKENTUI-E",
            "decision_summary_counts_modes_and_caps_evidence",
            "mixed",
            8,
            "summary mode counters and evidence cap",
            "pass",
        );
        assert_eq!(summary.total_records, 2);
        assert_eq!(summary.strict_records, 1);
        assert_eq!(summary.hardened_records, 1);
        assert!(
            summary
                .cards
                .iter()
                .all(|card| card.evidence_terms_shown == 1)
        );
        assert_eq!(summary.policy.hardened_join_row_cap, Some(8));
    }

    #[test]
    fn conformance_dashboard_aggregates_packet_and_trend_state() {
        let dir = tempdir().expect("tempdir");
        let root = dir.path().join("artifacts/phase2c");
        let packet_a = root.join("FP-P2C-001");
        let packet_b = root.join("FP-P2C-002");
        fs::create_dir_all(&packet_a).expect("packet a");
        fs::create_dir_all(&packet_b).expect("packet b");

        fs::write(
            packet_a.join("parity_report.json"),
            json!({
                "suite": "phase2c_packets",
                "packet_id": "FP-P2C-001",
                "oracle_present": true,
                "fixture_count": 2,
                "passed": 2,
                "failed": 0,
                "results": []
            })
            .to_string(),
        )
        .expect("parity a");
        fs::write(
            packet_a.join("parity_gate_result.json"),
            json!({
                "packet_id": "FP-P2C-001",
                "pass": true,
                "fixture_count": 2,
                "strict_total": 2,
                "strict_failed": 0,
                "hardened_total": 0,
                "hardened_failed": 0,
                "reasons": []
            })
            .to_string(),
        )
        .expect("gate a");

        fs::write(
            packet_b.join("parity_report.json"),
            json!({
                "suite": "phase2c_packets",
                "packet_id": "FP-P2C-002",
                "oracle_present": true,
                "fixture_count": 3,
                "passed": 2,
                "failed": 1,
                "results": []
            })
            .to_string(),
        )
        .expect("parity b");
        fs::write(
            packet_b.join("parity_gate_result.json"),
            json!({
                "packet_id": "FP-P2C-002",
                "pass": false,
                "fixture_count": 3,
                "strict_total": 2,
                "strict_failed": 1,
                "hardened_total": 1,
                "hardened_failed": 0,
                "reasons": ["synthetic gate failure"]
            })
            .to_string(),
        )
        .expect("gate b");

        fs::write(
            root.join("drift_history.jsonl"),
            format!(
                "{}\n{}\n",
                json!({
                    "ts_unix_ms": 1,
                    "packet_id": "FP-P2C-001",
                    "suite": "phase2c_packets",
                    "fixture_count": 2,
                    "passed": 2,
                    "failed": 0,
                    "strict_failed": 0,
                    "hardened_failed": 0,
                    "gate_pass": true,
                    "report_hash": "sha256:a"
                }),
                json!({
                    "ts_unix_ms": 2,
                    "packet_id": "FP-P2C-002",
                    "suite": "phase2c_packets",
                    "fixture_count": 3,
                    "passed": 2,
                    "failed": 1,
                    "strict_failed": 1,
                    "hardened_failed": 0,
                    "gate_pass": false,
                    "report_hash": "sha256:b"
                })
            ),
        )
        .expect("drift history");

        let source = FsFtuiDataSource::from_repo_root(dir.path());
        let dashboard = source
            .load_conformance_dashboard()
            .expect("load conformance dashboard");

        emit_test_log(
            "FP-P2C-002",
            "conformance_dashboard_aggregates_packet_and_trend_state",
            "mixed",
            2,
            "dashboard totals and trend aggregation",
            "pass",
        );
        assert_eq!(dashboard.total_packets, 2);
        assert_eq!(dashboard.green_packets, 1);
        assert_eq!(dashboard.failing_packets, 1);
        assert_eq!(dashboard.packet_trends.len(), 2);
        assert!(dashboard.render_plain().contains("Conformance packets=2"));
    }

    #[test]
    fn final_evidence_pack_reports_green_packet_and_render_summary() {
        let dir = tempdir().expect("tempdir");
        let packet_root = dir.path().join("artifacts/phase2c/FP-P2C-001");
        fs::create_dir_all(&packet_root).expect("packet root");
        write_packet_with_raptorq_artifacts(&packet_root, "FP-P2C-001", true);

        let source = FsFtuiDataSource::from_repo_root(dir.path());
        let evidence = source
            .load_final_evidence_pack()
            .expect("load final evidence pack");

        assert_eq!(evidence.total_packets, 1);
        assert_eq!(evidence.parity_gate_passed, 1);
        assert_eq!(evidence.parity_gate_failed, 0);
        assert_eq!(evidence.parity_gate_missing, 0);
        assert_eq!(evidence.sidecar_integrity_passed, 1);
        assert_eq!(evidence.sidecar_integrity_failed, 0);
        assert_eq!(evidence.decode_recovered, 1);
        assert_eq!(evidence.decode_failed_or_missing, 0);
        assert!(evidence.all_checks_passed);
        assert!(evidence.risk_notes.is_empty());
        assert_eq!(evidence.packets.len(), 1);
        assert!(evidence.packets[0].is_green());

        let rendered = evidence.render_plain();
        assert!(rendered.contains("FinalEvidence packets=1 all_checks_passed=true"));
        assert!(rendered.contains("- FP-P2C-001 gate=true"));
    }

    #[test]
    fn final_evidence_pack_flags_decode_proof_hash_mismatch_risk() {
        let dir = tempdir().expect("tempdir");
        let packet_root = dir.path().join("artifacts/phase2c/FP-P2C-001");
        fs::create_dir_all(&packet_root).expect("packet root");
        write_packet_with_raptorq_artifacts(&packet_root, "FP-P2C-001", true);
        tamper_decode_proof_hash(&packet_root);

        let source = FsFtuiDataSource::from_repo_root(dir.path());
        let evidence = source
            .load_final_evidence_pack()
            .expect("load final evidence pack");

        assert_eq!(evidence.total_packets, 1);
        assert!(!evidence.all_checks_passed);
        assert_eq!(evidence.sidecar_integrity_passed, 0);
        assert_eq!(evidence.sidecar_integrity_failed, 1);
        assert_eq!(evidence.decode_recovered, 1);
        assert_eq!(evidence.decode_failed_or_missing, 0);
        assert!(!evidence.risk_notes.is_empty());
        assert!(evidence.risk_notes.iter().any(|note| note.contains(
            "decode proof hash mismatch between sidecar envelope and decode proof artifact"
        )));
        assert!(!evidence.packets[0].is_green());
        assert!(!evidence.packets[0].sidecar_integrity_ok);
        assert!(
            evidence.packets[0]
                .risk_notes
                .iter()
                .any(|note| note.contains("decode proof hash mismatch")),
            "expected decode-proof pairing risk note"
        );
    }

    #[test]
    fn forensic_log_loader_skips_malformed_lines() {
        let dir = tempdir().expect("tempdir");
        let forensic_path = dir.path().join("forensic.jsonl");
        fs::write(
            &forensic_path,
            format!(
                "{}\nnot-json\n",
                json!({
                    "ts_unix_ms": 10,
                    "event": {
                        "kind": "suite_start",
                        "suite": "phase2c_packets",
                        "packet_filter": null
                    }
                })
            ),
        )
        .expect("write forensic log");

        let source = FsFtuiDataSource::from_repo_root(dir.path());
        let forensic = source
            .load_forensic_log(&forensic_path)
            .expect("load forensic log");

        assert!(!forensic.missing);
        assert_eq!(forensic.events.len(), 1);
        assert_eq!(forensic.malformed_lines, 1);
    }

    #[test]
    fn governance_gate_snapshot_reads_known_report() {
        let dir = tempdir().expect("tempdir");
        let root = dir.path().join("artifacts/phase2c");
        fs::create_dir_all(&root).expect("phase2c root");
        let ci = dir.path().join("artifacts/ci");
        fs::create_dir_all(&ci).expect("ci root");
        fs::write(
            ci.join("governance_gate_report.json"),
            json!({
                "generated_unix_ms": 123,
                "all_passed": false,
                "violation_count": 3
            })
            .to_string(),
        )
        .expect("governance report");

        let source = FsFtuiDataSource::from_repo_root(dir.path());
        let report = source
            .load_governance_gate_snapshot()
            .expect("load report")
            .expect("report present");
        assert!(!report.all_passed);
        assert_eq!(report.violation_count, 3);
        assert_eq!(report.generated_unix_ms, 123);
    }

    #[test]
    fn app_state_cycles_views_and_packet_selection() {
        let mut app = FtuiAppState::new(vec![
            "FP-P2C-002".to_owned(),
            "FP-P2C-001".to_owned(),
            "FP-P2C-003".to_owned(),
        ]);
        assert_eq!(app.selected_packet(), Some("FP-P2C-001"));
        app.select_next_packet();
        assert_eq!(app.selected_packet(), Some("FP-P2C-002"));
        app.cycle_next_view();
        app.cycle_next_view();
        app.cycle_next_view();
        app.cycle_next_view();
        assert_eq!(app.active_view, DashboardView::Conformance);
    }

    proptest! {
        #[test]
        fn prop_packet_id_accepts_three_digit_suffix(suffix in 0u16..1000u16) {
            let packet_id = format!("FP-P2C-{suffix:03}");
            emit_test_log(
                &packet_id,
                "prop_packet_id_accepts_three_digit_suffix",
                "n/a",
                u64::from(suffix),
                "is_valid_packet_id generated packet id",
                "pass",
            );
            prop_assert!(is_valid_packet_id(&packet_id));
        }

        #[test]
        fn prop_decision_summary_respects_cap_and_mode_counts(
            mode_plan in proptest::collection::vec(any::<bool>(), 1..32),
            cap in 0usize..8usize
        ) {
            let mut ledger = EvidenceLedger::new();
            let strict = RuntimePolicy::strict();
            let hardened = RuntimePolicy::hardened(Some(16));

            for (idx, strict_mode) in mode_plan.iter().copied().enumerate() {
                if strict_mode {
                    strict.decide_unknown_feature(
                        format!("feature_{idx}"),
                        "unsupported",
                        &mut ledger,
                    );
                } else {
                    hardened.decide_join_admission(idx + 1, &mut ledger);
                }
            }

            let summary = summarize_decision_dashboard(&ledger, &hardened, cap);
            let strict_expected = mode_plan.iter().filter(|&&is_strict| is_strict).count();
            let hardened_expected = mode_plan.len() - strict_expected;
            emit_test_log(
                "FRANKENTUI-E",
                "prop_decision_summary_respects_cap_and_mode_counts",
                "mixed",
                mode_plan.len() as u64,
                "summary totals and evidence cap invariants",
                "pass",
            );

            prop_assert_eq!(summary.total_records, mode_plan.len());
            prop_assert_eq!(summary.strict_records, strict_expected);
            prop_assert_eq!(summary.hardened_records, hardened_expected);
            prop_assert!(summary.cards.iter().all(|card| card.evidence_terms_shown <= cap));
            prop_assert!(
                summary
                    .cards
                    .iter()
                    .all(|card| card.evidence_terms_shown <= card.evidence_terms_total)
            );
        }
    }
}