omega-cognitive-kernel 0.16.0

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

#[allow(unused_imports)]
use crate::prelude::*;

use crate::api::Kernel;
use crate::error::Result;
use crate::l0::bandit_decision::BanditUcbDecisionMaker;
use crate::l0::decision::DecisionMaker;
use alloc::collections::BTreeMap;
use serde::{Serialize, Serializer};
use std::env::temp_dir;

fn serialize_score_breakdown<S>(
    values: &BTreeMap<String, f64>,
    serializer: S,
) -> core::result::Result<S::Ok, S::Error>
where
    S: Serializer,
{
    let mut entries: Vec<_> = values.iter().collect();
    entries.sort_unstable_by_key(|(key, _)| *key);
    serializer.collect_map(entries)
}

#[derive(Debug, Clone, Default, Serialize)]
/// Data structure representing L2 expert metrics.
pub struct L2ExpertMetrics {
    /// Committed for this value.
    pub committed: u64,
    /// Applied for this value.
    pub applied: u64,
    /// Not applied for this value.
    pub not_applied: u64,
    /// Reward sum for this value.
    pub reward_sum: f64,
}

#[derive(Debug, Clone, Default, Serialize)]
/// Data structure representing L2 pipeline diagnostics.
pub struct L2PipelineDiagnostics {
    /// Observations for this value.
    pub observations: u64,
    /// Spectral active for this value.
    pub spectral_active: u64,
    /// Proposals for this value.
    pub proposals: u64,
    /// Dry runs for this value.
    pub dry_runs: u64,
    /// Candidate arm changed relative to KEEP_L0 on the same pre-action snapshot.
    pub candidate_changes: u64,
    /// Selected arm changed relative to KEEP_L0 on that same snapshot.
    pub selected_changes: u64,
    /// Counterfactual changed candidate but L0 safety/hysteresis held the arm.
    pub candidate_changes_not_selected: u64,
    /// History discounts for this value.
    pub history_discounts: u64,
    /// Spectral rejections for this value.
    pub spectral_rejections: u64,
    /// Lyapunov rejections for this value.
    pub lyapunov_rejections: u64,
    /// Cooldown rejections for this value.
    pub cooldown_rejections: u64,
    /// Confidence rejections for this value.
    pub confidence_rejections: u64,
}

#[derive(Debug, Clone, PartialEq, Serialize)]
/// Data structure representing L2 diagnostic sample.
pub struct L2DiagnosticSample {
    /// Step for this value.
    pub step: u64,
    /// Selected arm for this value.
    pub selected_arm: usize,
    /// Optimal arm for this value.
    pub optimal_arm: usize,
    /// Reward for this value.
    pub reward: f64,
    /// Spectral bias for this value.
    pub spectral_bias: f64,
    /// Normalized energy for this value.
    pub normalized_energy: f64,
    /// Spectral dc drift for this value.
    pub spectral_dc_drift: f64,
    /// Convergence residual for this value.
    pub convergence_residual: f64,
    /// Controller residual for this value.
    pub controller_residual: f64,
    /// Alpha for this value.
    pub alpha: f64,
    /// Beta for this value.
    pub beta: f64,
    /// Confidence for this value.
    pub confidence: f64,
    /// Optional proposed expert.
    pub proposed_expert: Option<usize>,
    /// Whether applied is enabled or active.
    pub applied: bool,
    /// Optional dry run baseline arm.
    pub dry_run_baseline_arm: Option<usize>,
    /// Optional dry run treatment arm.
    pub dry_run_treatment_arm: Option<usize>,
    /// Optional dry run baseline candidate.
    pub dry_run_baseline_candidate: Option<usize>,
    /// Optional dry run treatment candidate.
    pub dry_run_treatment_candidate: Option<usize>,
    /// Optional rejection reason.
    pub rejection_reason: Option<String>,
}

#[derive(Debug, Clone, Copy, Default, Serialize)]
/// Data structure representing correlation diagnostic.
pub struct CorrelationDiagnostic {
    /// Samples for this value.
    pub samples: usize,
    /// Optional pearson.
    pub pearson: Option<f64>,
    /// Optional spearman.
    pub spearman: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    /// Optional spearman bootstrap ci95.
    pub spearman_bootstrap_ci95: Option<[f64; 2]>,
}

#[derive(Debug, Clone, Default, Serialize)]
/// Data structure representing L2 signal diagnostics.
pub struct L2SignalDiagnostics {
    /// Bias to next reward for this value.
    pub bias_to_next_reward: CorrelationDiagnostic,
    /// Residual to next error for this value.
    pub residual_to_next_error: CorrelationDiagnostic,
    /// Bias to regime change for this value.
    pub bias_to_regime_change: CorrelationDiagnostic,
    /// Bias to next optimal arm for this value.
    pub bias_to_next_optimal_arm: CorrelationDiagnostic,
}

#[derive(Debug, Clone, Default, Serialize)]
/// Data structure representing L2 experiment settings.
pub struct L2ExperimentSettings {
    /// Whether spectral control is enabled or active.
    pub spectral_control: bool,
    /// Whether purity prior is enabled or active.
    pub purity_prior: bool,
    /// Whether reverse brake is enabled or active.
    pub reverse_brake: bool,
    /// Whether history discount is enabled or active.
    pub history_discount: bool,
}

#[derive(Debug, Clone, Serialize)]
/// Report of bandit.
pub struct BanditReport {
    /// Scenario for this value.
    pub scenario: String,
    /// Episodes for this value.
    pub episodes: u32,
    /// Steps per episode for this value.
    pub steps_per_episode: u32,
    /// Mean reward for this value.
    pub mean_reward: f64,
    /// Mean external reward after UCB's error, rollback, and switching costs.
    /// This is a learning diagnostic, not a substitute for external reward.
    pub mean_adjusted_reward: f64,
    /// Best arm rate for this value.
    pub best_arm_rate: f64,
    /// Prediction-error damping factor at the end of the run.
    pub final_damping: f64,
    /// Final explore bonus for this value.
    pub final_explore_bonus: f64,
    /// Final risk tolerance for this value.
    pub final_risk_tolerance: f64,
    /// Whether average prediction error fell during the run.
    pub error_decreased: bool,
    /// Number of patches accepted during the run.
    pub patches_accepted: u64,
    /// Seed for this value.
    pub seed: u64,
    // Strategy-decay observability
    /// Number of stored strategies.
    pub strategy_count: usize,
    /// Number of idle strategy.
    pub idle_strategy_count: usize,
    /// Mean strategy weight for this value.
    pub mean_strategy_weight: f64,
    /// Number of mean idle.
    pub mean_idle_steps: f64,
    /// Maximum idle steps.
    pub max_idle_steps: u32,
    /// Mean idle weight for this value.
    pub mean_idle_weight: f64,
    /// Mean active weight for this value.
    pub mean_active_weight: f64,
    /// Initial average error for this value.
    pub initial_avg_error: f64,
    /// Final average error for this value.
    pub final_avg_error: f64,
    /// Fixed point enters for this value.
    pub fixed_point_enters: usize,
    /// Fixed point exits for this value.
    pub fixed_point_exits: usize,
    /// Maximum fixed point dwell.
    pub max_fixed_point_dwell: u64,
    /// L2 nudges for this value.
    pub l2_nudges: usize,
    /// L2 proposals for this value.
    pub l2_proposals: usize,
    /// L2 commits for this value.
    pub l2_commits: usize,
    /// Action switches for this value.
    pub action_switches: usize,
    /// Post commit action changes for this value.
    pub post_commit_action_changes: usize,
    /// Post commit arm changes for this value.
    pub post_commit_arm_changes: usize,
    /// Distinct actions for this value.
    pub distinct_actions: usize,
    /// Mean l2 consequence score for this value.
    pub mean_l2_consequence_score: f64,
    #[serde(serialize_with = "serialize_score_breakdown")]
    /// Mapping of final score breakdown.
    pub final_score_breakdown: BTreeMap<String, f64>,
    /// Final alignment score for this value.
    pub final_alignment_score: f64,
    /// Number of recovery.
    pub recovery_steps: Option<u32>,
    /// Number of L1 rollback.
    pub l1_rollback_count: u64,
    /// Number of L1 blocked by L2.
    pub l1_blocked_by_l2_count: u64,
    /// Number of L2 rollback.
    pub l2_rollback_count: u64,
    /// Whether dayan converged is enabled or active.
    pub dayan_converged: bool,
    /// Final dayan residual for this value.
    pub final_dayan_residual: f64,
    /// Number of dwell hold.
    pub dwell_hold_count: u64,
    /// Number of margin hold.
    pub margin_hold_count: u64,
    /// Number of active.
    pub active_steps: u64,
    /// Committed policies applied for this value.
    pub committed_policies_applied: u64,
    /// Expert metrics for this value.
    pub expert_metrics: [L2ExpertMetrics; 4],
    /// Lyapunov vetoes for this value.
    pub lyapunov_vetoes: u64,
    /// Meta cache hits for this value.
    pub meta_cache_hits: u64,
    /// Collection of recovery latencies.
    pub recovery_latencies: Vec<u32>,
    /// Collection of warm recovery latencies.
    pub warm_recovery_latencies: Vec<u32>,
    /// Mean residual improvement for this value.
    pub mean_residual_improvement: f64,
    #[serde(skip_serializing_if = "Option::is_none")]
    /// Optional pipeline.
    pub pipeline: Option<L2PipelineDiagnostics>,
    #[serde(skip_serializing_if = "Option::is_none")]
    /// Optional diagnostics.
    pub diagnostics: Option<Vec<L2DiagnosticSample>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    /// Optional signals.
    pub signals: Option<L2SignalDiagnostics>,
    #[serde(skip_serializing_if = "Option::is_none")]
    /// Optional experiment.
    pub experiment: Option<L2ExperimentSettings>,
}

#[derive(Debug, Clone, Serialize)]
/// Data structure representing L2 benchmark aggregate.
pub struct L2BenchmarkAggregate {
    /// Runs for this value.
    pub runs: u32,
    /// Mean reward for this value.
    pub mean_reward: f64,
    /// Mean adjusted reward for this value.
    pub mean_adjusted_reward: f64,
    /// Best arm rate for this value.
    pub best_arm_rate: f64,
    /// Error decrease rate for this value.
    pub error_decrease_rate: f64,
    /// Mean initial error for this value.
    pub mean_initial_error: f64,
    /// Mean final error for this value.
    pub mean_final_error: f64,
    /// Mean error delta for this value.
    pub mean_error_delta: f64,
    /// Mean patches accepted for this value.
    pub mean_patches_accepted: f64,
    /// Mean fixed point enters for this value.
    pub mean_fixed_point_enters: f64,
    /// Mean fixed point exits for this value.
    pub mean_fixed_point_exits: f64,
    /// Mean maximum fixed point dwell for this value.
    pub mean_max_fixed_point_dwell: f64,
    /// Mean l2 nudges for this value.
    pub mean_l2_nudges: f64,
    /// Mean l2 proposals for this value.
    pub mean_l2_proposals: f64,
    /// Mean l2 commits for this value.
    pub mean_l2_commits: f64,
    /// Mean action switches for this value.
    pub mean_action_switches: f64,
    /// Mean post commit action changes for this value.
    pub mean_post_commit_action_changes: f64,
    /// Mean post commit arm changes for this value.
    pub mean_post_commit_arm_changes: f64,
    /// Mean distinct actions for this value.
    pub mean_distinct_actions: f64,
    /// Mean l2 consequence score for this value.
    pub mean_l2_consequence_score: f64,
    #[serde(serialize_with = "serialize_score_breakdown")]
    /// Mapping of mean final score breakdown.
    pub mean_final_score_breakdown: BTreeMap<String, f64>,
    /// Mean final alignment score for this value.
    pub mean_final_alignment_score: f64,
    /// Number of mean recovery.
    pub mean_recovery_steps: Option<f64>,
    /// Recovery rate for this value.
    pub recovery_rate: f64,
    /// Number of mean L1 rollback.
    pub mean_l1_rollback_count: f64,
    /// Number of mean L1 blocked by L2.
    pub mean_l1_blocked_by_l2_count: f64,
    /// Number of mean L2 rollback.
    pub mean_l2_rollback_count: f64,
    /// Dayan convergence rate for this value.
    pub dayan_convergence_rate: f64,
    /// Mean final dayan residual for this value.
    pub mean_final_dayan_residual: f64,
    /// Number of mean dwell hold.
    pub mean_dwell_hold_count: f64,
    /// Number of mean margin hold.
    pub mean_margin_hold_count: f64,
    /// Number of mean active.
    pub mean_active_steps: f64,
    /// Mean committed policies applied for this value.
    pub mean_committed_policies_applied: f64,
    /// Mean expert committed for this value.
    pub mean_expert_committed: [f64; 4],
    /// Mean expert applied for this value.
    pub mean_expert_applied: [f64; 4],
    /// Mean expert not applied for this value.
    pub mean_expert_not_applied: [f64; 4],
    /// Optional mean expert reward.
    pub mean_expert_reward: [Option<f64>; 4],
    /// Mean lyapunov vetoes for this value.
    pub mean_lyapunov_vetoes: f64,
    /// Mean meta cache hits for this value.
    pub mean_meta_cache_hits: f64,
    /// Recovery event rate for this value.
    pub recovery_event_rate: f64,
    /// Number of mean warm recovery.
    pub mean_warm_recovery_steps: Option<f64>,
    /// Mean residual improvement for this value.
    pub mean_residual_improvement: f64,
}

#[derive(Debug, Clone, Default, PartialEq, Serialize)]
/// Data structure representing paired mean difference.
pub struct PairedMeanDifference {
    /// Mean for this value.
    pub mean: f64,
    /// Optional ci95 low.
    pub ci95_low: Option<f64>,
    /// Optional ci95 high.
    pub ci95_high: Option<f64>,
}

#[derive(Debug, Clone, Serialize)]
/// Data structure representing L2 paired run.
pub struct L2PairedRun {
    /// Seed for this value.
    pub seed: u64,
    /// Baseline for this value.
    pub baseline: BanditReport,
    /// Treatment for this value.
    pub treatment: BanditReport,
    /// Delta mean reward for this value.
    pub delta_mean_reward: f64,
    /// Delta best arm rate for this value.
    pub delta_best_arm_rate: f64,
    /// Delta error delta for this value.
    pub delta_error_delta: f64,
    /// Whether treatment influenced L0 is enabled or active.
    pub treatment_influenced_l0: bool,
}

#[derive(Debug, Clone, Serialize)]
/// Report of L2 benchmark.
pub struct L2BenchmarkReport {
    /// Scenario for this value.
    pub scenario: String,
    /// Episodes for this value.
    pub episodes: u32,
    /// Steps per episode for this value.
    pub steps_per_episode: u32,
    /// Runs for this value.
    pub runs: u32,
    /// Seed for this value.
    pub seed: u64,
    /// Baseline l2 disabled for this value.
    pub baseline_l2_disabled: L2BenchmarkAggregate,
    /// Whether treatment L2 enabled.
    pub treatment_l2_enabled: L2BenchmarkAggregate,
    /// Delta mean reward for this value.
    pub delta_mean_reward: f64,
    /// Delta best arm rate for this value.
    pub delta_best_arm_rate: f64,
    /// Delta error decrease rate for this value.
    pub delta_error_decrease_rate: f64,
    /// Paired reward difference for this value.
    pub paired_reward_difference: PairedMeanDifference,
    /// Paired best arm difference for this value.
    pub paired_best_arm_difference: PairedMeanDifference,
    /// Paired reward bootstrap for this value.
    pub paired_reward_bootstrap: PairedMeanDifference,
    /// Paired best arm bootstrap for this value.
    pub paired_best_arm_bootstrap: PairedMeanDifference,
    /// L0 influenced runs for this value.
    pub l0_influenced_runs: u32,
    /// Per-seed evidence for diagnosing differences that occur without a commit.
    pub paired_runs: Vec<L2PairedRun>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
/// Identifies a supported factorial arm.
pub enum FactorialArm {
    /// Variant representing L0.
    L0,
    /// Variant representing L1.
    L1,
    /// Variant representing L2.
    L2,
    /// Variant representing L1 L2.
    L1L2,
}

impl FactorialArm {
    /// Constant defining all.
    pub const ALL: [Self; 4] = [Self::L0, Self::L1, Self::L2, Self::L1L2];

    fn index(self) -> usize {
        match self {
            Self::L0 => 0,
            Self::L1 => 1,
            Self::L2 => 2,
            Self::L1L2 => 3,
        }
    }

    /// Performs label for this type.
    pub fn label(self) -> &'static str {
        match self {
            Self::L0 => "L0",
            Self::L1 => "L1",
            Self::L2 => "L2",
            Self::L1L2 => "L1+L2",
        }
    }

    fn l1_enabled(self) -> bool {
        matches!(self, Self::L1 | Self::L1L2)
    }

    fn l2_enabled(self) -> bool {
        matches!(self, Self::L2 | Self::L1L2)
    }
}

#[derive(Debug, Clone, Default, PartialEq, Serialize)]
/// Data structure representing factorial effect.
pub struct FactorialEffect {
    /// Reward for this value.
    pub reward: PairedMeanDifference,
    /// Reward bootstrap for this value.
    pub reward_bootstrap: PairedMeanDifference,
    /// Best arm rate for this value.
    pub best_arm_rate: PairedMeanDifference,
    /// Adjusted reward for this value.
    pub adjusted_reward: PairedMeanDifference,
}

#[derive(Debug, Clone, Serialize)]
/// Data structure representing factorial run.
pub struct FactorialRun {
    /// Seed for this value.
    pub seed: u64,
    /// Arms for this value.
    pub arms: [BanditReport; 4],
    /// L1 reward delta for this value.
    pub l1_reward_delta: f64,
    /// L2 reward delta for this value.
    pub l2_reward_delta: f64,
    /// Joint reward delta for this value.
    pub joint_reward_delta: f64,
    /// Interaction reward delta for this value.
    pub interaction_reward_delta: f64,
}

#[derive(Debug, Clone, Serialize)]
/// Report of factorial benchmark.
pub struct FactorialBenchmarkReport {
    /// Scenario for this value.
    pub scenario: String,
    /// Episodes for this value.
    pub episodes: u32,
    /// Steps per episode for this value.
    pub steps_per_episode: u32,
    /// Runs for this value.
    pub runs: u32,
    /// Seed for this value.
    pub seed: u64,
    /// Arm order for this value.
    pub arm_order: [FactorialArm; 4],
    /// Aggregates for this value.
    pub aggregates: [L2BenchmarkAggregate; 4],
    /// L1 effect for this value.
    pub l1_effect: FactorialEffect,
    /// L2 effect for this value.
    pub l2_effect: FactorialEffect,
    /// Joint effect for this value.
    pub joint_effect: FactorialEffect,
    /// Interaction effect for this value.
    pub interaction_effect: FactorialEffect,
    /// Collection of paired runs.
    pub paired_runs: Vec<FactorialRun>,
}

/// Constant defining L2 gain scenarios.
pub const L2_GAIN_SCENARIOS: [&str; 4] =
    ["stable", "nonstationary", "regime_shift", "cyclic_shift"];
/// Constant defining L2 gain discovery seed.
pub const L2_GAIN_DISCOVERY_SEED: u64 = 20261115;
/// Constant defining L2 gain validation seed.
pub const L2_GAIN_VALIDATION_SEED: u64 = 20270001;
/// Constant defining L2 gain default runs.
pub const L2_GAIN_DEFAULT_RUNS: u32 = 30;
/// Constant defining L2 gain default episodes.
pub const L2_GAIN_DEFAULT_EPISODES: u32 = 12;
/// Constant defining L2 gain default steps.
pub const L2_GAIN_DEFAULT_STEPS: u32 = 12;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
/// Identifies a supported L2 gain seed set.
pub enum L2GainSeedSet {
    /// Variant representing discovery.
    Discovery,
    /// Variant representing validation.
    Validation,
}

#[derive(Debug, Clone, Serialize)]
/// Data structure representing L2 gain scenario assessment.
pub struct L2GainScenarioAssessment {
    /// Whether reward ci95 lower positive is enabled or active.
    pub reward_ci95_lower_positive: bool,
    /// Whether stable loss within tolerance is enabled or active.
    pub stable_loss_within_tolerance: bool,
    /// Executed interventions for this value.
    pub executed_interventions: u64,
}

#[derive(Debug, Clone, Serialize)]
/// Data structure representing L2 gain assessment.
pub struct L2GainAssessment {
    /// Primary scenario for this value.
    pub primary_scenario: String,
    /// Safety scenario for this value.
    pub safety_scenario: String,
    /// Stable loss tolerance for this value.
    pub stable_loss_tolerance: f64,
    /// Whether mechanism precondition met is enabled or active.
    pub mechanism_precondition_met: bool,
    /// Whether discovery primary passed is enabled or active.
    pub discovery_primary_passed: bool,
    /// Whether validation reproduced is enabled or active.
    pub validation_reproduced: bool,
    /// Whether discovery safety passed is enabled or active.
    pub discovery_safety_passed: bool,
    /// Whether validation safety passed is enabled or active.
    pub validation_safety_passed: bool,
    /// Whether reproducible gain is enabled or active.
    pub reproducible_gain: bool,
    /// Conclusion for this value.
    pub conclusion: String,
    /// Discovery for this value.
    pub discovery: L2GainScenarioAssessment,
    /// Validation for this value.
    pub validation: L2GainScenarioAssessment,
}

#[derive(Debug, Clone, Serialize)]
/// Report of L2 gain matrix.
pub struct L2GainMatrixReport {
    /// Version of the serialized kernel-state schema.
    pub schema_version: u32,
    /// Design for this value.
    pub design: String,
    /// Runs per scenario for this value.
    pub runs_per_scenario: u32,
    /// Episodes for this value.
    pub episodes: u32,
    /// Steps per episode for this value.
    pub steps_per_episode: u32,
    /// Scenarios for this value.
    pub scenarios: [&'static str; 4],
    /// Discovery seed for this value.
    pub discovery_seed: u64,
    /// Validation seed for this value.
    pub validation_seed: u64,
    /// Kernel runs for this value.
    pub kernel_runs: u64,
    /// Number of decision.
    pub decision_steps: u64,
    /// Collection of reports.
    pub reports: Vec<FactorialBenchmarkReport>,
    /// Assessment for this value.
    pub assessment: L2GainAssessment,
}

fn assess_gain_scenario(report: &FactorialBenchmarkReport) -> L2GainScenarioAssessment {
    let executed_interventions = report
        .paired_runs
        .iter()
        .map(|run| run.arms[FactorialArm::L2.index()].committed_policies_applied)
        .sum();
    L2GainScenarioAssessment {
        reward_ci95_lower_positive: report
            .l2_effect
            .reward
            .ci95_low
            .is_some_and(|low| low > 0.0),
        stable_loss_within_tolerance: report
            .l2_effect
            .reward
            .ci95_low
            .is_some_and(|low| low >= -0.01),
        executed_interventions,
    }
}

fn gain_conclusion(assessment: &L2GainAssessment) -> String {
    if assessment.reproducible_gain {
        "L2-only reward gain reproduced within this fixture and seed matrix".into()
    } else if !assessment.mechanism_precondition_met {
        "No executed L2 intervention; reward differences cannot demonstrate an L2 gain".into()
    } else if assessment.discovery_primary_passed && !assessment.validation_reproduced {
        "Discovery gain did not reproduce on the independent validation seeds".into()
    } else {
        "The preregistered reward criterion did not demonstrate a reproducible L2 gain".into()
    }
}

fn assess_l2_gain_matrix(reports: &[FactorialBenchmarkReport]) -> Result<L2GainAssessment> {
    if reports.len() != L2_GAIN_SCENARIOS.len() * 2 {
        return Err(crate::error::OmegaError::Memory(format!(
            "gain assessment requires {} reports, got {}",
            L2_GAIN_SCENARIOS.len() * 2,
            reports.len()
        )));
    }
    for seed_set in [L2GainSeedSet::Discovery, L2GainSeedSet::Validation] {
        for scenario in L2_GAIN_SCENARIOS {
            let expected_seed = match seed_set {
                L2GainSeedSet::Discovery => L2_GAIN_DISCOVERY_SEED,
                L2GainSeedSet::Validation => L2_GAIN_VALIDATION_SEED,
            };
            let matching: Vec<_> = reports
                .iter()
                .filter(|report| report.scenario == scenario && report.seed == expected_seed)
                .collect();
            if matching.len() != 1 {
                return Err(crate::error::OmegaError::Memory(format!(
                    "gain assessment requires one {seed_set:?} report for {scenario}"
                )));
            }
            let report = matching[0];
            if report.runs < 2 || report.paired_runs.len() != report.runs as usize {
                return Err(crate::error::OmegaError::Memory(
                    "gain report has incomplete paired seeds".into(),
                ));
            }
            for (index, pair) in report.paired_runs.iter().enumerate() {
                if pair.seed != expected_seed.wrapping_add(index as u64) {
                    return Err(crate::error::OmegaError::Memory(
                        "gain report has missing, duplicate, or reordered seeds".into(),
                    ));
                }
            }
        }
    }
    let find = |seed_set: L2GainSeedSet, scenario: &str| {
        let expected_seed = match seed_set {
            L2GainSeedSet::Discovery => L2_GAIN_DISCOVERY_SEED,
            L2GainSeedSet::Validation => L2_GAIN_VALIDATION_SEED,
        };
        reports
            .iter()
            .find(|report| report.scenario == scenario && report.seed == expected_seed)
            .ok_or_else(|| {
                crate::error::OmegaError::Memory(format!(
                    "missing {seed_set:?} gain report for {scenario}"
                ))
            })
    };
    let discovery = find(L2GainSeedSet::Discovery, "regime_shift")?;
    let validation = find(L2GainSeedSet::Validation, "regime_shift")?;
    let discovery_stable = find(L2GainSeedSet::Discovery, "stable")?;
    let validation_stable = find(L2GainSeedSet::Validation, "stable")?;
    let discovery = assess_gain_scenario(discovery);
    let validation = assess_gain_scenario(validation);
    let discovery_stable = assess_gain_scenario(discovery_stable);
    let validation_stable = assess_gain_scenario(validation_stable);
    let mechanism_precondition_met =
        discovery.executed_interventions > 0 && validation.executed_interventions > 0;
    let mut assessment = L2GainAssessment {
        primary_scenario: "regime_shift".into(),
        safety_scenario: "stable".into(),
        stable_loss_tolerance: 0.01,
        mechanism_precondition_met,
        discovery_primary_passed: discovery.reward_ci95_lower_positive,
        validation_reproduced: validation.reward_ci95_lower_positive,
        discovery_safety_passed: discovery_stable.stable_loss_within_tolerance,
        validation_safety_passed: validation_stable.stable_loss_within_tolerance,
        reproducible_gain: false,
        conclusion: String::new(),
        discovery,
        validation,
    };
    assessment.reproducible_gain = assessment.mechanism_precondition_met
        && assessment.discovery_primary_passed
        && assessment.validation_reproduced
        && assessment.discovery_safety_passed
        && assessment.validation_safety_passed;
    assessment.conclusion = gain_conclusion(&assessment);
    Ok(assessment)
}

fn factorial_differences<F>(runs: &[FactorialRun], value: F) -> [Vec<f64>; 4]
where
    F: Fn(&BanditReport) -> f64,
{
    let mut differences = core::array::from_fn(|_| Vec::with_capacity(runs.len()));
    for run in runs {
        let values = [
            value(&run.arms[0]),
            value(&run.arms[1]),
            value(&run.arms[2]),
            value(&run.arms[3]),
        ];
        differences[0].push(values[1] - values[0]);
        differences[1].push(values[2] - values[0]);
        differences[2].push(values[3] - values[0]);
        differences[3].push(values[3] - values[2] - values[1] + values[0]);
    }
    differences
}

fn factorial_effects(runs: &[FactorialRun], seed: u64) -> [FactorialEffect; 4] {
    let reward = factorial_differences(runs, |report| report.mean_reward);
    let best_arm = factorial_differences(runs, |report| report.best_arm_rate);
    let adjusted = factorial_differences(runs, |report| report.mean_adjusted_reward);
    core::array::from_fn(|effect| FactorialEffect {
        reward: paired_difference(&reward[effect]),
        reward_bootstrap: bootstrap_difference(
            &reward[effect],
            seed ^ 0x4c314c32 ^ (effect as u64),
        ),
        best_arm_rate: paired_difference(&best_arm[effect]),
        adjusted_reward: paired_difference(&adjusted[effect]),
    })
}

struct Rng {
    state: u64,
}

impl Rng {
    fn new(seed: u64) -> Self {
        Self { state: seed | 1 }
    }

    fn next_f64(&mut self) -> f64 {
        self.state = self.state.wrapping_mul(1664525).wrapping_add(1013904223);
        (self.state >> 8) as f64 / (1u64 << 56) as f64
    }
}

fn arm_for_action(action: &str) -> usize {
    match action {
        "stabilize" | "exploit" => 0,
        "explore" => 1,
        _ => 0,
    }
}

/// Runs run bandit task and returns its result.
pub fn run_bandit_task(
    kernel: &mut Kernel,
    episodes: u32,
    steps_per_episode: u32,
) -> Result<BanditReport> {
    run_bandit_task_seeded(kernel, episodes, steps_per_episode, 405123076)
}

/// Runs run bandit task seeded and returns its result.
pub fn run_bandit_task_seeded(
    kernel: &mut Kernel,
    episodes: u32,
    steps_per_episode: u32,
    seed: u64,
) -> Result<BanditReport> {
    run_bandit_task_seeded_scenario(
        kernel,
        episodes,
        steps_per_episode,
        seed,
        "nonstationary",
        None,
    )
}

fn run_bandit_task_seeded_scenario<D>(
    kernel: &mut Kernel<
        crate::l0::observer::MultiModalObserver,
        D,
        crate::l0::executor::SandboxedExecutor,
    >,
    episodes: u32,
    steps_per_episode: u32,
    seed: u64,
    scenario: &str,
    experiment: Option<L2ExperimentSettings>,
) -> Result<BanditReport>
where
    D: DecisionMaker,
{
    let mut rng = Rng::new(seed);
    let mut total_reward = 0.0;
    let mut total_adjusted_reward = 0.0;
    let mut best_hits = 0u32;
    let mut total_choices = 0u32;
    let mut patches = 0u64;
    let mut l2_nudges = 0usize;
    let mut l2_proposals = 0usize;
    let mut l2_commits = 0usize;
    let mut action_switches = 0usize;
    let mut post_commit_action_changes = 0usize;
    let mut post_commit_arm_changes = 0usize;
    let mut distinct_actions = std::collections::HashSet::new();
    let mut previous_action: Option<String> = None;
    let mut pending_proposal: Option<(usize, String, usize)> = None;
    let mut max_fixed_point_dwell = 0u64;
    let mut consequence_sum = 0.0;
    let mut early_err = None;
    let mut final_score_breakdown = BTreeMap::new();
    let mut recovery_steps = None;
    let mut recovery_streak = 0;
    let mut l1_rollback_count = 0;
    let mut l1_blocked_by_l2_count = 0;
    let mut l2_rollback_count = 0;
    let mut final_dayan_residual = 1.0;
    let mut dwell_hold_count = 0;
    let mut margin_hold_count = 0;
    let mut active_steps = 0;
    let mut committed_policies_applied = 0;
    let mut expert_metrics: [L2ExpertMetrics; 4] =
        core::array::from_fn(|_| L2ExpertMetrics::default());
    let mut lyapunov_vetoes = 0;
    let mut meta_cache_hits = 0;
    let mut recovery_latencies = Vec::new();
    let mut warm_recovery_latencies = Vec::new();
    let mut recovery_started_at = None;
    let mut recovery_warm = false;
    let mut recovery_used_commit = false;
    let mut last_warm_commit: Option<crate::types::L2Policy> = None;
    let mut pipeline = L2PipelineDiagnostics::default();
    let mut diagnostic_samples = Vec::new();
    let collect_diagnostics = experiment.is_some();
    let mut residual_improvement = 0.0;
    let mut initial_dayan_residual = None;
    let mut previous_dayan_residual = None;
    let mut dayan_decreased_steps = 0u64;
    let total_steps = episodes.saturating_mul(steps_per_episode);
    let shift_step = total_steps / 2;
    let recovery_target = total_steps.saturating_sub(shift_step) / 3;

    for ep in 0..episodes {
        // Non-stationary: best arm flips halfway (and once more late if many episodes).
        let best = match scenario {
            "stable" | "fixedpoint" => 0,
            "degraded" if ep >= episodes / 2 => 0,
            _ if ep >= episodes / 2 && !(episodes >= 4 && ep >= (episodes * 3) / 4) => 1,
            _ => 0,
        };
        if scenario == "degraded" && ep == episodes / 2 {
            kernel.inner_mut().l0.memory.cas.avg_prediction_error = 0.9;
        }
        if scenario == "fixedpoint" {
            kernel.inner_mut().l0.memory.cas.avg_prediction_error =
                if ep < episodes / 2 { 0.2 } else { 0.9 };
        }
        let mut ep_reward = 0.0;

        for step_in_episode in 0..steps_per_episode {
            let global_step = ep * steps_per_episode + step_in_episode;
            let best = if scenario == "cyclic_shift" {
                (global_step / 12) as usize % 2
            } else if matches!(scenario, "regime_shift" | "nonstationary")
                && global_step >= shift_step
            {
                if scenario == "nonstationary" && global_step >= (total_steps * 3) / 4 {
                    0
                } else {
                    1
                }
            } else {
                best
            };
            let mut before_err = kernel.inner().l0.memory.cas.avg_prediction_error;
            if matches!(scenario, "regime_shift" | "cyclic_shift")
                && ((scenario == "regime_shift" && global_step >= shift_step)
                    || (scenario == "cyclic_shift" && global_step % 12 < 3))
            {
                // Inject observation noise before learning and preserve the
                // same pre-step error for the consequence calculation.
                kernel.inner_mut().l0.memory.cas.avg_prediction_error =
                    if global_step == shift_step { 0.9 } else { 0.65 };
                before_err = kernel.inner().l0.memory.cas.avg_prediction_error;
            }
            // Capture the state before L0 consumes the one-shot policy. Both
            // dry-runs must use this exact snapshot: a post-action snapshot has
            // already changed the incumbent/dwell state and cannot attribute
            // this action to L2.
            let dry_run = if collect_diagnostics {
                let applied = kernel.inner().l2.pending_policy.effective();
                kernel
                    .inner()
                    .l0
                    .decision
                    .bandit_snapshot()
                    .map(|mut snapshot| {
                        // The snapshot's policy was consumed by the previous action.
                        // run_once replaces it with pending_policy before deciding.
                        snapshot.l2_policy = crate::types::L2Policy::default();
                        let mut baseline = BanditUcbDecisionMaker::default();
                        baseline.restore(snapshot.clone());
                        let (baseline, _) =
                            baseline.dry_run_policy(crate::types::L2Policy::default());
                        let mut treatment = BanditUcbDecisionMaker::default();
                        treatment.restore(snapshot);
                        let (treatment, _) = treatment.dry_run_policy(applied);
                        (baseline, treatment)
                    })
            } else {
                None
            };
            let r = kernel
                .step("maintain coherent self-model omega dayan while maximizing bandit reward")?;
            let after_err = kernel.inner().l0.memory.cas.avg_prediction_error;
            if early_err.is_none() {
                early_err = Some(after_err);
            }
            if r.l1.patched {
                patches += 1;
            }
            let l1_rolled_back = kernel.observe_l1_consequence(after_err - before_err);
            let l1_rollback = l1_rolled_back || r.l1.rollback_effect.is_some();
            let applied = r.l2.applied_policy;
            if let Some(logged_policy) = r
                .trajectory
                .actions
                .first()
                .and_then(|action| action.params.get("l2_policy"))
                .and_then(|value| {
                    serde_json::from_value::<crate::types::L2Policy>(value.clone()).ok()
                })
            {
                debug_assert_eq!(applied, logged_policy);
            }
            let kl_policy = r
                .trajectory
                .actions
                .first()
                .and_then(|action| {
                    serde_json::from_value::<[f64; 2]>(action.params.get("kl_policy")?.clone()).ok()
                })
                .unwrap_or([1.0, 0.0]);
            if r.l2.effect_nudge.is_some() {
                l2_nudges += 1;
            }
            if r.l2.modulation_proposed {
                l2_proposals += 1;
            }
            if r.l2.modulation_committed {
                l2_commits += 1;
            }
            if collect_diagnostics {
                pipeline.observations += 1;
                pipeline.spectral_active += u64::from(
                    r.l2.spectral_output
                        .is_some_and(|output| output.state == crate::l2::L2State::Active),
                );
                pipeline.history_discounts += u64::from(
                    r.l2.spectral_output
                        .is_some_and(|output| output.regime_detected),
                );
                match r.l2.rejection_reason.as_deref() {
                    Some("spectral_gate") => pipeline.spectral_rejections += 1,
                    Some("lyapunov_veto") => pipeline.lyapunov_rejections += 1,
                    Some("commit_cooldown") => pipeline.cooldown_rejections += 1,
                    Some("commit_threshold") | Some("trust_or_confidence_zero") => {
                        pipeline.confidence_rejections += 1
                    }
                    _ => {}
                }
            }
            max_fixed_point_dwell = max_fixed_point_dwell.max(r.l2.dwell_steps);
            final_dayan_residual = r.l2.dayan_residual;
            residual_improvement += previous_dayan_residual
                .map(|previous| previous - r.l2.dayan_residual)
                .unwrap_or(0.0);
            dayan_decreased_steps += u64::from(
                previous_dayan_residual
                    .map(|previous| r.l2.dayan_residual < previous)
                    .unwrap_or(false),
            );
            initial_dayan_residual.get_or_insert(r.l2.dayan_residual);
            previous_dayan_residual = Some(r.l2.dayan_residual);
            let l2_policy_applied =
                r.l2.decision
                    .as_ref()
                    .map(|decision| decision.l2_policy_applied)
                    .unwrap_or(applied.committed);
            if collect_diagnostics {
                pipeline.dry_runs += 1;
                if let Some((baseline, treatment)) = &dry_run {
                    let candidate_changed = baseline.candidate_arm != treatment.candidate_arm;
                    let selected_changed = baseline.selected_arm != treatment.selected_arm;
                    pipeline.candidate_changes += u64::from(candidate_changed);
                    pipeline.selected_changes += u64::from(selected_changed);
                    pipeline.candidate_changes_not_selected +=
                        u64::from(candidate_changed && !selected_changed);
                }
                pipeline.proposals += u64::from(r.l2.modulation_committed);
                let spec = r.l2.spectral_output;
                diagnostic_samples.push(L2DiagnosticSample {
                    step: kernel.inner().total_steps,
                    selected_arm: r.l2.decision.as_ref().map(|d| d.selected_arm).unwrap_or(0),
                    optimal_arm: best,
                    reward: 0.0,
                    spectral_bias: spec.map(|s| s.bias).unwrap_or(0.0),
                    normalized_energy: spec.map(|s| s.normalized_energy).unwrap_or(0.0),
                    spectral_dc_drift: spec.map(|s| s.dc_drift).unwrap_or(0.0),
                    convergence_residual: spec.map(|s| s.convergence_residual).unwrap_or(0.0),
                    controller_residual: r.l2.dayan_residual,
                    alpha: r.l2.alpha,
                    beta: r.l2.beta,
                    confidence: kernel.inner().l2.controller.model_confidence,
                    proposed_expert: r.l2.modulation_committed.then_some(r.l2.l2_policy.expert),
                    applied: l2_policy_applied,
                    dry_run_baseline_arm: dry_run
                        .as_ref()
                        .map(|(baseline, _)| baseline.selected_arm),
                    dry_run_treatment_arm: dry_run
                        .as_ref()
                        .map(|(_, treatment)| treatment.selected_arm),
                    dry_run_baseline_candidate: dry_run
                        .as_ref()
                        .map(|(baseline, _)| baseline.candidate_arm),
                    dry_run_treatment_candidate: dry_run
                        .as_ref()
                        .map(|(_, treatment)| treatment.candidate_arm),
                    rejection_reason: r.l2.rejection_reason.clone(),
                });
            }
            active_steps += u64::from(r.l2.gate_state == crate::l2::control::L2GateState::Active);
            committed_policies_applied += u64::from(l2_policy_applied);
            lyapunov_vetoes += u64::from(r.l2.lyapunov_veto);
            meta_cache_hits += u64::from(r.l2.meta_cache_hit);
            if let Some(decision) = &r.l2.decision {
                dwell_hold_count += u64::from(decision.dwell_suppressed);
                margin_hold_count += u64::from(decision.margin_suppressed);
            }
            if !r.l2.score_breakdown.is_empty() {
                final_score_breakdown = r.l2.score_breakdown.clone();
            }
            let action = r
                .trajectory
                .actions
                .first()
                .map(|a| a.name.clone())
                .unwrap_or_else(|| "observe".into());
            let arm = arm_for_action(&action);
            distinct_actions.insert(action.clone());
            if previous_action
                .as_deref()
                .map(|prev| prev != action)
                .unwrap_or(false)
            {
                action_switches += 1;
            }
            if let Some((commit_step, before_action, before_arm)) = pending_proposal.take() {
                debug_assert_eq!(commit_step + 1, kernel.inner().total_steps as usize);
                if l2_policy_applied {
                    if action != before_action {
                        post_commit_action_changes += 1;
                    }
                    if arm != before_arm {
                        post_commit_arm_changes += 1;
                    }
                }
            }
            if r.l2.modulation_committed {
                pending_proposal = Some((kernel.inner().total_steps as usize, action.clone(), arm));
            }
            previous_action = Some(action.clone());
            let p = if scenario == "degraded" && ep >= episodes / 2 {
                if arm == best {
                    0.45
                } else {
                    0.35
                }
            } else if arm == best {
                0.85
            } else {
                0.25
            };
            let reward = if rng.next_f64() < p { 1.0 } else { 0.0 };
            if let Some(sample) = diagnostic_samples.last_mut() {
                sample.reward = reward;
            }
            if let Some(proposed) = r
                .trajectory
                .actions
                .first()
                .and_then(|action| action.params.get("l2_proposed_policy"))
                .and_then(|value| {
                    serde_json::from_value::<crate::types::L2Policy>(value.clone()).ok()
                })
                .filter(|policy| policy.committed && policy.expert < 4)
            {
                let metrics = &mut expert_metrics[proposed.expert];
                metrics.committed += 1;
                if l2_policy_applied {
                    metrics.applied += 1;
                    metrics.reward_sum += reward;
                } else {
                    metrics.not_applied += 1;
                }
            }

            let rollback_count = u64::from(l1_rollback) + u64::from(r.l1.safety_degraded);
            let switch_cost =
                r.l2.decision
                    .as_ref()
                    .filter(|decision| decision.switched && decision.selected_arm == arm)
                    .map(|decision| decision.switch_cost_applied)
                    .unwrap_or(0.0);
            let rollback_penalty = kernel
                .inner()
                .l0
                .decision
                .bandit_config()
                .map(|config| config.rollback_penalty)
                .unwrap_or(0.0);
            let adjusted_reward = reward
                - 0.25 * (after_err - before_err)
                - rollback_penalty * rollback_count as f64
                - switch_cost;
            total_adjusted_reward += adjusted_reward;
            kernel.inner_mut().l0.memory.record_reward(&action, reward);
            // External reward is separated from error improvement and explicit
            // L1 safety costs so a rollback cannot disappear behind a good error.
            kernel.inner_mut().l0.decision.observe_with_feedback(
                arm,
                reward,
                crate::types::DecisionFeedback {
                    l1_rollback,
                    safety_degradation: r.l1.safety_degraded,
                    error_delta: after_err - before_err,
                },
            );
            debug_assert!(
                kernel.inner().l0.decision.bandit_config().is_none()
                    || kernel
                        .inner()
                        .l0
                        .decision
                        .l2_decision()
                        .and_then(|decision| decision.adjusted_reward)
                        == Some(adjusted_reward),
                "reported net reward must equal the UCB learning feedback"
            );
            kernel.observe_l2_feedback(
                reward,
                after_err,
                l1_rollback,
                kernel.inner().l2.last_consequence_score,
                kl_policy,
            );
            let consequence_score = 0.60 * (reward - 0.5) - 0.25 * (after_err - before_err);
            consequence_sum += consequence_score;
            kernel.observe_l2_consequence(reward - 0.5, after_err - before_err, 0.0);
            if kernel.inner().l2.last_consequence_score < -0.05
                && kernel.inner().l2.rollback_effect.is_some()
            {
                l2_rollback_count += 1;
            }
            l1_blocked_by_l2_count += u64::from(r.l1_blocked_by_l2);
            l1_rollback_count += u64::from(l1_rollback);
            if r.l2.modulation_committed {
                last_warm_commit = kernel
                    .inner()
                    .l2
                    .controller
                    .meta_cache_hit
                    .then_some(r.l2.l2_policy);
            }
            recovery_used_commit |= last_warm_commit == Some(applied) && applied.committed;
            if matches!(scenario, "regime_shift" | "cyclic_shift") {
                let transition = (scenario == "regime_shift" && global_step == shift_step)
                    || (scenario == "cyclic_shift"
                        && global_step > 0
                        && global_step.is_multiple_of(12));
                if transition {
                    recovery_started_at = Some(global_step);
                    recovery_streak = 0;
                    recovery_warm = false;
                    recovery_used_commit = false;
                    last_warm_commit = None;
                }
                let target = if scenario == "regime_shift" {
                    recovery_target
                } else {
                    3
                };
                if let Some(start) = recovery_started_at {
                    recovery_warm |= kernel.inner().l2.controller.meta_cache_hit;
                    recovery_streak = if arm == best { recovery_streak + 1 } else { 0 };
                    if recovery_streak >= target.max(1) {
                        let latency = global_step - start + 1;
                        recovery_latencies.push(latency);
                        if recovery_warm && recovery_used_commit {
                            warm_recovery_latencies.push(latency);
                        }
                        recovery_steps.get_or_insert(latency);
                        recovery_started_at = None;
                    }
                }
            }

            ep_reward += reward;
            total_reward += reward;
            total_choices += 1;
            if arm == best {
                best_hits += 1;
            }
        }

        kernel.audit_task("bandit2", ep_reward, steps_per_episode)?;
    }

    let final_err = kernel.inner().l0.memory.cas.avg_prediction_error;
    let initial_err = early_err.unwrap_or(final_err);
    let effect = &kernel.inner().l0.memory.cognitive_effect;
    let idle_threshold = kernel.inner().l0.learner.decay_idle_threshold;
    let st = kernel.inner().l0.memory.strategy.stats(idle_threshold);
    let audit = kernel.audit_summary()?;
    let status = kernel.status();

    let signals = collect_diagnostics.then(|| signal_diagnostics(&diagnostic_samples));
    Ok(BanditReport {
        scenario: scenario.into(),
        episodes,
        steps_per_episode,
        mean_reward: if total_choices == 0 {
            0.0
        } else {
            total_reward / total_choices as f64
        },
        mean_adjusted_reward: total_adjusted_reward / total_choices.max(1) as f64,
        best_arm_rate: if total_choices == 0 {
            0.0
        } else {
            best_hits as f64 / total_choices as f64
        },
        final_damping: effect.error_damping,
        final_explore_bonus: effect.explore_bonus,
        final_risk_tolerance: effect.risk_tolerance,
        error_decreased: final_err < initial_err,
        patches_accepted: patches,
        seed,
        strategy_count: st.strategy_count,
        idle_strategy_count: st.idle_count,
        mean_strategy_weight: st.mean_weight,
        mean_idle_steps: st.mean_idle_steps,
        max_idle_steps: st.max_idle_steps,
        mean_idle_weight: st.mean_idle_weight,
        mean_active_weight: st.mean_active_weight,
        initial_avg_error: initial_err,
        final_avg_error: final_err,
        fixed_point_enters: audit.fixed_point_enters,
        fixed_point_exits: audit.fixed_point_exits,
        max_fixed_point_dwell,
        l2_nudges,
        l2_proposals,
        l2_commits,
        action_switches,
        post_commit_action_changes,
        post_commit_arm_changes,
        distinct_actions: distinct_actions.len(),
        mean_l2_consequence_score: if total_choices == 0 {
            0.0
        } else {
            consequence_sum / total_choices as f64
        },
        final_score_breakdown,
        final_alignment_score: status.last_alignment_score,
        recovery_steps,
        l1_rollback_count,
        l1_blocked_by_l2_count,
        l2_rollback_count,
        dayan_converged: final_dayan_residual <= 0.18
            && dayan_decreased_steps > 0
            && initial_dayan_residual
                .map(|initial| final_dayan_residual <= initial)
                .unwrap_or(false),
        final_dayan_residual,
        dwell_hold_count,
        margin_hold_count,
        active_steps,
        committed_policies_applied,
        expert_metrics,
        lyapunov_vetoes,
        meta_cache_hits,
        recovery_latencies,
        warm_recovery_latencies,
        mean_residual_improvement: residual_improvement / total_choices.max(1) as f64,
        experiment,
        pipeline: collect_diagnostics.then_some(pipeline),
        diagnostics: collect_diagnostics.then_some(diagnostic_samples),
        signals,
    })
}

fn aggregate(reports: &[BanditReport]) -> L2BenchmarkAggregate {
    let shift_events = reports
        .first()
        .map(|r| match r.scenario.as_str() {
            "regime_shift" => 1,
            "cyclic_shift" => {
                r.episodes
                    .saturating_mul(r.steps_per_episode)
                    .saturating_sub(1)
                    / 12
            }
            _ => 0,
        })
        .unwrap_or(0);
    let runs = reports.len() as u32;
    if reports.is_empty() {
        return L2BenchmarkAggregate {
            runs,
            mean_reward: 0.0,
            mean_adjusted_reward: 0.0,
            best_arm_rate: 0.0,
            error_decrease_rate: 0.0,
            mean_initial_error: 0.0,
            mean_final_error: 0.0,
            mean_error_delta: 0.0,
            mean_patches_accepted: 0.0,
            mean_fixed_point_enters: 0.0,
            mean_fixed_point_exits: 0.0,
            mean_max_fixed_point_dwell: 0.0,
            mean_l2_nudges: 0.0,
            mean_l2_proposals: 0.0,
            mean_l2_commits: 0.0,
            mean_action_switches: 0.0,
            mean_post_commit_action_changes: 0.0,
            mean_post_commit_arm_changes: 0.0,
            mean_distinct_actions: 0.0,
            mean_l2_consequence_score: 0.0,
            mean_final_score_breakdown: BTreeMap::new(),
            mean_final_alignment_score: 0.0,
            mean_recovery_steps: None,
            recovery_rate: 0.0,
            mean_l1_rollback_count: 0.0,
            mean_l1_blocked_by_l2_count: 0.0,
            mean_l2_rollback_count: 0.0,
            dayan_convergence_rate: 0.0,
            mean_final_dayan_residual: 0.0,
            mean_dwell_hold_count: 0.0,
            mean_margin_hold_count: 0.0,
            mean_active_steps: 0.0,
            mean_committed_policies_applied: 0.0,
            mean_expert_committed: [0.0; 4],
            mean_expert_applied: [0.0; 4],
            mean_expert_not_applied: [0.0; 4],
            mean_expert_reward: [None; 4],
            mean_lyapunov_vetoes: 0.0,
            mean_meta_cache_hits: 0.0,
            recovery_event_rate: 0.0,
            mean_warm_recovery_steps: None,
            mean_residual_improvement: 0.0,
        };
    }
    let n = reports.len() as f64;
    let mean = |f: fn(&BanditReport) -> f64| reports.iter().map(f).sum::<f64>() / n;
    let mean_expert = |f: fn(&L2ExpertMetrics) -> f64, expert: usize| {
        reports
            .iter()
            .map(|report| f(&report.expert_metrics[expert]))
            .sum::<f64>()
            / n
    };
    L2BenchmarkAggregate {
        runs,
        mean_reward: mean(|r| r.mean_reward),
        mean_adjusted_reward: mean(|r| r.mean_adjusted_reward),
        best_arm_rate: mean(|r| r.best_arm_rate),
        error_decrease_rate: reports.iter().filter(|r| r.error_decreased).count() as f64 / n,
        mean_initial_error: mean(|r| r.initial_avg_error),
        mean_final_error: mean(|r| r.final_avg_error),
        mean_error_delta: mean(|r| r.final_avg_error - r.initial_avg_error),
        mean_patches_accepted: mean(|r| r.patches_accepted as f64),
        mean_fixed_point_enters: mean(|r| r.fixed_point_enters as f64),
        mean_fixed_point_exits: mean(|r| r.fixed_point_exits as f64),
        mean_max_fixed_point_dwell: mean(|r| r.max_fixed_point_dwell as f64),
        mean_l2_nudges: mean(|r| r.l2_nudges as f64),
        mean_l2_proposals: mean(|r| r.l2_proposals as f64),
        mean_l2_commits: mean(|r| r.l2_commits as f64),
        mean_action_switches: mean(|r| r.action_switches as f64),
        mean_post_commit_action_changes: mean(|r| r.post_commit_action_changes as f64),
        mean_post_commit_arm_changes: mean(|r| r.post_commit_arm_changes as f64),
        mean_distinct_actions: mean(|r| r.distinct_actions as f64),
        mean_l2_consequence_score: mean(|r| r.mean_l2_consequence_score),
        mean_final_score_breakdown: {
            // BTreeMap keeps each report's keys ordered. Accumulate in key order, then
            // sum across reports in the caller's deterministic report/seed order.
            let mut keys: Vec<&String> = reports
                .iter()
                .flat_map(|report| report.final_score_breakdown.keys())
                .collect();
            keys.sort_unstable();
            keys.dedup();
            keys.into_iter()
                .map(|key| {
                    let sum = reports
                        .iter()
                        .filter_map(|report| report.final_score_breakdown.get(key))
                        .sum::<f64>();
                    (key.clone(), sum / n)
                })
                .collect()
        },
        mean_final_alignment_score: mean(|r| r.final_alignment_score),
        mean_recovery_steps: {
            let recovered: Vec<u32> = reports.iter().filter_map(|r| r.recovery_steps).collect();
            (!recovered.is_empty())
                .then(|| recovered.iter().sum::<u32>() as f64 / recovered.len() as f64)
        },
        recovery_rate: reports
            .iter()
            .filter(|r| r.recovery_steps.is_some())
            .count() as f64
            / n,
        mean_l1_rollback_count: mean(|r| r.l1_rollback_count as f64),
        mean_l1_blocked_by_l2_count: mean(|r| r.l1_blocked_by_l2_count as f64),
        mean_l2_rollback_count: mean(|r| r.l2_rollback_count as f64),
        dayan_convergence_rate: reports.iter().filter(|r| r.dayan_converged).count() as f64 / n,
        mean_final_dayan_residual: mean(|r| r.final_dayan_residual),
        mean_dwell_hold_count: mean(|r| r.dwell_hold_count as f64),
        mean_margin_hold_count: mean(|r| r.margin_hold_count as f64),
        mean_active_steps: mean(|r| r.active_steps as f64),
        mean_committed_policies_applied: mean(|r| r.committed_policies_applied as f64),
        mean_expert_committed: core::array::from_fn(|expert| {
            mean_expert(|metrics| metrics.committed as f64, expert)
        }),
        mean_expert_applied: core::array::from_fn(|expert| {
            mean_expert(|metrics| metrics.applied as f64, expert)
        }),
        mean_expert_not_applied: core::array::from_fn(|expert| {
            mean_expert(|metrics| metrics.not_applied as f64, expert)
        }),
        mean_expert_reward: core::array::from_fn(|expert| {
            let applied = reports
                .iter()
                .map(|r| r.expert_metrics[expert].applied)
                .sum::<u64>();
            (applied > 0).then(|| {
                reports
                    .iter()
                    .map(|r| r.expert_metrics[expert].reward_sum)
                    .sum::<f64>()
                    / applied as f64
            })
        }),
        mean_lyapunov_vetoes: mean(|r| r.lyapunov_vetoes as f64),
        mean_meta_cache_hits: mean(|r| r.meta_cache_hits as f64),
        recovery_event_rate: if shift_events == 0 {
            0.0
        } else {
            mean(|r| r.recovery_latencies.len() as f64) / shift_events as f64
        },
        mean_warm_recovery_steps: {
            let recovered: Vec<u32> = reports
                .iter()
                .flat_map(|r| &r.warm_recovery_latencies)
                .copied()
                .collect();
            (!recovered.is_empty())
                .then(|| recovered.iter().sum::<u32>() as f64 / recovered.len() as f64)
        },
        mean_residual_improvement: mean(|r| r.mean_residual_improvement),
    }
}

fn cleanup_benchmark_files(state_path: &std::path::Path) {
    if let Some(parent) = state_path.parent() {
        let _ = std::fs::remove_dir_all(parent);
    }
}

fn paired_difference(differences: &[f64]) -> PairedMeanDifference {
    let n = differences.len() as f64;
    let mean = differences.iter().sum::<f64>() / n;
    if differences.len() < 2 {
        return PairedMeanDifference {
            mean,
            ci95_low: None,
            ci95_high: None,
        };
    }
    let variance = differences
        .iter()
        .map(|difference| (difference - mean).powi(2))
        .sum::<f64>()
        / (n - 1.0);
    // Student t critical values (df=1..30, two-sided 95%); normal for df>30.
    const T95: [f64; 30] = [
        12.706, 4.303, 3.182, 2.776, 2.571, 2.447, 2.365, 2.306, 2.262, 2.228, 2.201, 2.179, 2.160,
        2.145, 2.131, 2.120, 2.110, 2.101, 2.093, 2.086, 2.080, 2.074, 2.069, 2.064, 2.060, 2.056,
        2.052, 2.048, 2.045, 2.042,
    ];
    let df = differences.len() - 1;
    let critical = T95.get(df - 1).copied().unwrap_or(1.96);
    let half_width = critical * (variance / n).sqrt();
    PairedMeanDifference {
        mean,
        ci95_low: Some(mean - half_width),
        ci95_high: Some(mean + half_width),
    }
}

fn mean(values: &[f64]) -> f64 {
    values.iter().sum::<f64>() / values.len() as f64
}

fn pearson(x: &[f64], y: &[f64]) -> Option<f64> {
    if x.len() < 2 || x.len() != y.len() {
        return None;
    }
    let mx = mean(x);
    let my = mean(y);
    let numerator = x
        .iter()
        .zip(y)
        .map(|(a, b)| (a - mx) * (b - my))
        .sum::<f64>();
    let sx = x.iter().map(|a| (a - mx).powi(2)).sum::<f64>().sqrt();
    let sy = y.iter().map(|b| (b - my).powi(2)).sum::<f64>().sqrt();
    (sx > 0.0 && sy > 0.0).then_some(numerator / (sx * sy))
}

fn ranks(values: &[f64]) -> Vec<f64> {
    let mut sorted: Vec<(usize, f64)> = values.iter().copied().enumerate().collect();
    sorted.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(core::cmp::Ordering::Equal));
    let mut ranks = vec![0.0; values.len()];
    let mut start = 0;
    while start < sorted.len() {
        let mut end = start + 1;
        while end < sorted.len() && sorted[end].1 == sorted[start].1 {
            end += 1;
        }
        let rank = (start + end - 1) as f64 / 2.0 + 1.0;
        for &(index, _) in &sorted[start..end] {
            ranks[index] = rank;
        }
        start = end;
    }
    ranks
}

fn correlation(pairs: &[(f64, f64)]) -> CorrelationDiagnostic {
    let x: Vec<f64> = pairs.iter().map(|pair| pair.0).collect();
    let y: Vec<f64> = pairs.iter().map(|pair| pair.1).collect();
    let spearman = pearson(&ranks(&x), &ranks(&y));
    let spearman_bootstrap_ci95 = if pairs.len() >= 8 {
        let mut rng = Rng::new(0x53504541524d414e);
        let mut bootstrap = Vec::with_capacity(1_000);
        for _ in 0..1_000 {
            let mut sample_x = Vec::with_capacity(pairs.len());
            let mut sample_y = Vec::with_capacity(pairs.len());
            for _ in 0..pairs.len() {
                let index = ((rng.next_f64() * pairs.len() as f64) as usize).min(pairs.len() - 1);
                sample_x.push(x[index]);
                sample_y.push(y[index]);
            }
            if let Some(value) = pearson(&ranks(&sample_x), &ranks(&sample_y)) {
                bootstrap.push(value);
            }
        }
        bootstrap.sort_by(|a, b| a.partial_cmp(b).unwrap_or(core::cmp::Ordering::Equal));
        (bootstrap.len() >= 20).then(|| {
            [
                bootstrap[bootstrap.len() / 40],
                bootstrap[bootstrap.len() * 39 / 40],
            ]
        })
    } else {
        None
    };
    CorrelationDiagnostic {
        samples: pairs.len(),
        pearson: pearson(&x, &y),
        spearman,
        spearman_bootstrap_ci95,
    }
}

fn signal_diagnostics(samples: &[L2DiagnosticSample]) -> L2SignalDiagnostics {
    let mut reward = Vec::new();
    let mut residual = Vec::new();
    let mut regime = Vec::new();
    let mut optimal = Vec::new();
    for pair in samples.windows(2) {
        let current = &pair[0];
        let next = &pair[1];
        if current.normalized_energy > 0.0 {
            reward.push((current.spectral_bias, next.reward));
        }
        optimal.push((current.spectral_bias, next.optimal_arm as f64));
        residual.push((current.convergence_residual, next.convergence_residual));
        regime.push((
            current.spectral_bias,
            f64::from(current.optimal_arm != next.optimal_arm),
        ));
    }
    L2SignalDiagnostics {
        bias_to_next_reward: correlation(&reward),
        residual_to_next_error: correlation(&residual),
        bias_to_regime_change: correlation(&regime),
        bias_to_next_optimal_arm: correlation(&optimal),
    }
}

fn bootstrap_difference(differences: &[f64], seed: u64) -> PairedMeanDifference {
    let mean_difference = mean(differences);
    if differences.len() < 2 {
        return PairedMeanDifference {
            mean: mean_difference,
            ci95_low: None,
            ci95_high: None,
        };
    }
    let mut rng = Rng::new(seed);
    let mut means = Vec::with_capacity(2_000);
    let mut sample = vec![0.0; differences.len()];
    for _ in 0..2_000 {
        for value in &mut sample {
            let index =
                ((rng.next_f64() * differences.len() as f64) as usize).min(differences.len() - 1);
            *value = differences[index];
        }
        means.push(mean(&sample));
    }
    means.sort_by(|a, b| a.partial_cmp(b).unwrap_or(core::cmp::Ordering::Equal));
    PairedMeanDifference {
        mean: mean_difference,
        ci95_low: Some(means[(means.len() as f64 * 0.025) as usize]),
        ci95_high: Some(means[(means.len() as f64 * 0.975) as usize]),
    }
}

/// Compare identical seeded bandit runs with L2 interventions disabled/enabled.
/// The benchmark is deterministic and reports deltas rather than treating a
/// single successful run as evidence of improvement.
pub fn run_l2_benchmark(
    runs: u32,
    episodes: u32,
    steps_per_episode: u32,
    seed: u64,
) -> Result<L2BenchmarkReport> {
    run_l2_benchmark_scenario("nonstationary", runs, episodes, steps_per_episode, seed)
}

/// Run the paired L2 benchmark under a named deterministic environment.
pub fn run_l2_benchmark_scenario(
    scenario: &str,
    runs: u32,
    episodes: u32,
    steps_per_episode: u32,
    seed: u64,
) -> Result<L2BenchmarkReport> {
    let negative_reward_required = if scenario == "stable" { 5 } else { 3 };
    let (commit_threshold, commit_cooldown) = if scenario == "degraded" {
        (0.50, 3)
    } else {
        // Confidence of the one-step residual model, not anomaly severity.
        (0.35, 3)
    };
    run_l2_benchmark_scenario_with_gate(
        scenario,
        runs,
        episodes,
        steps_per_episode,
        seed,
        commit_threshold,
        commit_cooldown,
        negative_reward_required,
        None,
    )
}

#[allow(clippy::too_many_arguments)]
/// Runs run L2 benchmark scenario with gate and returns its result.
pub fn run_l2_benchmark_scenario_with_gate(
    scenario: &str,
    runs: u32,
    episodes: u32,
    steps_per_episode: u32,
    seed: u64,
    commit_threshold: f64,
    commit_cooldown_steps: u64,
    negative_reward_required: u32,
    experiment: Option<L2ExperimentSettings>,
) -> Result<L2BenchmarkReport> {
    let scenario = match scenario {
        "stable" | "nonstationary" | "degraded" | "fixedpoint" | "regime_shift"
        | "cyclic_shift" => scenario,
        other => {
            return Err(crate::error::OmegaError::Config(format!(
                "unknown benchmark scenario: {other}"
            )))
        }
    };
    let runs = runs.max(1);
    let mut paired_runs = Vec::with_capacity(runs as usize);

    for i in 0..runs {
        let run_seed = seed.wrapping_add(i as u64);
        let base_dir = temp_dir().join(format!(
            "omega-l2-benchmark-{}-{}-base",
            std::process::id(),
            crate::new_uuid()
        ));
        let treatment_dir = temp_dir().join(format!(
            "omega-l2-benchmark-{}-{}-l2",
            std::process::id(),
            crate::new_uuid()
        ));
        std::fs::create_dir_all(&base_dir)
            .map_err(|error| crate::error::OmegaError::Persist(error.to_string()))?;
        std::fs::create_dir_all(&treatment_dir)
            .map_err(|error| crate::error::OmegaError::Persist(error.to_string()))?;
        let base_path = base_dir.join("state.json");
        let treatment_path = treatment_dir.join("state.json");

        let mut base = Kernel::with_bandit_ucb(&base_path);
        let mut l2 = Kernel::with_bandit_ucb(&treatment_path);
        for branch in [&mut base, &mut l2] {
            branch.set_autosave(false);
            branch.set_auto_checkpoint_on_patch(false);
            branch.set_dump_trajectory(false);
            branch.inner_mut().l1.self_modify_enabled = true;
            branch
                .inner_mut()
                .l1
                .store
                .active
                .insert("cognitive_rules".into(), "self-model bias damp rule".into());
            branch.inner_mut().l2.detector.window = 2;
            branch.inner_mut().l2.detector.pred_threshold = 0.30;
            branch.inner_mut().l2.detector.self_ref_threshold = 0.30;
            branch.inner_mut().l2.detector.cooldown_steps = 0;
            branch.inner_mut().l2.commit_threshold = commit_threshold.clamp(0.0, 1.0);
            branch.inner_mut().l2.commit_cooldown_steps = commit_cooldown_steps;
            branch.inner_mut().l2.negative_reward_required = negative_reward_required.max(1);
            branch.inner_mut().l2.configure_spectral_control(
                experiment
                    .as_ref()
                    .is_some_and(|settings| settings.spectral_control),
            );
            branch.inner_mut().l2.spectral_gate.configure_ablation(
                experiment
                    .as_ref()
                    .is_some_and(|settings| settings.purity_prior),
                experiment
                    .as_ref()
                    .is_some_and(|settings| settings.reverse_brake),
                experiment
                    .as_ref()
                    .is_some_and(|settings| settings.history_discount),
            );
            if matches!(scenario, "regime_shift" | "cyclic_shift") {
                let mut state = branch.inner_mut().l0.decision.snapshot();
                state.discount_factor = 0.85;
                branch.inner_mut().l0.decision.restore(state);
            }
        }
        // Only the intervention permission differs. Every other policy,
        // feedback, persistence, and environment parameter is paired.
        base.set_l2_enabled(false);
        l2.set_l2_enabled(true);

        // Both arms start from the same coherent policy context. This makes
        // fixed-point entry observable while preserving a fair intervention
        // comparison: only L2 is disabled in the baseline.
        base.inner_mut()
            .l1
            .store
            .active
            .insert("cognitive_rules".into(), "self-model bias damp rule".into());
        base.set_l2_enabled(false);
        base.inner_mut().l1.self_modify_enabled = true;
        if matches!(scenario, "regime_shift" | "cyclic_shift") {
            let mut state = base.inner_mut().l0.decision.snapshot();
            state.discount_factor = 0.85;
            base.inner_mut().l0.decision.restore(state);
        }
        let base_report = run_bandit_task_seeded_scenario(
            &mut base,
            episodes,
            steps_per_episode,
            run_seed,
            scenario,
            None,
        )?;
        cleanup_benchmark_files(&base_path);
        let treatment_report = run_bandit_task_seeded_scenario(
            &mut l2,
            episodes,
            steps_per_episode,
            run_seed,
            scenario,
            experiment.clone(),
        )?;
        cleanup_benchmark_files(&treatment_path);
        paired_runs.push(L2PairedRun {
            seed: run_seed,
            delta_mean_reward: treatment_report.mean_reward - base_report.mean_reward,
            delta_best_arm_rate: treatment_report.best_arm_rate - base_report.best_arm_rate,
            delta_error_delta: (treatment_report.final_avg_error
                - treatment_report.initial_avg_error)
                - (base_report.final_avg_error - base_report.initial_avg_error),
            treatment_influenced_l0: treatment_report.committed_policies_applied > 0
                || treatment_report.l2_nudges > 0,
            baseline: base_report,
            treatment: treatment_report,
        });
    }

    let baseline: Vec<_> = paired_runs.iter().map(|run| run.baseline.clone()).collect();
    let treatment: Vec<_> = paired_runs
        .iter()
        .map(|run| run.treatment.clone())
        .collect();
    let baseline = aggregate(&baseline);
    let treatment = aggregate(&treatment);
    let reward_differences: Vec<_> = paired_runs
        .iter()
        .map(|run| run.delta_mean_reward)
        .collect();
    let best_arm_differences: Vec<_> = paired_runs
        .iter()
        .map(|run| run.delta_best_arm_rate)
        .collect();
    let paired_reward_difference = paired_difference(&reward_differences);
    let paired_best_arm_difference = paired_difference(&best_arm_differences);
    let l0_influenced_runs = paired_runs
        .iter()
        .filter(|run| run.treatment_influenced_l0)
        .count() as u32;
    Ok(L2BenchmarkReport {
        scenario: scenario.into(),
        episodes,
        steps_per_episode,
        runs,
        seed,
        delta_mean_reward: treatment.mean_reward - baseline.mean_reward,
        delta_best_arm_rate: treatment.best_arm_rate - baseline.best_arm_rate,
        delta_error_decrease_rate: treatment.error_decrease_rate - baseline.error_decrease_rate,
        paired_reward_difference,
        paired_best_arm_difference,
        paired_reward_bootstrap: bootstrap_difference(&reward_differences, seed ^ 0x4c32),
        paired_best_arm_bootstrap: bootstrap_difference(&best_arm_differences, seed ^ 0x4241),
        l0_influenced_runs,
        baseline_l2_disabled: baseline,
        treatment_l2_enabled: treatment,
        paired_runs,
    })
}

/// Run a 2x2 factorial comparison of independent L1/L2 intervention gates.
/// Arm order is L0, L1-only, L2-only, and L1+L2. Each position in a seeded
/// environment consumes one random number, providing common random numbers
/// across arms without changing the existing task environment.
#[allow(clippy::too_many_arguments)]
pub fn run_l1_l2_factorial_benchmark(
    scenario: &str,
    runs: u32,
    episodes: u32,
    steps_per_episode: u32,
    seed: u64,
    commit_threshold: f64,
    commit_cooldown_steps: u64,
    negative_reward_required: u32,
) -> Result<FactorialBenchmarkReport> {
    if !matches!(
        scenario,
        "stable" | "nonstationary" | "degraded" | "fixedpoint" | "regime_shift" | "cyclic_shift"
    ) {
        return Err(crate::error::OmegaError::Config(format!(
            "unknown benchmark scenario: {scenario}"
        )));
    }
    let runs = runs.max(1);
    let mut paired_runs = Vec::with_capacity(runs as usize);
    for index in 0..runs {
        let run_seed = seed.wrapping_add(index as u64);
        let mut arm_reports = Vec::with_capacity(FactorialArm::ALL.len());
        for arm in FactorialArm::ALL {
            let directory = temp_dir().join(format!(
                "omega-l1-l2-factorial-{}-{}-{}",
                std::process::id(),
                crate::new_uuid(),
                arm.label()
            ));
            std::fs::create_dir_all(&directory)
                .map_err(|error| crate::error::OmegaError::Persist(error.to_string()))?;
            let path = directory.join("state.json");
            let mut kernel = Kernel::with_bandit_ucb(&path);
            kernel.set_autosave(false);
            kernel.set_auto_checkpoint_on_patch(false);
            kernel.set_dump_trajectory(false);
            kernel.inner_mut().l1.self_modify_enabled = arm.l1_enabled();
            kernel.inner_mut().l1.shadow_mode = false;
            kernel
                .inner_mut()
                .l1
                .store
                .active
                .insert("cognitive_rules".into(), "self-model bias damp rule".into());
            kernel.inner_mut().l2.detector.window = 2;
            kernel.inner_mut().l2.detector.pred_threshold = 0.30;
            kernel.inner_mut().l2.detector.self_ref_threshold = 0.30;
            kernel.inner_mut().l2.detector.cooldown_steps = 0;
            kernel.inner_mut().l2.commit_threshold = commit_threshold.clamp(0.0, 1.0);
            kernel.inner_mut().l2.commit_cooldown_steps = commit_cooldown_steps;
            kernel.inner_mut().l2.negative_reward_required = negative_reward_required.max(1);
            kernel.inner_mut().l2.configure_spectral_control(false);
            if matches!(scenario, "regime_shift" | "cyclic_shift") {
                let mut state = kernel.inner_mut().l0.decision.snapshot();
                state.discount_factor = 0.85;
                kernel.inner_mut().l0.decision.restore(state);
            }
            kernel.set_l2_enabled(arm.l2_enabled());
            let report = run_bandit_task_seeded_scenario(
                &mut kernel,
                episodes,
                steps_per_episode,
                run_seed,
                scenario,
                None,
            );
            cleanup_benchmark_files(&path);
            arm_reports.push(report?);
        }
        let arms: [BanditReport; 4] = arm_reports.try_into().map_err(|_| {
            crate::error::OmegaError::Memory("factorial benchmark requires four arms".into())
        })?;
        let l1_reward_delta = arms[1].mean_reward - arms[0].mean_reward;
        let l2_reward_delta = arms[2].mean_reward - arms[0].mean_reward;
        let joint_reward_delta = arms[3].mean_reward - arms[0].mean_reward;
        let interaction_reward_delta =
            arms[3].mean_reward - arms[2].mean_reward - arms[1].mean_reward + arms[0].mean_reward;
        paired_runs.push(FactorialRun {
            seed: run_seed,
            arms,
            l1_reward_delta,
            l2_reward_delta,
            joint_reward_delta,
            interaction_reward_delta,
        });
    }
    let aggregates = FactorialArm::ALL.map(|arm| {
        let reports: Vec<_> = paired_runs
            .iter()
            .map(|run| run.arms[arm.index()].clone())
            .collect();
        aggregate(&reports)
    });
    let [l1_effect, l2_effect, joint_effect, interaction_effect] =
        factorial_effects(&paired_runs, seed);
    Ok(FactorialBenchmarkReport {
        scenario: scenario.into(),
        episodes,
        steps_per_episode,
        runs,
        seed,
        arm_order: FactorialArm::ALL,
        aggregates,
        l1_effect,
        l2_effect,
        joint_effect,
        interaction_effect,
        paired_runs,
    })
}

/// Execute the preregistered discovery/validation L2-only gain matrix. The
/// factorial reports retain L1 and interaction diagnostics, but only L2-L0
/// participates in the gain verdict. No controller setting is tuned here.
pub fn run_l2_gain_matrix(
    runs: u32,
    episodes: u32,
    steps_per_episode: u32,
) -> Result<L2GainMatrixReport> {
    if runs < 2 || episodes == 0 || steps_per_episode == 0 {
        return Err(crate::error::OmegaError::Config(
            "gain matrix requires at least two paired seeds and nonzero horizon".into(),
        ));
    }
    let mut reports = Vec::with_capacity(L2_GAIN_SCENARIOS.len() * 2);
    for seed in [L2_GAIN_DISCOVERY_SEED, L2_GAIN_VALIDATION_SEED] {
        for scenario in L2_GAIN_SCENARIOS {
            let negative_reward_required = if scenario == "stable" { 5 } else { 3 };
            reports.push(run_l1_l2_factorial_benchmark(
                scenario,
                runs,
                episodes,
                steps_per_episode,
                seed,
                0.35,
                3,
                negative_reward_required,
            )?);
        }
    }
    let assessment = assess_l2_gain_matrix(&reports)?;
    let kernel_runs = runs as u64 * L2_GAIN_SCENARIOS.len() as u64 * 2 * 4;
    Ok(L2GainMatrixReport {
        schema_version: 1,
        design: "paired_l1_l2_factorial_discovery_validation_v1".into(),
        runs_per_scenario: runs,
        episodes,
        steps_per_episode,
        scenarios: L2_GAIN_SCENARIOS,
        discovery_seed: L2_GAIN_DISCOVERY_SEED,
        validation_seed: L2_GAIN_VALIDATION_SEED,
        kernel_runs,
        decision_steps: kernel_runs * episodes as u64 * steps_per_episode as u64,
        reports,
        assessment,
    })
}

/// Per-arm metrics from the closed-loop multi-parameter comparison benchmark.
#[derive(Debug, Clone, Serialize, serde::Deserialize)]
#[non_exhaustive]
pub struct ClosedLoopComparisonRow {
    /// Arm name (`baseline_no_adapt`, `l1_unbounded`, `l1_l2_guarded`).
    pub arm: String,
    /// Total executed steps.
    pub steps: u32,
    /// Overall mean environment error across all steps.
    pub mean_error: f64,
    /// Mean environment error during the regime-drift phase.
    pub drift_mean_error: f64,
    /// 95th percentile tail error across all steps.
    pub p95_error: f64,
    /// Steps after drift onset until error drops below 0.30 (`None` if unrecovered).
    pub drift_recovery_steps: Option<u32>,
    /// Fraction of steady-state steps where parameters remained untouched.
    pub steady_preservation_rate: f64,
    /// Number of parameter direction reversals or noisy oscillations.
    pub param_oscillations: u32,
    /// Total patches emitted by the session.
    pub patches_emitted: u32,
    /// Total rollbacks triggered by the session.
    pub rollbacks: u32,
}

/// Report comparing no-adaptation, L1-only, and L1+L2 guarded closed loops.
#[derive(Debug, Clone, Serialize, serde::Deserialize)]
#[non_exhaustive]
pub struct ClosedLoopComparisonReport {
    /// Total steps executed per arm.
    pub steps_per_arm: u32,
    /// Per-arm comparison rows.
    pub rows: Vec<ClosedLoopComparisonRow>,
}

/// Runs a true closed-loop multi-parameter comparison where directives feed back
/// into the simulated service environment across steady, drift, and noisy phases.
pub fn run_closed_loop_comparison_benchmark(steps: u32) -> ClosedLoopComparisonReport {
    use crate::api::{
        ClosedLoopKernel, ClosedLoopSession, DefaultKernel, ExternalOutcome, StepTelemetry,
    };
    use crate::config::{KernelConfig, LoopPreset, ParameterSpec, PatchDirection, PolicySchema};

    let total_steps = steps.max(30);
    let steady_end = total_steps / 5;
    let drift_end = (total_steps * 3) / 5;

    let schema = PolicySchema {
        params: vec![
            ParameterSpec {
                name: String::from("concurrency_scale"),
                min: 0.1,
                max: 1.0,
                initial: 0.8,
                max_step: 0.15,
                direction: PatchDirection::DecreaseOnError,
            },
            ParameterSpec {
                name: String::from("backoff_scale"),
                min: 0.1,
                max: 1.0,
                initial: 0.2,
                max_step: 0.15,
                direction: PatchDirection::IncreaseOnError,
            },
        ],
    };

    let arms = [
        ("baseline_no_adapt", None),
        ("l1_unbounded", Some(LoopPreset::HotPatcher)),
        ("l1_l2_guarded", Some(LoopPreset::ControlPlane)),
    ];

    let base_dir = std::env::temp_dir().join(format!(
        "omega-closed-loop-cmp-{}-{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_nanos())
            .unwrap_or(0)
    ));
    let _ = std::fs::create_dir_all(&base_dir);

    let mut rows = Vec::with_capacity(arms.len());
    for (arm_name, maybe_preset) in arms {
        let mut concurrency = 0.8_f64;
        let mut backoff = 0.2_f64;
        let mut prev_conc_delta = 0.0_f64;
        let mut prev_err = 0.06_f64;
        let mut last_outcome: Option<ExternalOutcome> = None;

        let mut session = maybe_preset.map(|preset| {
            let mut cfg = KernelConfig::default()
                .with_loop_preset(preset)
                .with_policy_schema(schema.clone());
            cfg.error_threshold = 0.15;
            let mut kernel =
                DefaultKernel::with_state_path(base_dir.join(format!("{arm_name}.json")));
            kernel.set_autosave(false);
            kernel.set_dump_trajectory(false);
            kernel.set_auto_checkpoint_on_patch(true);
            ClosedLoopSession::from_kernel(kernel, &cfg)
        });

        let mut errors = Vec::with_capacity(total_steps as usize);
        let mut drift_err_sum = 0.0_f64;
        let mut drift_count = 0u32;
        let mut drift_recovery_steps: Option<u32> = None;
        let mut steady_untouched = 0u32;
        let mut param_oscillations = 0u32;
        let mut patches_emitted = 0u32;
        let mut rollbacks = 0u32;

        for step in 1..=total_steps {
            let (target_c, target_b) = if step <= steady_end {
                (0.80_f64, 0.20_f64)
            } else {
                (0.30_f64, 0.75_f64)
            };

            let dist = ((concurrency - target_c).powi(2) + (backoff - target_b).powi(2)).sqrt();
            let ripple = 0.01 * ((step as f64) * 0.7).sin().abs();
            let is_spike = step > drift_end && step.is_multiple_of(5);
            let spike_err = if is_spike { 0.45 } else { 0.0 };
            let risk = if is_spike { 0.82 } else { 0.15 };
            let err = (0.06 + 0.55 * dist + ripple + spike_err).clamp(0.0, 1.0);

            errors.push(err);
            if step > steady_end && step <= drift_end {
                drift_err_sum += err;
                drift_count += 1;
                if drift_recovery_steps.is_none() && err < 0.30 {
                    drift_recovery_steps = Some(step - steady_end);
                }
            }

            if let Some(sess) = session.as_mut() {
                let tel = StepTelemetry {
                    step_id: u64::from(step),
                    prediction_error: err,
                    observed_risk: risk,
                    signal_window: vec![err],
                    last_outcome,
                };
                if let Ok(dir) = sess.step_external(tel) {
                    let prev_c = concurrency;
                    let prev_b = backoff;
                    if let Some(params) = dir.active_params.as_ref() {
                        if let Some(c) = params.get("concurrency_scale") {
                            concurrency = *c;
                        }
                        if let Some(b) = params.get("backoff_scale") {
                            backoff = *b;
                        }
                    }
                    let moved =
                        (concurrency - prev_c).abs() > 1e-6 || (backoff - prev_b).abs() > 1e-6;
                    if step <= steady_end && !moved {
                        steady_untouched += 1;
                    }
                    let conc_delta = concurrency - prev_c;
                    if conc_delta.abs() > 1e-6 {
                        if prev_conc_delta.abs() > 1e-6
                            && conc_delta.signum() != prev_conc_delta.signum()
                        {
                            param_oscillations += 1;
                        }
                        prev_conc_delta = conc_delta;
                    }
                    if dir.rule_patch.is_some() {
                        patches_emitted += 1;
                    }
                    if dir.rollback_to_checkpoint.is_some() {
                        rollbacks += 1;
                    }
                    last_outcome = if moved && (is_spike || err > prev_err + 0.05) {
                        Some(ExternalOutcome::Degraded)
                    } else if moved && err < prev_err {
                        Some(ExternalOutcome::AcceptedAndImproved)
                    } else {
                        None
                    };
                }
            } else if step <= steady_end {
                steady_untouched += 1;
            }
            prev_err = err;
        }

        let mean_error = errors.iter().sum::<f64>() / (errors.len().max(1) as f64);
        let mut sorted = errors.clone();
        sorted.sort_by(|a, b| a.total_cmp(b));
        let p95_idx = ((sorted.len() as f64) * 0.95).floor() as usize;
        let p95_error = sorted
            .get(p95_idx.min(sorted.len().saturating_sub(1)))
            .copied()
            .unwrap_or(0.0);

        rows.push(ClosedLoopComparisonRow {
            arm: String::from(arm_name),
            steps: total_steps,
            mean_error,
            drift_mean_error: drift_err_sum / f64::from(drift_count.max(1)),
            p95_error,
            drift_recovery_steps,
            steady_preservation_rate: f64::from(steady_untouched) / f64::from(steady_end.max(1)),
            param_oscillations,
            patches_emitted,
            rollbacks,
        });
    }

    let _ = std::fs::remove_dir_all(&base_dir);
    ClosedLoopComparisonReport {
        steps_per_arm: total_steps,
        rows,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::env::temp_dir;

    #[test]
    fn gain_matrix_has_fixed_independent_design_and_replay() {
        let first = run_l2_gain_matrix(2, 8, 8).unwrap();
        let second = run_l2_gain_matrix(2, 8, 8).unwrap();
        assert_eq!(
            serde_json::to_vec(&first).unwrap(),
            serde_json::to_vec(&second).unwrap()
        );
        assert_eq!(first.schema_version, 1);
        assert_eq!(first.reports.len(), 8);
        assert_eq!(first.kernel_runs, 64);
        assert_eq!(first.decision_steps, 4_096);
        assert_ne!(first.discovery_seed, first.validation_seed);
        assert!(first.discovery_seed + first.runs_per_scenario as u64 <= first.validation_seed);
        for report in &first.reports {
            assert_eq!(report.runs, 2);
            assert_eq!(report.arm_order, FactorialArm::ALL);
            for pair in &report.paired_runs {
                for (arm, arm_report) in FactorialArm::ALL.iter().zip(&pair.arms) {
                    assert!(arm_report.mean_reward.is_finite());
                    assert!(arm_report.mean_adjusted_reward.is_finite());
                    if !arm.l1_enabled() {
                        assert_eq!(arm_report.patches_accepted, 0);
                        assert_eq!(arm_report.l1_rollback_count, 0);
                    }
                    if !arm.l2_enabled() {
                        assert_eq!(arm_report.l2_proposals, 0);
                        assert_eq!(arm_report.l2_commits, 0);
                        assert_eq!(arm_report.committed_policies_applied, 0);
                        assert_eq!(arm_report.l2_rollback_count, 0);
                    }
                }
            }
        }
        let mut missing_primary = first.reports.clone();
        missing_primary.retain(|report| {
            !(report.scenario == "regime_shift" && report.seed == L2_GAIN_VALIDATION_SEED)
        });
        assert!(assess_l2_gain_matrix(&missing_primary).is_err());
        let mut duplicate_primary = first.reports.clone();
        duplicate_primary[6] = duplicate_primary[2].clone();
        assert!(assess_l2_gain_matrix(&duplicate_primary).is_err());
        let mut missing_seed = first.reports.clone();
        missing_seed[2].paired_runs.pop();
        assert!(assess_l2_gain_matrix(&missing_seed).is_err());
        assert!(run_l2_gain_matrix(1, 8, 8).is_err());
        assert!(run_l2_gain_matrix(2, 0, 8).is_err());
        assert!(run_l2_gain_matrix(2, 8, 0).is_err());
    }

    #[test]
    fn gain_verdict_requires_execution_discovery_validation_and_safety() {
        let mut matrix = run_l2_gain_matrix(2, 8, 8).unwrap();
        for report in &mut matrix.reports {
            for pair in &mut report.paired_runs {
                pair.arms[FactorialArm::L2.index()].committed_policies_applied = 1;
            }
            if report.scenario == "regime_shift" {
                report.l2_effect.reward = PairedMeanDifference {
                    mean: 0.02,
                    ci95_low: Some(0.01),
                    ci95_high: Some(0.03),
                };
            }
            if report.scenario == "stable" {
                report.l2_effect.reward = PairedMeanDifference {
                    mean: 0.0,
                    ci95_low: Some(-0.005),
                    ci95_high: Some(0.005),
                };
            }
        }
        let assessment = assess_l2_gain_matrix(&matrix.reports).unwrap();
        assert!(assessment.mechanism_precondition_met);
        assert!(assessment.reproducible_gain);

        let mut no_execution = matrix.clone();
        for report in &mut no_execution.reports {
            if report.scenario == "regime_shift" && report.seed == L2_GAIN_VALIDATION_SEED {
                for pair in &mut report.paired_runs {
                    pair.arms[FactorialArm::L2.index()].committed_policies_applied = 0;
                }
            }
        }
        let assessment = assess_l2_gain_matrix(&no_execution.reports).unwrap();
        assert!(!assessment.mechanism_precondition_met);
        assert!(!assessment.reproducible_gain);
        assert!(assessment.conclusion.contains("No executed"));

        let mut failed_replication = matrix.clone();
        let validation = failed_replication
            .reports
            .iter_mut()
            .find(|report| {
                report.scenario == "regime_shift" && report.seed == L2_GAIN_VALIDATION_SEED
            })
            .unwrap();
        validation.l2_effect.reward.ci95_low = Some(-0.01);
        let assessment = assess_l2_gain_matrix(&failed_replication.reports).unwrap();
        assert!(!assessment.validation_reproduced);
        assert!(!assessment.reproducible_gain);
        assert!(assessment.conclusion.contains("did not reproduce"));

        let mut unsafe_stable = matrix;
        let stable = unsafe_stable
            .reports
            .iter_mut()
            .find(|report| report.scenario == "stable" && report.seed == L2_GAIN_DISCOVERY_SEED)
            .unwrap();
        stable.l2_effect.reward.ci95_low = Some(-0.011);
        let assessment = assess_l2_gain_matrix(&unsafe_stable.reports).unwrap();
        assert!(!assessment.discovery_safety_passed);
        assert!(!assessment.reproducible_gain);
    }

    #[test]
    fn preregistered_gain_defaults_are_large_and_unchanged() {
        assert_eq!(L2_GAIN_DEFAULT_RUNS, 30);
        assert_eq!(L2_GAIN_DEFAULT_EPISODES, 12);
        assert_eq!(L2_GAIN_DEFAULT_STEPS, 12);
        assert_eq!(L2_GAIN_DISCOVERY_SEED, 20261115);
        assert_eq!(L2_GAIN_VALIDATION_SEED, 20270001);
        assert_eq!(L2_GAIN_SCENARIOS.len(), 4);
        let kernel_runs = L2_GAIN_DEFAULT_RUNS as u64 * 4 * 2 * 4;
        assert_eq!(kernel_runs, 960);
        assert_eq!(
            kernel_runs * L2_GAIN_DEFAULT_EPISODES as u64 * L2_GAIN_DEFAULT_STEPS as u64,
            138_240
        );
    }

    fn test_path(label: &str) -> std::path::PathBuf {
        let dir = temp_dir().join(format!(
            "omega-task-{}-{}-{}",
            std::process::id(),
            label,
            crate::new_uuid()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        dir.join("state.json")
    }

    #[test]
    fn factorial_benchmark_is_deterministic_and_separates_gates() {
        let run =
            || run_l1_l2_factorial_benchmark("regime_shift", 2, 8, 8, 73, 0.35, 3, 3).unwrap();
        let first = run();
        let second = run();
        assert_eq!(
            serde_json::to_vec(&first).unwrap(),
            serde_json::to_vec(&second).unwrap()
        );
        assert_eq!(first.arm_order, FactorialArm::ALL);
        for pair in &first.paired_runs {
            for (arm, report) in FactorialArm::ALL.iter().zip(&pair.arms) {
                if !arm.l1_enabled() {
                    assert_eq!(report.patches_accepted, 0);
                    assert_eq!(report.l1_rollback_count, 0);
                }
                if !arm.l2_enabled() {
                    assert_eq!(report.l2_proposals, 0);
                    assert_eq!(report.l2_commits, 0);
                    assert_eq!(report.committed_policies_applied, 0);
                    assert_eq!(report.l2_rollback_count, 0);
                    assert_eq!(report.l1_blocked_by_l2_count, 0);
                }
                assert!(report.mean_adjusted_reward.is_finite());
            }
            let values = [
                pair.arms[0].mean_reward,
                pair.arms[1].mean_reward,
                pair.arms[2].mean_reward,
                pair.arms[3].mean_reward,
            ];
            assert_eq!(pair.l1_reward_delta, values[1] - values[0]);
            assert_eq!(pair.l2_reward_delta, values[2] - values[0]);
            assert_eq!(pair.joint_reward_delta, values[3] - values[0]);
            assert_eq!(
                pair.interaction_reward_delta,
                values[3] - values[2] - values[1] + values[0]
            );
        }
        assert!(first
            .paired_runs
            .iter()
            .any(|pair| pair.arms[1].patches_accepted > 0));
        assert!(first
            .paired_runs
            .iter()
            .any(|pair| pair.arms[3].l1_blocked_by_l2_count > 0));
    }

    #[test]
    fn factorial_effect_uses_four_arm_interaction_contrast() {
        let report =
            run_l1_l2_factorial_benchmark("nonstationary", 3, 8, 8, 20261115, 0.35, 3, 3).unwrap();
        for (effect, selector) in [
            (&report.l1_effect, 0),
            (&report.l2_effect, 1),
            (&report.joint_effect, 2),
            (&report.interaction_effect, 3),
        ] {
            let differences = factorial_differences(&report.paired_runs, |arm| arm.mean_reward);
            assert_eq!(effect.reward, paired_difference(&differences[selector]));
        }
        assert!(run_l1_l2_factorial_benchmark("invalid", 1, 1, 1, 1, 0.35, 3, 3).is_err());
    }

    #[test]
    fn score_aggregation_and_json_ignore_hash_map_iteration_order() {
        let path = test_path("aggregate-order");
        let mut kernel = Kernel::with_bandit_ucb(&path);
        kernel.set_autosave(false);
        kernel.set_auto_checkpoint_on_patch(false);
        kernel.set_dump_trajectory(false);
        let mut left =
            run_bandit_task_seeded_scenario(&mut kernel, 2, 4, 73, "regime_shift", None).unwrap();
        let mut right = left.clone();
        left.final_score_breakdown = BTreeMap::from_iter([
            ("a".into(), 1.0e16),
            ("b".into(), 1.0),
            ("c".into(), -1.0e16),
        ]);
        right.final_score_breakdown = BTreeMap::from_iter([
            ("c".into(), -1.0e16),
            ("b".into(), 1.0),
            ("a".into(), 1.0e16),
        ]);
        assert_eq!(
            serde_json::to_vec(&left).unwrap(),
            serde_json::to_vec(&right).unwrap()
        );

        let mut reverse = right.clone();
        reverse.seed = left.seed.wrapping_add(1);
        let forward = aggregate(&[left.clone(), right.clone()]);
        let backward = aggregate(&[reverse, left]);
        assert_eq!(
            forward.mean_final_score_breakdown["a"],
            backward.mean_final_score_breakdown["a"]
        );
        assert_eq!(
            forward.mean_final_score_breakdown["b"],
            backward.mean_final_score_breakdown["b"]
        );
        assert_eq!(
            forward.mean_final_score_breakdown["c"],
            backward.mean_final_score_breakdown["c"]
        );
        assert_eq!(
            serde_json::to_vec(&forward.mean_final_score_breakdown).unwrap(),
            serde_json::to_vec(&backward.mean_final_score_breakdown).unwrap()
        );
        let _ = std::fs::remove_dir_all(path.parent().unwrap());
    }

    #[test]
    fn bandit_runs() {
        let path = test_path("bandit");
        let mut k = Kernel::with_state_path(&path);
        k.set_autosave(false);
        let report = run_bandit_task_seeded(&mut k, 4, 3, 42).unwrap();
        assert_eq!(report.episodes, 4);
        assert!(report.mean_reward >= 0.0);
        assert!(report.strategy_count >= 1);
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn reward_feeds_strategy_memory() {
        let path = test_path("reward");
        let mut k = Kernel::with_state_path(&path);
        k.set_autosave(false);
        k.set_auto_checkpoint_on_patch(false);
        let before = k.inner().l0.memory.strategy.retrieve("", 20).len();
        let report = run_bandit_task_seeded(&mut k, 3, 4, 7).unwrap();
        let after = k.inner().l0.memory.strategy.retrieve("", 20);
        assert!(after.len() >= before);
        assert!(after.iter().any(|s| s.success_count + s.fail_count > 0));
        assert_eq!(report.strategy_count, after.len());
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn seeded_bandit_is_deterministic() {
        let p1 = test_path("deterministic-a");
        let p2 = test_path("deterministic-b");
        let mut k1 = Kernel::with_state_path(&p1);
        let mut k2 = Kernel::with_state_path(&p2);
        k1.set_autosave(false);
        k2.set_autosave(false);
        k1.set_auto_checkpoint_on_patch(false);
        k2.set_auto_checkpoint_on_patch(false);
        let r1 = run_bandit_task_seeded(&mut k1, 5, 3, 12345).unwrap();
        let r2 = run_bandit_task_seeded(&mut k2, 5, 3, 12345).unwrap();
        assert_eq!(r1.mean_reward, r2.mean_reward);
        assert_eq!(r1.best_arm_rate, r2.best_arm_rate);
        assert_eq!(r1.strategy_count, r2.strategy_count);
        let _ = std::fs::remove_file(&p1);
        let _ = std::fs::remove_file(&p2);
    }

    #[test]
    fn bandit_reports_strategy_decay_metrics() {
        let path = test_path("decay");
        let mut k = Kernel::with_state_path(&path);
        k.set_autosave(false);
        k.set_auto_checkpoint_on_patch(false);
        // Longer run so some strategies go idle
        let report = run_bandit_task_seeded(&mut k, 6, 5, 99).unwrap();
        assert!(report.strategy_count >= 1);
        assert!(report.mean_strategy_weight > 0.0);
        // max_idle_steps should be tracked (may be 0 if all actions stay hot)
        let _ = report.max_idle_steps;
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn regime_shift_benchmark_exposes_recovery_and_residual() {
        let report = run_l2_benchmark_scenario("regime_shift", 2, 8, 8, 73).unwrap();
        assert_eq!(report.scenario, "regime_shift");
        for branch in [&report.baseline_l2_disabled, &report.treatment_l2_enabled] {
            assert!(branch.recovery_rate >= 0.0 && branch.recovery_rate <= 1.0);
            assert!(branch.mean_final_dayan_residual.is_finite());
            assert!(branch.mean_l1_rollback_count >= 0.0);
            assert!(branch.mean_dwell_hold_count >= 0.0);
        }
        assert!(report.treatment_l2_enabled.mean_dwell_hold_count > 0.0);
    }

    #[test]
    fn diagnostic_statistics_and_paired_replay_are_deterministic() {
        let ranks = ranks(&[0.2, 0.1, 0.2, 0.4]);
        assert_eq!(ranks, vec![2.5, 1.0, 2.5, 4.0]);
        assert!(pearson(&[1.0, 1.0], &[0.0, 1.0]).is_none());
        let constant = correlation(&[(0.0, 0.0); 8]);
        assert_eq!(constant.pearson, None);
        assert_eq!(constant.spearman, None);
        let settings = L2ExperimentSettings {
            spectral_control: true,
            purity_prior: true,
            reverse_brake: true,
            history_discount: true,
        };
        let first = run_l2_benchmark_scenario_with_gate(
            "regime_shift",
            2,
            8,
            8,
            20261115,
            0.35,
            3,
            3,
            Some(settings.clone()),
        )
        .unwrap();
        let second = run_l2_benchmark_scenario_with_gate(
            "regime_shift",
            2,
            8,
            8,
            20261115,
            0.35,
            3,
            3,
            Some(settings),
        )
        .unwrap();
        let json = |report: &L2BenchmarkReport| serde_json::to_value(report).unwrap();
        let first_json = json(&first);
        let second_json = json(&second);
        if first_json != second_json {
            fn first_difference<'a>(
                path: &str,
                left: &'a serde_json::Value,
                right: &'a serde_json::Value,
            ) -> Option<(String, &'a serde_json::Value, &'a serde_json::Value)> {
                match (left, right) {
                    (serde_json::Value::Object(left), serde_json::Value::Object(right)) => {
                        let mut keys: Vec<_> = left.keys().chain(right.keys()).collect();
                        keys.sort_unstable();
                        keys.dedup();
                        keys.into_iter().find_map(|key| {
                            first_difference(
                                &format!("{path}.{key}"),
                                left.get(key).unwrap_or(&serde_json::Value::Null),
                                right.get(key).unwrap_or(&serde_json::Value::Null),
                            )
                        })
                    }
                    (serde_json::Value::Array(left), serde_json::Value::Array(right)) => {
                        (0..left.len().max(right.len())).find_map(|index| {
                            first_difference(
                                &format!("{path}[{index}]"),
                                left.get(index).unwrap_or(&serde_json::Value::Null),
                                right.get(index).unwrap_or(&serde_json::Value::Null),
                            )
                        })
                    }
                    _ if left == right => None,
                    _ => Some((path.to_string(), left, right)),
                }
            }
            panic!(
                "replay mismatch: {:?}",
                first_difference("$", &first_json, &second_json)
            );
        }
        assert_eq!(
            serde_json::to_vec(&first).unwrap(),
            serde_json::to_vec(&second).unwrap()
        );
        for (left, right) in first.paired_runs.iter().zip(&second.paired_runs) {
            for (a, b) in [
                (&left.baseline, &right.baseline),
                (&left.treatment, &right.treatment),
            ] {
                assert_eq!(a.mean_reward, b.mean_reward);
                assert_eq!(a.best_arm_rate, b.best_arm_rate);
                assert_eq!(a.action_switches, b.action_switches);
                assert_eq!(a.patches_accepted, b.patches_accepted);
                assert_eq!(a.diagnostics, b.diagnostics);
            }
        }
        for run in first.paired_runs.iter().map(|run| &run.treatment) {
            let pipeline = run.pipeline.as_ref().unwrap();
            assert_eq!(pipeline.proposals, run.l2_commits as u64);
            for sample in run.diagnostics.as_ref().unwrap() {
                assert_eq!(sample.dry_run_treatment_arm, Some(sample.selected_arm));
            }
        }
        let run = &first.paired_runs[0].treatment;
        assert_eq!(run.pipeline.as_ref().unwrap().observations, 64);
        assert_eq!(run.diagnostics.as_ref().unwrap().len(), 64);
        assert!(run.signals.as_ref().unwrap().bias_to_next_reward.samples > 0);
    }

    #[test]
    fn diagnostics_do_not_change_the_paired_run() {
        let settings = L2ExperimentSettings::default();
        let plain = run_l2_benchmark_scenario_with_gate(
            "nonstationary",
            3,
            8,
            8,
            20261115,
            0.35,
            3,
            3,
            None,
        )
        .unwrap();
        let observed = run_l2_benchmark_scenario_with_gate(
            "nonstationary",
            3,
            8,
            8,
            20261115,
            0.35,
            3,
            3,
            Some(settings),
        )
        .unwrap();
        let without_diagnostics = |report: &L2BenchmarkReport| {
            let mut value = serde_json::to_value(report).unwrap();
            for pair in value["paired_runs"].as_array_mut().unwrap() {
                for branch in ["baseline", "treatment"] {
                    let branch = &mut pair[branch];
                    for field in ["pipeline", "diagnostics", "signals", "experiment"] {
                        branch.as_object_mut().unwrap().remove(field);
                    }
                }
            }
            value
        };
        assert_eq!(without_diagnostics(&plain), without_diagnostics(&observed));
    }

    #[test]
    fn l2_benchmark_is_paired_and_reports_intervention_limits() {
        let report = run_l2_benchmark(1, 8, 8, 42).unwrap();
        assert_eq!(report.runs, 1);
        assert_eq!(report.baseline_l2_disabled.mean_l2_nudges, 0.0);
        assert_eq!(report.baseline_l2_disabled.mean_l2_proposals, 0.0);
        assert_eq!(report.baseline_l2_disabled.mean_l2_commits, 0.0);
        assert_eq!(
            report.baseline_l2_disabled.mean_committed_policies_applied,
            0.0
        );
        assert!(report.treatment_l2_enabled.mean_final_alignment_score > 0.0);
        assert!(report.treatment_l2_enabled.mean_dwell_hold_count > 0.0);
        // A proposal/cache hit is not evidence that L2 influenced L0. Any
        // actual commit must be attributed to its immutable applied snapshot.
        assert_eq!(report.paired_reward_difference.ci95_low, None);
        assert_eq!(report.paired_reward_difference.ci95_high, None);
        assert_eq!(report.paired_runs.len(), 1);
        let paired = &report.paired_runs[0];
        let treatment_influenced_l0 =
            paired.treatment.committed_policies_applied > 0 || paired.treatment.l2_nudges > 0;
        assert_eq!(
            report.l0_influenced_runs,
            u32::from(treatment_influenced_l0)
        );
        assert_eq!(paired.seed, 42);
        assert_eq!(
            paired.delta_mean_reward,
            paired.treatment.mean_reward - paired.baseline.mean_reward
        );
        assert_eq!(
            paired.delta_best_arm_rate,
            paired.treatment.best_arm_rate - paired.baseline.best_arm_rate
        );
        assert_eq!(paired.treatment_influenced_l0, treatment_influenced_l0);
        for metrics in &paired.treatment.expert_metrics {
            assert_eq!(metrics.committed, metrics.applied + metrics.not_applied);
            if metrics.applied == 0 {
                assert_eq!(metrics.reward_sum, 0.0);
            }
        }
        assert!(
            report.treatment_l2_enabled.mean_committed_policies_applied
                <= report.treatment_l2_enabled.mean_l2_commits
        );
    }

    #[test]
    fn closed_loop_comparison_shows_adaptation_over_baseline() {
        let report = run_closed_loop_comparison_benchmark(150);
        assert_eq!(report.rows.len(), 3);
        let baseline = &report.rows[0];
        let l1 = &report.rows[1];
        let guarded = &report.rows[2];
        assert!(l1.drift_mean_error < baseline.drift_mean_error);
        assert!(guarded.drift_mean_error < baseline.drift_mean_error);
        assert!(baseline.drift_recovery_steps.is_none());
        assert!(guarded.drift_recovery_steps.is_some());
    }
}