gam-models 0.3.151

Model families (GAMLSS, survival location-scale, BMS) for the gam penalized-likelihood engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
//! Single-source flex survival row NLL over a runtime-`K` jet algebra (#932,
//! doc §C/§D/Unifying).
//!
//! The flex marginal-slope row negative log-likelihood is
//! ```text
//! ℓ = w·[ logΦ(−η₀) − (1−d)·logΦ(−η₁)
//!         + d·½η₁² − d·logχ₁ + d·½q₁² + d·logD₁ − d·logqd₁ + d·ln2π ]
//! ```
//! (`flex_sensitivity.rs:105`). [`flex_row_nll`] writes this **once** over a
//! generic [`FlexJet`] scalar; instantiating it at [`Jet2`] yields value /
//! gradient / Hessian, at [`Jet3`] yields the contracted third `D_dir H[u,v]`,
//! and at [`Jet4`] the contracted fourth. The directional / bidirectional
//! contraction "directions" fall out of the nilpotent ε / δ seeds of the timepoint
//! jets, exactly as the packed `Order2`/`OneSeed`/`TwoSeed` scalars do for
//! location-scale — but here over a **runtime** primary count `p` (the flex
//! primary count `4 + |h| + |w| + 1` is large and variable, so a `Vec`-backed
//! jet avoids the const-generic monomorphization blow-up the packed scalars would
//! incur).
//!
//! The timepoint quantities `η₀, η₁, χ₁, D₁` are produced **by the jet path
//! itself** in production: [`flex_timepoint_inputs_generic`] builds them from the
//! per-cell coefficient θ-jets and the moving-edge / moment recurrence, seeded at
//! `Jet2` (value/grad/Hess), `Jet3` (+directional) or `Jet4` (+bidirectional).
//! `q₁`/`qd₁` are seeded as plain primaries. The single-source probit derivative
//! stack `surv_stack` and the `ln` stack carry the only special functions (humans
//! own primitive stability, the algebra owns combinatorics).
//!
//! Verification is deliberately independent of the production composition:
//!
//! - scalar finite differences re-solve the real moving-boundary intercept;
//! - `Dual22` checks fourth order through a distinct 2+2 nesting;
//! - the compiled order-two lowering is pinned to the generic plan;
//! - rigid zero-deviation rows are pinned to the independent `Tower4` program.
//!
//! The Euler projector in [`MomentTerm::moment_term`] supplies the universal
//! `j/(j+m)` distinguished-derivative weight, and [`lift_intercept_flex`] runs
//! enough frozen-inverse iterations for the represented jet order. Those two
//! rules are shared by every timepoint channel.
//!

use super::*;
use crate::bms::signed_probit_neglog_unary_stack;
use crate::survival::marginal_slope::timewiggle_geometry::{
    TimewiggleBasisDerivativeRows, TimewiggleQBaseValues, timewiggle_q_from_basis_derivative_rows,
};
use gam_math::jet_scalar::{
    DynamicJetArena, DynamicOneSeed, DynamicOrder2, DynamicOrder2Accumulator, DynamicOrder2Term,
    OneSeed, Order2, RuntimeJetScalar,
};
use gam_math::jet_tower::Tower2;

/// Canonical value/gradient/Hessian timepoint channels consumed by the
/// contracted row expression.
#[derive(Clone, Debug)]
pub(crate) struct FlexTimepointBasePack {
    pub(crate) eta: f64,
    pub(crate) chi: f64,
    pub(crate) d: f64,
    pub(crate) eta_u: Vec<f64>,
    pub(crate) eta_uv: Vec<f64>,
    pub(crate) chi_u: Vec<f64>,
    pub(crate) chi_uv: Vec<f64>,
    pub(crate) d_u: Vec<f64>,
    pub(crate) d_uv: Vec<f64>,
}

/// Single-direction extension of the canonical timepoint channels.
#[derive(Clone, Debug)]
pub(crate) struct FlexTimepointDirectionalPack {
    pub(crate) eta_uv_dir: Vec<f64>,
    pub(crate) eta_u_dir: Vec<f64>,
    pub(crate) chi_u_dir: Vec<f64>,
    pub(crate) chi_uv_dir: Vec<f64>,
    pub(crate) d_u_dir: Vec<f64>,
    pub(crate) d_uv_dir: Vec<f64>,
}

/// Mixed second-direction extension of the canonical timepoint channels.
#[derive(Clone, Debug)]
pub(crate) struct FlexTimepointBidirectionalPack {
    pub(crate) eta_uv_uv: Vec<f64>,
    pub(crate) chi_uv_uv: Vec<f64>,
    pub(crate) d_uv_uv: Vec<f64>,
}

/// Motion of every family-owned scalar entering one FLEX row along one outer
/// direction.
///
/// The offset entries are deliberately not derivatives of the final
/// `(q0, q1, qd1)` coordinates: when time wiggle is active, the generic q-map
/// owns that nonlinear composition. `probit_scale` is motion of the physical
/// multiplicative probit scale (not log-sigma); a baseline direction sets it to
/// zero, while a learned-scale direction supplies the exact analytic scale
/// derivative stack. This carrier therefore serves baseline, scale, and their
/// combined/polarized directions without another row formula.
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct FlexFamilyRowDirection {
    pub(crate) entry: f64,
    pub(crate) exit: f64,
    pub(crate) derivative_exit: f64,
    pub(crate) probit_scale: f64,
}

/// One family derivative channel of a complete FLEX row in flattened
/// coefficient coordinates.
#[derive(Clone, Debug)]
pub(crate) struct FlexFamilyCoefficientTerms {
    pub(crate) objective: f64,
    pub(crate) gradient: Array1<f64>,
    pub(crate) hessian: Array2<f64>,
}

/// Exact first and same-direction second family derivatives of a complete FLEX
/// row, plus an optional coefficient-map drift of the first channel.
#[derive(Clone, Debug)]
pub(crate) struct FlexFamilyDirectionRowTerms {
    pub(crate) first: FlexFamilyCoefficientTerms,
    pub(crate) second: FlexFamilyCoefficientTerms,
    pub(crate) directional: Option<FlexFamilyCoefficientTerms>,
}

pub(crate) fn pack_flex_timepoint_base(base: &SurvivalFlexTimepointExact) -> FlexTimepointBasePack {
    FlexTimepointBasePack {
        eta: base.eta,
        chi: base.chi,
        d: base.d,
        eta_u: base.eta_u.to_vec(),
        eta_uv: base.eta_uv.iter().copied().collect(),
        chi_u: base.chi_u.to_vec(),
        chi_uv: base.chi_uv.iter().copied().collect(),
        d_u: base.d_u.to_vec(),
        d_uv: base.d_uv.iter().copied().collect(),
    }
}

thread_local! {
    /// Per-worker FLEX directional workspace. The largest row tape is retained
    /// across contractions, so warmed production calls do not revisit the
    /// global allocator for runtime-sized derivative channels.
    static FLEX_THIRD_JET_ARENA: std::cell::RefCell<DynamicJetArena> =
        std::cell::RefCell::new(DynamicJetArena::new());
}

pub(crate) fn with_flex_third_jet_arena<R>(evaluate: impl FnOnce(&mut DynamicJetArena) -> R) -> R {
    FLEX_THIRD_JET_ARENA.with(|workspace| {
        let mut arena = workspace.borrow_mut();
        arena.reset();
        let result = evaluate(&mut arena);
        arena.reset();
        result
    })
}

/// The `[f64; 5]` Faà di Bruno stack of `g(η) = logΦ(−η)` at `η`.
///
/// With `N(m) = −logΦ(m)` and `(k1,k2,k3,k4) = N′…N⁗(m)` at `m = −η`
/// (`signed_probit_neglog_derivatives_up_to_fourth`), the chain rule on
/// `g(η) = −N(−η)` gives `g′ = k1`, `g″ = −k2`, `g‴ = k3`, `g⁗ = −k4`. This is
/// the entry/exit survival stack; composing the timepoint η-jet with it
/// supplies the canonical entry/exit survival derivatives consumed by every
/// generated flex-row lowering.
#[inline]
fn surv_stack(eta: f64) -> Result<[f64; 5], String> {
    let signed_margin = -eta;
    if signed_margin != f64::INFINITY && !signed_margin.is_finite() {
        return Err(format!(
            "non-finite signed margin in exact probit derivative helper: {signed_margin}"
        ));
    }
    // `weight = -1` makes the fused BMS primitive return the derivative stack
    // of `logΦ(m)` from ONE Mills-ratio evaluation. Compose with `m = -η` by
    // flipping odd derivative orders. This replaces the old two-call sequence
    // (one `logcdf`, then another `logcdf` discarded by the derivative helper).
    let m_stack = signed_probit_neglog_unary_stack(signed_margin, -1.0);
    Ok([m_stack[0], -m_stack[1], m_stack[2], -m_stack[3], m_stack[4]])
}

/// The `[f64; 5]` Faà di Bruno stack of `ln(x)`.
#[inline]
fn ln_stack(x: f64) -> [f64; 5] {
    let inv = 1.0 / x;
    let inv2 = inv * inv;
    [x.ln(), inv, -inv2, 2.0 * inv2 * inv, -6.0 * inv2 * inv2]
}

/// A runtime-`K` truncated-Taylor scalar: the row loss is written once against
/// this interface and re-instantiated at [`Jet1`] / [`Jet2`] / [`Jet3`] /
/// [`Jet4`] for gradient-only, value/grad/Hessian, contracted-third, and
/// contracted-fourth channels.
/// The runtime-`p` (Vec-backed) INNER timepoint-geometry jet layer. It EXTENDS
/// the shared [`JetField`] scalar-field algebra (value / add / sub / mul / neg /
/// scale / the single Faà di Bruno `compose_unary`) with only the one thing the
/// flex geometry adds on top: the truncation order [`FlexJet::ORDER`]. The
/// const-`K` packed row seam (`JetScalar`) extends the SAME `JetField` base — but
/// the two program layers stay distinct: `FlexJet` is runtime-`p`, not const-`K`.
trait FlexJet: JetField + Clone {
    /// Highest derivative order represented by this nilpotent algebra.
    /// A value-zero perturbation raised to `ORDER + 1` is identically zero, so
    /// generic Taylor-polynomial builders must stop at this exact order.
    const ORDER: usize;

    /// Scale every derivative channel by its total homogeneous order. Entry
    /// `factors[r]` applies to channels carrying exactly `r` derivatives.
    /// This is the representation-independent Euler-operator seam used by the
    /// distinguished calibration projector.
    fn scale_homogeneous_orders(&self, factors: [f64; 5]) -> Self;
}

impl FlexJet for f64 {
    const ORDER: usize = 0;

    #[inline]
    fn scale_homogeneous_orders(&self, factors: [f64; 5]) -> Self {
        factors[0] * self
    }
}

/// Lift any flex scalar through one independent second-order family direction.
///
/// A channel in `v`, `g`, or `h` carries respectively zero, one, or two outer
/// derivatives in addition to its inner homogeneous order. Shifting the Euler
/// factors by that outer order is essential: applying the unshifted factors to
/// all three fields would silently mis-scale calibration's distinguished
/// family derivative. Channels above the row program's certified total order
/// four are truncated explicitly.
impl<J: FlexJet> FlexJet for Dual2<J> {
    const ORDER: usize = if J::ORDER >= 2 { 4 } else { J::ORDER + 2 };

    #[inline]
    fn scale_homogeneous_orders(&self, factors: [f64; 5]) -> Self {
        let shifted = |outer_order: usize| {
            std::array::from_fn(|inner_order| {
                factors
                    .get(inner_order + outer_order)
                    .copied()
                    .unwrap_or(0.0)
            })
        };
        Self {
            v: self.v.scale_homogeneous_orders(shifted(0)),
            g: self.g.scale_homogeneous_orders(shifted(1)),
            h: self.h.scale_homogeneous_orders(shifted(2)),
        }
    }
}

const FLEX_OUTER_SOURCE_COUNT: usize = 6;
const FLEX_OUTER_TERM_COUNT: usize = 7;

/// The six independent inner scalars used by the seven-term flex row NLL.
/// `eta1` appears twice (survival and Gaussian-density terms), and the order-two
/// compiler fuses those two outer stacks before touching its derivative views.
#[derive(Clone, Copy)]
#[repr(usize)]
enum FlexOuterSource {
    Eta0 = 0,
    Eta1 = 1,
    Q1 = 2,
    Chi1 = 3,
    D1 = 4,
    Qd1 = 5,
}

impl FlexOuterSource {
    #[inline(always)]
    fn index(self) -> usize {
        self as usize
    }
}

#[derive(Clone, Copy)]
enum FlexOuterTransform {
    Compose([f64; 5]),
    Square,
}

#[derive(Clone, Copy)]
enum FlexOuterCombine {
    Add,
    Subtract,
}

/// One term of the flex row NLL. This term list is the sole mathematical
/// definition consumed by both the generic high-order jets and the compiled
/// allocation-minimal order-two lowering.
#[derive(Clone, Copy)]
struct FlexOuterTerm {
    source: FlexOuterSource,
    transform: FlexOuterTransform,
    scale: f64,
    combine: FlexOuterCombine,
}

impl FlexOuterTerm {
    #[inline(always)]
    fn evaluate<J: FlexJet>(&self, sources: &FlexJetSources<'_, J>) -> J {
        let source = sources.get(self.source);
        let transformed = match self.transform {
            FlexOuterTransform::Compose(stack) => source.compose_unary(stack),
            FlexOuterTransform::Square => source.mul(source),
        };
        transformed.scale(self.scale)
    }

    #[inline(always)]
    fn order2_channels(&self, source_value: f64) -> [f64; 3] {
        let mut channels = match self.transform {
            FlexOuterTransform::Compose(stack) => [stack[0], stack[1], stack[2]],
            FlexOuterTransform::Square => [
                source_value * source_value,
                source_value + source_value,
                2.0,
            ],
        };
        for channel in &mut channels {
            *channel *= self.scale;
        }
        channels
    }
}

struct FlexJetSources<'a, J> {
    eta0: &'a J,
    eta1: &'a J,
    q1: &'a J,
    chi1: &'a J,
    d1: &'a J,
    qd1: &'a J,
}

impl<'a, J> FlexJetSources<'a, J> {
    #[inline(always)]
    fn get(&self, source: FlexOuterSource) -> &'a J {
        match source {
            FlexOuterSource::Eta0 => self.eta0,
            FlexOuterSource::Eta1 => self.eta1,
            FlexOuterSource::Q1 => self.q1,
            FlexOuterSource::Chi1 => self.chi1,
            FlexOuterSource::D1 => self.d1,
            FlexOuterSource::Qd1 => self.qd1,
        }
    }
}

/// The single flex row-NLL source, excluding the additive `w·d·ln2π`
/// constant. The ordered seven-term plan preserves the generic evaluator's
/// historical arithmetic while exposing the same source/transform metadata to
/// the order-two compiler.
struct FlexOuterPlan {
    terms: [FlexOuterTerm; FLEX_OUTER_TERM_COUNT],
}

impl FlexOuterPlan {
    #[inline(always)]
    fn new(
        chi1: f64,
        d1: f64,
        qd1: f64,
        surv0: [f64; 5],
        surv1: [f64; 5],
        wi: f64,
        di: f64,
    ) -> Self {
        let wd = wi * di;
        Self {
            terms: [
                FlexOuterTerm {
                    source: FlexOuterSource::Eta0,
                    transform: FlexOuterTransform::Compose(surv0),
                    scale: wi,
                    combine: FlexOuterCombine::Add,
                },
                FlexOuterTerm {
                    source: FlexOuterSource::Eta1,
                    transform: FlexOuterTransform::Compose(surv1),
                    scale: -wi * (1.0 - di),
                    combine: FlexOuterCombine::Add,
                },
                FlexOuterTerm {
                    source: FlexOuterSource::Eta1,
                    transform: FlexOuterTransform::Square,
                    scale: 0.5 * wd,
                    combine: FlexOuterCombine::Add,
                },
                FlexOuterTerm {
                    source: FlexOuterSource::Q1,
                    transform: FlexOuterTransform::Square,
                    scale: 0.5 * wd,
                    combine: FlexOuterCombine::Add,
                },
                FlexOuterTerm {
                    source: FlexOuterSource::Chi1,
                    transform: FlexOuterTransform::Compose(ln_stack(chi1)),
                    scale: wd,
                    combine: FlexOuterCombine::Subtract,
                },
                FlexOuterTerm {
                    source: FlexOuterSource::D1,
                    transform: FlexOuterTransform::Compose(ln_stack(d1)),
                    scale: wd,
                    combine: FlexOuterCombine::Add,
                },
                FlexOuterTerm {
                    source: FlexOuterSource::Qd1,
                    transform: FlexOuterTransform::Compose(ln_stack(qd1)),
                    scale: wd,
                    combine: FlexOuterCombine::Subtract,
                },
            ],
        }
    }

    #[inline(always)]
    fn evaluate<J: FlexJet>(&self, sources: &FlexJetSources<'_, J>) -> J {
        let mut output = self.terms[0].evaluate(sources);
        for term in &self.terms[1..] {
            let contribution = term.evaluate(sources);
            output = match term.combine {
                FlexOuterCombine::Add => output.add(&contribution),
                FlexOuterCombine::Subtract => output.sub(&contribution),
            };
        }
        output
    }

    /// Compile the ordered term list to one value plus one `(f', f'')` pair per
    /// independent source. Terms sharing a source are fused before the
    /// runtime-width gradient/Hessian sweep.
    #[inline(always)]
    fn compile_order2(&self, source_values: [f64; FLEX_OUTER_SOURCE_COUNT]) -> FlexOrder2Plan {
        let mut value = 0.0;
        let mut derivatives = [[0.0; 2]; FLEX_OUTER_SOURCE_COUNT];
        for term in &self.terms {
            let channels = term.order2_channels(source_values[term.source.index()]);
            let sign = match term.combine {
                FlexOuterCombine::Add => 1.0,
                FlexOuterCombine::Subtract => -1.0,
            };
            value += sign * channels[0];
            derivatives[term.source.index()][0] += sign * channels[1];
            derivatives[term.source.index()][1] += sign * channels[2];
        }
        FlexOrder2Plan { value, derivatives }
    }
}

/// The single-source flex row NLL **minus** the additive `w·d·ln2π` constant
/// (which the caller adds to the value channel — it has no derivative). Written
/// once over `FlexJet`; the instantiating scalar selects the channel.
#[inline]
fn flex_row_nll<J: FlexJet>(
    eta0: &J,
    eta1: &J,
    chi1: &J,
    d1: &J,
    q1: &J,
    qd1: &J,
    surv0: [f64; 5],
    surv1: [f64; 5],
    wi: f64,
    di: f64,
) -> J {
    FlexOuterPlan::new(chi1.value(), d1.value(), qd1.value(), surv0, surv1, wi, di).evaluate(
        &FlexJetSources {
            eta0,
            eta1,
            q1,
            chi1,
            d1,
            qd1,
        },
    )
}

// ── Compiled two-allocation order-two lowering (value/grad/Hessian) ────────
//
// Instantiating the plan through the generic [`Jet2`] algebra would allocate
// roughly 18 intermediate vectors. Instead [`FlexOuterPlan::compile_order2`]
// fuses the ordered term list to six source coefficients and the universal
// [`DynamicOrder2Accumulator`] reads the ndarray channels in place. The only
// allocations are the two buffers returned to the caller. Both representations
// consume the same plan; there is no second likelihood formula to maintain.
struct FlexOrder2Plan {
    value: f64,
    derivatives: [[f64; 2]; FLEX_OUTER_SOURCE_COUNT],
}

struct FlexOrder2View<'a> {
    value: f64,
    gradient: ndarray::ArrayView1<'a, f64>,
    hessian: ndarray::ArrayView2<'a, f64>,
}

struct FlexOrder2Inputs<'a> {
    eta0: FlexOrder2View<'a>,
    eta1: FlexOrder2View<'a>,
    q1: (f64, usize),
    chi1: FlexOrder2View<'a>,
    d1: FlexOrder2View<'a>,
    qd1: (f64, usize),
}

enum FlexOrder2Term<'a> {
    Dense {
        outer: [f64; 2],
        gradient: ndarray::ArrayView1<'a, f64>,
        hessian: ndarray::ArrayView2<'a, f64>,
    },
    Axis {
        outer: [f64; 2],
        axis: usize,
    },
}

impl DynamicOrder2Term for FlexOrder2Term<'_> {
    #[inline(always)]
    fn outer_first(&self) -> f64 {
        match self {
            Self::Dense { outer, .. } | Self::Axis { outer, .. } => outer[0],
        }
    }

    #[inline(always)]
    fn outer_second(&self) -> f64 {
        match self {
            Self::Dense { outer, .. } | Self::Axis { outer, .. } => outer[1],
        }
    }

    #[inline(always)]
    fn inner_gradient(&self, axis: usize) -> f64 {
        match self {
            Self::Dense { gradient, .. } => gradient[axis],
            Self::Axis { axis: source, .. } => {
                if axis == *source {
                    1.0
                } else {
                    0.0
                }
            }
        }
    }

    #[inline(always)]
    fn inner_hessian(&self, row: usize, column: usize) -> f64 {
        match self {
            Self::Dense { hessian, .. } => hessian[[row, column]],
            Self::Axis { .. } => 0.0,
        }
    }
}

/// Allocation-minimal order-two lowering of the same [`FlexOuterPlan`] used by
/// the generic high-order jets. The plan fuses the two `eta1` terms into one
/// outer derivative pair; [`DynamicOrder2Accumulator`] then performs one fused
/// gradient pass and one fused Hessian pass into exactly two owned buffers.
#[inline]
fn lower_flex_outer_plan_order2(
    plan: &FlexOuterPlan,
    inputs: FlexOrder2Inputs<'_>,
    dimension: usize,
) -> (f64, Vec<f64>, Vec<f64>) {
    let source_values = [
        inputs.eta0.value,
        inputs.eta1.value,
        inputs.q1.0,
        inputs.chi1.value,
        inputs.d1.value,
        inputs.qd1.0,
    ];
    let compiled = plan.compile_order2(source_values);
    let terms = [
        FlexOrder2Term::Dense {
            outer: compiled.derivatives[FlexOuterSource::Eta0.index()],
            gradient: inputs.eta0.gradient,
            hessian: inputs.eta0.hessian,
        },
        FlexOrder2Term::Dense {
            outer: compiled.derivatives[FlexOuterSource::Eta1.index()],
            gradient: inputs.eta1.gradient,
            hessian: inputs.eta1.hessian,
        },
        FlexOrder2Term::Axis {
            outer: compiled.derivatives[FlexOuterSource::Q1.index()],
            axis: inputs.q1.1,
        },
        FlexOrder2Term::Dense {
            outer: compiled.derivatives[FlexOuterSource::Chi1.index()],
            gradient: inputs.chi1.gradient,
            hessian: inputs.chi1.hessian,
        },
        FlexOrder2Term::Dense {
            outer: compiled.derivatives[FlexOuterSource::D1.index()],
            gradient: inputs.d1.gradient,
            hessian: inputs.d1.hessian,
        },
        FlexOrder2Term::Axis {
            outer: compiled.derivatives[FlexOuterSource::Qd1.index()],
            axis: inputs.qd1.1,
        },
    ];
    DynamicOrder2Accumulator::from_composed_sum(dimension, compiled.value, &terms).into_channels()
}

// ── Jet2: value / gradient / Hessian (runtime K) ───────────────────────────

/// Value `v`, gradient `g[i]`, Hessian `h[i*p+j]` (row-major, symmetric) over a
/// runtime primary count `p = g.len()`. The order-≤2 truncation of the Leibniz /
/// Faà di Bruno rules — bit-identical to [`super::super::super::jet_tower::Tower2`]
/// channel-for-channel, just `Vec`-backed.
#[derive(Clone)]
struct Jet2 {
    v: f64,
    g: Vec<f64>,
    h: Vec<f64>,
}

impl Jet2 {
    /// A jet from explicit channels: `g` length `p`, `h` length `p*p` (or empty
    /// for the grad-only path, treated as the zero Hessian).
    fn from_parts(v: f64, g: &[f64], h: &[f64]) -> Self {
        let p = g.len();
        let hv = if h.is_empty() {
            vec![0.0; p * p]
        } else {
            assert_eq!(h.len(), p * p, "Jet2::from_parts Hessian length");
            h.to_vec()
        };
        Jet2 {
            v,
            g: g.to_vec(),
            h: hv,
        }
    }

    /// The seeded primary `p_axis` at value `x`: unit gradient in slot `axis`,
    /// zero Hessian.
    fn primary(x: f64, axis: usize, p: usize) -> Self {
        let mut g = vec![0.0; p];
        if axis < p {
            g[axis] = 1.0;
        }
        Jet2 {
            v: x,
            g,
            h: vec![0.0; p * p],
        }
    }

    #[inline]
    fn p(&self) -> usize {
        self.g.len()
    }

    #[inline]
    fn scale_homogeneous_from(&self, offset: usize, factors: [f64; 5]) -> Self {
        assert!(offset + 2 < factors.len());
        Jet2 {
            v: factors[offset] * self.v,
            g: self
                .g
                .iter()
                .map(|&channel| factors[offset + 1] * channel)
                .collect(),
            h: self
                .h
                .iter()
                .map(|&channel| factors[offset + 2] * channel)
                .collect(),
        }
    }
}

impl JetField for Jet2 {
    #[inline]
    fn value(&self) -> f64 {
        self.v
    }
    fn add(&self, o: &Self) -> Self {
        let p = self.p();
        let mut g = vec![0.0; p];
        let mut h = vec![0.0; p * p];
        for i in 0..p {
            g[i] = self.g[i] + o.g[i];
        }
        for k in 0..p * p {
            h[k] = self.h[k] + o.h[k];
        }
        Jet2 {
            v: self.v + o.v,
            g,
            h,
        }
    }
    fn sub(&self, o: &Self) -> Self {
        let p = self.p();
        let mut g = vec![0.0; p];
        let mut h = vec![0.0; p * p];
        for i in 0..p {
            g[i] = self.g[i] - o.g[i];
        }
        for k in 0..p * p {
            h[k] = self.h[k] - o.h[k];
        }
        Jet2 {
            v: self.v - o.v,
            g,
            h,
        }
    }
    fn mul(&self, o: &Self) -> Self {
        let p = self.p();
        let mut g = vec![0.0; p];
        let mut h = vec![0.0; p * p];
        for i in 0..p {
            g[i] = self.v * o.g[i] + self.g[i] * o.v;
        }
        for i in 0..p {
            for j in 0..p {
                h[i * p + j] = self.v * o.h[i * p + j]
                    + self.g[i] * o.g[j]
                    + self.g[j] * o.g[i]
                    + self.h[i * p + j] * o.v;
            }
        }
        Jet2 {
            v: self.v * o.v,
            g,
            h,
        }
    }
    fn scale(&self, s: f64) -> Self {
        Jet2 {
            v: self.v * s,
            g: self.g.iter().map(|&x| x * s).collect(),
            h: self.h.iter().map(|&x| x * s).collect(),
        }
    }
    #[inline]
    fn neg(&self) -> Self {
        self.scale(-1.0)
    }
    fn compose_unary(&self, d: [f64; 5]) -> Self {
        // Order-≤2 reads only [f, f', f''].
        let p = self.p();
        let (f, f1, f2) = (d[0], d[1], d[2]);
        let mut g = vec![0.0; p];
        let mut h = vec![0.0; p * p];
        for i in 0..p {
            g[i] = f1 * self.g[i];
        }
        for i in 0..p {
            for j in 0..p {
                h[i * p + j] = f2 * self.g[i] * self.g[j] + f1 * self.h[i * p + j];
            }
        }
        Jet2 { v: f, g, h }
    }
}

impl FlexJet for Jet2 {
    const ORDER: usize = 2;

    #[inline]
    fn scale_homogeneous_orders(&self, factors: [f64; 5]) -> Self {
        self.scale_homogeneous_from(0, factors)
    }
}

// ── Jet1: value + gradient only (grad-only path, no discarded Hessian) ──────

/// The order-≤1 truncation of the same Leibniz / Faà di Bruno rules `Jet2`
/// realises — value + gradient, **no Hessian channel**. The value and gradient
/// arithmetic of `Jet2` never reads its own `h` channel (`v`/`g` depend only on
/// `v`/`g`), so instantiating [`flex_row_nll`] at `Jet1` yields the value and
/// gradient `f64::to_bits`-identical to the `Jet2` path while eliminating the
/// entire `O(p²)` Hessian allocation + arithmetic. Used by the grad-only
/// production caller (`flex_sensitivity.rs`, `want_hess == false`), which builds
/// and then discards a full `p×p` Hessian under `Jet2`.
#[derive(Clone)]
struct Jet1 {
    v: f64,
    g: Vec<f64>,
}

impl Jet1 {
    /// A jet from a value + gradient view (the grad-only timepoint packs carry no
    /// `*_uv`, so only the value/gradient channels are ever supplied).
    fn from_view(v: f64, g: ndarray::ArrayView1<'_, f64>) -> Self {
        Jet1 {
            v,
            g: g.iter().copied().collect(),
        }
    }

    /// The seeded primary `p_axis` at value `x`: unit gradient in slot `axis`.
    fn primary(x: f64, axis: usize, p: usize) -> Self {
        let mut g = vec![0.0; p];
        if axis < p {
            g[axis] = 1.0;
        }
        Jet1 { v: x, g }
    }

    #[inline]
    fn p(&self) -> usize {
        self.g.len()
    }
}

impl JetField for Jet1 {
    #[inline]
    fn value(&self) -> f64 {
        self.v
    }
    fn add(&self, o: &Self) -> Self {
        let p = self.p();
        let mut g = vec![0.0; p];
        for i in 0..p {
            g[i] = self.g[i] + o.g[i];
        }
        Jet1 { v: self.v + o.v, g }
    }
    fn sub(&self, o: &Self) -> Self {
        let p = self.p();
        let mut g = vec![0.0; p];
        for i in 0..p {
            g[i] = self.g[i] - o.g[i];
        }
        Jet1 { v: self.v - o.v, g }
    }
    fn mul(&self, o: &Self) -> Self {
        let p = self.p();
        let mut g = vec![0.0; p];
        for i in 0..p {
            g[i] = self.v * o.g[i] + self.g[i] * o.v;
        }
        Jet1 { v: self.v * o.v, g }
    }
    fn scale(&self, s: f64) -> Self {
        Jet1 {
            v: self.v * s,
            g: self.g.iter().map(|&x| x * s).collect(),
        }
    }
    #[inline]
    fn neg(&self) -> Self {
        self.scale(-1.0)
    }
    fn compose_unary(&self, d: [f64; 5]) -> Self {
        // Order-≤1 reads only [f, f'].
        let p = self.p();
        let (f, f1) = (d[0], d[1]);
        let mut g = vec![0.0; p];
        for i in 0..p {
            g[i] = f1 * self.g[i];
        }
        Jet1 { v: f, g }
    }
}

impl FlexJet for Jet1 {
    const ORDER: usize = 1;

    #[inline]
    fn scale_homogeneous_orders(&self, factors: [f64; 5]) -> Self {
        Jet1 {
            v: factors[0] * self.v,
            g: self.g.iter().map(|&channel| factors[1] * channel).collect(),
        }
    }
}

// ── Jet3: one-seed directional, contracted third (doc §A.2) ────────────────

/// An [`Jet2`] base plus one nilpotent ε (`ε² = 0`) holding another [`Jet2`].
/// After seeding the timepoint jets' ε-parts with their directional derivatives,
/// the ε-Hessian of the evaluated NLL is `Σ_c ℓ_{abc} dir_c = (D_dir H)[a][b]`.
#[derive(Clone)]
struct Jet3 {
    base: Jet2,
    eps: Jet2,
}

impl Jet3 {
    /// Seeded primary: base = `primary(x, axis)`, ε = constant `dir[axis]`.
    fn primary(x: f64, axis: usize, p: usize, dir_axis: f64) -> Self {
        Jet3 {
            base: Jet2::primary(x, axis, p),
            eps: Jet2::from_parts(dir_axis, &vec![0.0; p], &[]),
        }
    }
    /// The contracted-third channel `Σ_c ℓ_{abc} dir_c` (the ε-Hessian).
    fn contracted_third(&self) -> Vec<f64> {
        self.eps.h.clone()
    }
}

impl JetField for Jet3 {
    #[inline]
    fn value(&self) -> f64 {
        self.base.v
    }
    fn add(&self, o: &Self) -> Self {
        Jet3 {
            base: self.base.add(&o.base),
            eps: self.eps.add(&o.eps),
        }
    }
    fn sub(&self, o: &Self) -> Self {
        Jet3 {
            base: self.base.sub(&o.base),
            eps: self.eps.sub(&o.eps),
        }
    }
    fn mul(&self, o: &Self) -> Self {
        Jet3 {
            base: self.base.mul(&o.base),
            eps: self.base.mul(&o.eps).add(&self.eps.mul(&o.base)),
        }
    }
    fn scale(&self, s: f64) -> Self {
        Jet3 {
            base: self.base.scale(s),
            eps: self.eps.scale(s),
        }
    }
    #[inline]
    fn neg(&self) -> Self {
        self.scale(-1.0)
    }
    fn compose_unary(&self, d: [f64; 5]) -> Self {
        let base = self.base.compose_unary([d[0], d[1], d[2], d[3], d[4]]);
        // f'(base) as a Jet2 (consumes [f', f'', f''']).
        let fprime = self.base.compose_unary([d[1], d[2], d[3], d[4], d[4]]);
        let eps = fprime.mul(&self.eps);
        Jet3 { base, eps }
    }
}

impl FlexJet for Jet3 {
    const ORDER: usize = 3;

    #[inline]
    fn scale_homogeneous_orders(&self, factors: [f64; 5]) -> Self {
        Jet3 {
            base: self.base.scale_homogeneous_from(0, factors),
            eps: self.eps.scale_homogeneous_from(1, factors),
        }
    }
}

/// Inner coefficient algebra used by the baseline-family row evaluator.
///
/// `Jet2` owns the coefficient value/score/Hessian channels. `Jet3` adds one
/// nilpotent coefficient direction whose epsilon part is the exact directional
/// drift of those same channels. The outer family coordinate is supplied by
/// `Dual2<J>` and is intentionally absent from this constructor.
trait FlexCoefficientJet: FlexJet {
    fn affine(
        value: f64,
        gradient: Vec<f64>,
        directional_value: f64,
        directional_gradient: Vec<f64>,
    ) -> Self;

    fn constant(value: f64, dimension: usize) -> Self {
        Self::affine(value, vec![0.0; dimension], 0.0, vec![0.0; dimension])
    }

    fn owned_base_terms(&self) -> FlexFamilyCoefficientTerms;

    fn owned_directional_terms(&self) -> Option<FlexFamilyCoefficientTerms>;
}

fn owned_jet2_terms(jet: &Jet2) -> FlexFamilyCoefficientTerms {
    let dimension = jet.g.len();
    FlexFamilyCoefficientTerms {
        objective: jet.v,
        gradient: Array1::from_vec(jet.g.clone()),
        hessian: Array2::from_shape_vec((dimension, dimension), jet.h.clone())
            .expect("Jet2 coefficient Hessian shape invariant"),
    }
}

impl FlexCoefficientJet for Jet2 {
    fn affine(
        value: f64,
        gradient: Vec<f64>,
        directional_value: f64,
        directional_gradient: Vec<f64>,
    ) -> Self {
        assert!(
            directional_value == 0.0 && directional_gradient.iter().all(|value| *value == 0.0),
            "Jet2 cannot erase a coefficient-direction seed; use Jet3"
        );
        Self::from_parts(value, &gradient, &[])
    }

    fn owned_base_terms(&self) -> FlexFamilyCoefficientTerms {
        owned_jet2_terms(self)
    }

    fn owned_directional_terms(&self) -> Option<FlexFamilyCoefficientTerms> {
        None
    }
}

impl FlexCoefficientJet for Jet3 {
    fn affine(
        value: f64,
        gradient: Vec<f64>,
        directional_value: f64,
        directional_gradient: Vec<f64>,
    ) -> Self {
        Self {
            base: Jet2::from_parts(value, &gradient, &[]),
            eps: Jet2::from_parts(directional_value, &directional_gradient, &[]),
        }
    }

    fn owned_base_terms(&self) -> FlexFamilyCoefficientTerms {
        owned_jet2_terms(&self.base)
    }

    fn owned_directional_terms(&self) -> Option<FlexFamilyCoefficientTerms> {
        Some(owned_jet2_terms(&self.eps))
    }
}

/// Arena-backed one-seed scalar for the production directional timepoint
/// program. It implements the same [`FlexJet`] algebra as [`Jet3`], while every
/// derivative channel is allocated from one resettable row arena instead of a
/// fresh `Vec` per primitive operation.
#[derive(Clone, Copy)]
struct ArenaJet3<'arena> {
    arena: &'arena DynamicJetArena,
    inner: DynamicOneSeed<'arena>,
}

impl<'arena> ArenaJet3<'arena> {
    #[inline]
    fn primary(
        x: f64,
        axis: usize,
        p: usize,
        direction: f64,
        arena: &'arena DynamicJetArena,
    ) -> Self {
        let inner = if axis < p {
            DynamicOneSeed::seed_direction(x, axis, direction, p, arena)
        } else {
            DynamicOneSeed {
                base: DynamicOrder2::constant(x, p, arena),
                eps: DynamicOrder2::constant(direction, p, arena),
            }
        };
        Self { arena, inner }
    }
}

impl JetField for ArenaJet3<'_> {
    #[inline(always)]
    fn value(&self) -> f64 {
        self.inner.value()
    }

    #[inline(always)]
    fn add(&self, other: &Self) -> Self {
        Self {
            arena: self.arena,
            inner: self.inner.add(&other.inner),
        }
    }

    #[inline(always)]
    fn sub(&self, other: &Self) -> Self {
        Self {
            arena: self.arena,
            inner: self.inner.sub(&other.inner),
        }
    }

    #[inline(always)]
    fn mul(&self, other: &Self) -> Self {
        Self {
            arena: self.arena,
            inner: self.inner.mul(&other.inner),
        }
    }

    #[inline(always)]
    fn neg(&self) -> Self {
        Self {
            arena: self.arena,
            inner: self.inner.neg(),
        }
    }

    #[inline(always)]
    fn scale(&self, scale: f64) -> Self {
        Self {
            arena: self.arena,
            inner: self.inner.scale(scale),
        }
    }

    #[inline(always)]
    fn compose_unary(&self, derivatives: [f64; 5]) -> Self {
        Self {
            arena: self.arena,
            inner: self.inner.compose_unary(derivatives),
        }
    }
}

impl FlexJet for ArenaJet3<'_> {
    const ORDER: usize = 3;

    #[inline]
    fn scale_homogeneous_orders(&self, factors: [f64; 5]) -> Self {
        let dimension = self.inner.base.g.len();
        let scale_order2 = |channels: &DynamicOrder2<'_>, offset: usize| {
            DynamicOrder2::from_channel_functions(
                factors[offset] * channels.v,
                dimension,
                self.arena,
                |axis| factors[offset + 1] * channels.g[axis],
                |row, column| factors[offset + 2] * channels.h[row * dimension + column],
            )
        };
        Self {
            arena: self.arena,
            inner: DynamicOneSeed {
                base: scale_order2(&self.inner.base, 0),
                eps: scale_order2(&self.inner.eps, 1),
            },
        }
    }
}

/// Inline fixed-width one-seed scalar for the common eight-primary FLEX row.
/// It instantiates the same generic timepoint program as [`ArenaJet3`], but the
/// compiler can scalarize every value/gradient/Hessian channel and eliminate
/// runtime-width indexing and arena traffic.
#[derive(Clone, Copy)]
struct FixedJet3<const K: usize> {
    inner: OneSeed<K>,
}

impl<const K: usize> FixedJet3<K> {
    #[inline]
    fn primary(x: f64, axis: usize, p: usize, direction: f64) -> Self {
        assert_eq!(p, K, "fixed FLEX Jet3 width mismatch");
        let inner = if axis < K {
            OneSeed::seed_direction(x, axis, direction)
        } else {
            OneSeed {
                base: <Order2<K> as gam_math::jet_scalar::JetScalar<K>>::constant(x),
                eps: <Order2<K> as gam_math::jet_scalar::JetScalar<K>>::constant(direction),
            }
        };
        Self { inner }
    }
}

impl<const K: usize> JetField for FixedJet3<K> {
    #[inline(always)]
    fn value(&self) -> f64 {
        self.inner.value()
    }

    #[inline(always)]
    fn add(&self, other: &Self) -> Self {
        Self {
            inner: self.inner.add(&other.inner),
        }
    }

    #[inline(always)]
    fn sub(&self, other: &Self) -> Self {
        Self {
            inner: self.inner.sub(&other.inner),
        }
    }

    #[inline(always)]
    fn mul(&self, other: &Self) -> Self {
        Self {
            inner: self.inner.mul(&other.inner),
        }
    }

    #[inline(always)]
    fn neg(&self) -> Self {
        Self {
            inner: self.inner.neg(),
        }
    }

    #[inline(always)]
    fn scale(&self, scale: f64) -> Self {
        Self {
            inner: self.inner.scale(scale),
        }
    }

    #[inline(always)]
    fn compose_unary(&self, derivatives: [f64; 5]) -> Self {
        Self {
            inner: self.inner.compose_unary(derivatives),
        }
    }
}

impl<const K: usize> FlexJet for FixedJet3<K> {
    const ORDER: usize = 3;

    #[inline]
    fn scale_homogeneous_orders(&self, factors: [f64; 5]) -> Self {
        let scale_order2 = |channels: &Order2<K>, offset: usize| {
            let mut scaled = Tower2::<K>::zero();
            scaled.v = factors[offset] * channels.0.v;
            for axis in 0..K {
                scaled.g[axis] = factors[offset + 1] * channels.0.g[axis];
            }
            for row in 0..K {
                for column in 0..K {
                    scaled.h[row][column] = factors[offset + 2] * channels.0.h[row][column];
                }
            }
            Order2(scaled)
        };
        Self {
            inner: OneSeed {
                base: scale_order2(&self.inner.base, 0),
                eps: scale_order2(&self.inner.eps, 1),
            },
        }
    }
}

trait FlexThirdOutput: FlexJet + MomentTerm {
    fn pack_timepoint_outputs(
        eta: &Self,
        chi: &Self,
        d: &Self,
    ) -> (FlexTimepointBasePack, FlexTimepointDirectionalPack);
}

impl FlexThirdOutput for ArenaJet3<'_> {
    fn pack_timepoint_outputs(
        eta: &Self,
        chi: &Self,
        d: &Self,
    ) -> (FlexTimepointBasePack, FlexTimepointDirectionalPack) {
        (
            FlexTimepointBasePack {
                eta: eta.inner.base.v,
                chi: chi.inner.base.v,
                d: d.inner.base.v,
                eta_u: eta.inner.base.g.to_vec(),
                eta_uv: eta.inner.base.h.to_vec(),
                chi_u: chi.inner.base.g.to_vec(),
                chi_uv: chi.inner.base.h.to_vec(),
                d_u: d.inner.base.g.to_vec(),
                d_uv: d.inner.base.h.to_vec(),
            },
            FlexTimepointDirectionalPack {
                eta_u_dir: eta.inner.eps.g.to_vec(),
                eta_uv_dir: eta.inner.eps.h.to_vec(),
                chi_u_dir: chi.inner.eps.g.to_vec(),
                chi_uv_dir: chi.inner.eps.h.to_vec(),
                d_u_dir: d.inner.eps.g.to_vec(),
                d_uv_dir: d.inner.eps.h.to_vec(),
            },
        )
    }
}

impl<const K: usize> FlexThirdOutput for FixedJet3<K> {
    fn pack_timepoint_outputs(
        eta: &Self,
        chi: &Self,
        d: &Self,
    ) -> (FlexTimepointBasePack, FlexTimepointDirectionalPack) {
        let flatten =
            |matrix: &[[f64; K]; K]| matrix.iter().flat_map(|row| row.iter().copied()).collect();
        (
            FlexTimepointBasePack {
                eta: eta.inner.base.0.v,
                chi: chi.inner.base.0.v,
                d: d.inner.base.0.v,
                eta_u: eta.inner.base.0.g.to_vec(),
                eta_uv: flatten(&eta.inner.base.0.h),
                chi_u: chi.inner.base.0.g.to_vec(),
                chi_uv: flatten(&chi.inner.base.0.h),
                d_u: d.inner.base.0.g.to_vec(),
                d_uv: flatten(&d.inner.base.0.h),
            },
            FlexTimepointDirectionalPack {
                eta_u_dir: eta.inner.eps.0.g.to_vec(),
                eta_uv_dir: flatten(&eta.inner.eps.0.h),
                chi_u_dir: chi.inner.eps.0.g.to_vec(),
                chi_uv_dir: flatten(&chi.inner.eps.0.h),
                d_u_dir: d.inner.eps.0.g.to_vec(),
                d_uv_dir: flatten(&d.inner.eps.0.h),
            },
        )
    }
}

// ── Jet4: two-seed, contracted fourth (doc §A.3) ───────────────────────────

/// An [`Jet2`] base plus ε, δ (`ε² = δ² = 0`, `εδ` retained) — four [`Jet2`]
/// parts. After seeding with both directions, the εδ-Hessian of the NLL is
/// `Σ_{cd} ℓ_{abcd} u_c v_d`.
#[derive(Clone)]
struct Jet4 {
    base: Jet2,
    eps: Jet2,
    del: Jet2,
    eps_del: Jet2,
}

impl Jet4 {
    fn primary(x: f64, axis: usize, p: usize, du: f64, dv: f64) -> Self {
        let zero = vec![0.0; p];
        Jet4 {
            base: Jet2::primary(x, axis, p),
            eps: Jet2::from_parts(du, &zero, &[]),
            del: Jet2::from_parts(dv, &zero, &[]),
            eps_del: Jet2::from_parts(0.0, &zero, &[]),
        }
    }
    fn contracted_fourth(&self) -> Vec<f64> {
        self.eps_del.h.clone()
    }
}

impl JetField for Jet4 {
    #[inline]
    fn value(&self) -> f64 {
        self.base.v
    }
    fn add(&self, o: &Self) -> Self {
        Jet4 {
            base: self.base.add(&o.base),
            eps: self.eps.add(&o.eps),
            del: self.del.add(&o.del),
            eps_del: self.eps_del.add(&o.eps_del),
        }
    }
    fn sub(&self, o: &Self) -> Self {
        Jet4 {
            base: self.base.sub(&o.base),
            eps: self.eps.sub(&o.eps),
            del: self.del.sub(&o.del),
            eps_del: self.eps_del.sub(&o.eps_del),
        }
    }
    fn mul(&self, o: &Self) -> Self {
        let base = self.base.mul(&o.base);
        let eps = self.base.mul(&o.eps).add(&self.eps.mul(&o.base));
        let del = self.base.mul(&o.del).add(&self.del.mul(&o.base));
        let eps_del = self
            .base
            .mul(&o.eps_del)
            .add(&self.eps.mul(&o.del))
            .add(&self.del.mul(&o.eps))
            .add(&self.eps_del.mul(&o.base));
        Jet4 {
            base,
            eps,
            del,
            eps_del,
        }
    }
    fn scale(&self, s: f64) -> Self {
        Jet4 {
            base: self.base.scale(s),
            eps: self.eps.scale(s),
            del: self.del.scale(s),
            eps_del: self.eps_del.scale(s),
        }
    }
    #[inline]
    fn neg(&self) -> Self {
        self.scale(-1.0)
    }
    fn compose_unary(&self, d: [f64; 5]) -> Self {
        let base = self.base.compose_unary([d[0], d[1], d[2], d[3], d[4]]);
        let fprime = self.base.compose_unary([d[1], d[2], d[3], d[4], d[4]]);
        let fsecond = self.base.compose_unary([d[2], d[3], d[4], d[4], d[4]]);
        let eps = fprime.mul(&self.eps);
        let del = fprime.mul(&self.del);
        let eps_del = fsecond
            .mul(&self.eps)
            .mul(&self.del)
            .add(&fprime.mul(&self.eps_del));
        Jet4 {
            base,
            eps,
            del,
            eps_del,
        }
    }
}

impl FlexJet for Jet4 {
    const ORDER: usize = 4;

    #[inline]
    fn scale_homogeneous_orders(&self, factors: [f64; 5]) -> Self {
        Jet4 {
            base: self.base.scale_homogeneous_from(0, factors),
            eps: self.eps.scale_homogeneous_from(1, factors),
            del: self.del.scale_homogeneous_from(1, factors),
            eps_del: self.eps_del.scale_homogeneous_from(2, factors),
        }
    }
}

/// `Σ_i x[i]·y[i]` over equal-length slices.
#[inline]
fn dot(x: &[f64], y: &[f64]) -> f64 {
    x.iter().zip(y.iter()).map(|(&a, &b)| a * b).sum()
}

/// `out[i] = Σ_j m[i*p+j]·v[j]` for a row-major `p×p` matrix `m`.
fn mat_vec(m: &[f64], v: &[f64], p: usize) -> Vec<f64> {
    let mut out = vec![0.0; p];
    for i in 0..p {
        let mut acc = 0.0;
        for j in 0..p {
            acc += m[i * p + j] * v[j];
        }
        out[i] = acc;
    }
    out
}

/// `v1ᵀ m v2` for a row-major `p×p` matrix `m`.
fn quad_form(m: &[f64], v1: &[f64], v2: &[f64], p: usize) -> f64 {
    let mut acc = 0.0;
    for i in 0..p {
        let mi = &m[i * p..i * p + p];
        acc += v1[i] * dot(mi, v2);
    }
    acc
}

/// Order-≤2 jet channels (value, gradient view, optional Hessian view) for the
/// four flex row-NLL inputs (entry η, exit η, observed χ, observed d), bundled
/// so `flex_row_nll_value_grad_hess` stays under the argument-count gate.
pub(crate) struct FlexRowJet2Channels<'a> {
    pub eta0_v: f64,
    pub eta0_g: ndarray::ArrayView1<'a, f64>,
    pub eta0_h: Option<ndarray::ArrayView2<'a, f64>>,
    pub eta1_v: f64,
    pub eta1_g: ndarray::ArrayView1<'a, f64>,
    pub eta1_h: Option<ndarray::ArrayView2<'a, f64>>,
    pub chi1_v: f64,
    pub chi1_g: ndarray::ArrayView1<'a, f64>,
    pub chi1_h: Option<ndarray::ArrayView2<'a, f64>>,
    pub d1_v: f64,
    pub d1_g: ndarray::ArrayView1<'a, f64>,
    pub d1_h: Option<ndarray::ArrayView2<'a, f64>>,
}

/// Entry/exit base + directional timepoint packs for the contracted-third path,
/// bundled to keep `flex_row_nll_third_contracted` under the argument-count gate.
pub(crate) struct FlexThirdPacks<'a> {
    pub entry_base: &'a FlexTimepointBasePack,
    pub exit_base: &'a FlexTimepointBasePack,
    pub entry_ext: &'a FlexTimepointDirectionalPack,
    pub exit_ext: &'a FlexTimepointDirectionalPack,
}

/// Entry/exit base + both directional + bidirectional timepoint packs for the
/// contracted-fourth path, bundled to keep `flex_row_nll_fourth_contracted`
/// under the argument-count gate.
pub(crate) struct FlexFourthPacks<'a> {
    pub entry_base: &'a FlexTimepointBasePack,
    pub exit_base: &'a FlexTimepointBasePack,
    pub entry_ext_u: &'a FlexTimepointDirectionalPack,
    pub exit_ext_u: &'a FlexTimepointDirectionalPack,
    pub entry_ext_v: &'a FlexTimepointDirectionalPack,
    pub exit_ext_v: &'a FlexTimepointDirectionalPack,
    pub entry_bi: &'a FlexTimepointBidirectionalPack,
    pub exit_bi: &'a FlexTimepointBidirectionalPack,
}

impl SurvivalMarginalSlopeFamily {
    /// Single-source flex row value + gradient (+ Hessian if `hess_h*` non-empty)
    /// from the entry/exit timepoint packs. The Hessian channel is returned only
    /// when the `*_uv` slices are supplied; the grad-only caller passes empty
    /// `h` slices (the value/gradient channels do not read the Hessian).
    ///
    /// `g_*` are the length-`p` gradient packs, `h_*` the `p*p` row-major Hessian
    /// packs (empty for grad-only). Replaces the hand value/grad/Hessian
    /// assembly in `flex_sensitivity.rs`.
    pub(crate) fn flex_row_nll_value_grad_hess(
        &self,
        row: usize,
        primary: &FlexPrimarySlices,
        q1: f64,
        qd1: f64,
        ch: FlexRowJet2Channels<'_>,
    ) -> Result<(f64, Array1<f64>, Array2<f64>), String> {
        let FlexRowJet2Channels {
            eta0_v,
            eta0_g,
            eta0_h,
            eta1_v,
            eta1_g,
            eta1_h,
            chi1_v,
            chi1_g,
            chi1_h,
            d1_v,
            d1_g,
            d1_h,
        } = ch;
        let p = primary.total;
        let wi = self.weights[row];
        let di = self.event[row];
        let surv0 = surv_stack(eta0_v)?;
        let surv1 = surv_stack(eta1_v)?;
        let want_hess = eta1_h.is_some();
        if !want_hess {
            // Grad-only: the value/gradient channels never read the Hessian, so a
            // value+gradient-only `Jet1` yields a `to_bits`-identical value+grad
            // while dropping the discarded `O(p²)` Hessian alloc + arithmetic.
            let eta0 = Jet1::from_view(eta0_v, eta0_g);
            let eta1 = Jet1::from_view(eta1_v, eta1_g);
            let chi1 = Jet1::from_view(chi1_v, chi1_g);
            let d1 = Jet1::from_view(d1_v, d1_g);
            let q1j = Jet1::primary(q1, primary.q1, p);
            let qd1j = Jet1::primary(qd1, primary.qd1, p);
            let out = flex_row_nll(&eta0, &eta1, &chi1, &d1, &q1j, &qd1j, surv0, surv1, wi, di);
            let value = out.v + wi * di * std::f64::consts::TAU.ln();
            let grad = Array1::from(out.g);
            return Ok((value, grad, Array2::zeros((p, p))));
        }
        // Compile the SAME seven-term outer plan the generic Jet1/Jet3/Jet4
        // evaluators consume, then lower its six independent sources in one
        // order-two pass. Only the returned gradient and Hessian allocate.
        let eta0_h = eta0_h.ok_or("flex order-two lowering: missing eta0 Hessian")?;
        let chi1_h = chi1_h.ok_or("flex order-two lowering: missing chi1 Hessian")?;
        let d1_h = d1_h.ok_or("flex order-two lowering: missing d1 Hessian")?;
        let eta1_h = eta1_h.ok_or("flex order-two lowering: missing eta1 Hessian")?;
        let plan = FlexOuterPlan::new(chi1_v, d1_v, qd1, surv0, surv1, wi, di);
        let (row_value, row_gradient, row_hessian) = lower_flex_outer_plan_order2(
            &plan,
            FlexOrder2Inputs {
                eta0: FlexOrder2View {
                    value: eta0_v,
                    gradient: eta0_g,
                    hessian: eta0_h,
                },
                eta1: FlexOrder2View {
                    value: eta1_v,
                    gradient: eta1_g,
                    hessian: eta1_h,
                },
                q1: (q1, primary.q1),
                chi1: FlexOrder2View {
                    value: chi1_v,
                    gradient: chi1_g,
                    hessian: chi1_h,
                },
                d1: FlexOrder2View {
                    value: d1_v,
                    gradient: d1_g,
                    hessian: d1_h,
                },
                qd1: (qd1, primary.qd1),
            },
            p,
        );
        let value = row_value + wi * di * std::f64::consts::TAU.ln();
        let grad = Array1::from(row_gradient);
        let hess = Array2::from_shape_vec((p, p), row_hessian).map_err(|e| e.to_string())?;
        Ok((value, grad, hess))
    }

    /// Single-source flex contracted third `D_dir H[u,v]` from the entry/exit
    /// base + directional packs through the canonical flex-row plan.
    pub(crate) fn flex_row_nll_third_contracted(
        &self,
        row: usize,
        primary: &FlexPrimarySlices,
        q1: f64,
        qd1: f64,
        dir: &[f64],
        packs: FlexThirdPacks<'_>,
    ) -> Result<Array2<f64>, String> {
        let FlexThirdPacks {
            entry_base,
            exit_base,
            entry_ext,
            exit_ext,
        } = packs;
        let p = primary.total;
        let wi = self.weights[row];
        let di = self.event[row];
        let surv0 = surv_stack(entry_base.eta)?;
        let surv1 = surv_stack(exit_base.eta)?;

        let mk =
            |base_v: f64, base_g: &[f64], base_h: &[f64], ext_g: &[f64], ext_h: &[f64]| -> Jet3 {
                Jet3 {
                    base: Jet2::from_parts(base_v, base_g, base_h),
                    eps: Jet2::from_parts(dot(base_g, dir), ext_g, ext_h),
                }
            };
        let eta0 = mk(
            entry_base.eta,
            &entry_base.eta_u,
            &entry_base.eta_uv,
            &entry_ext.eta_u_dir,
            &entry_ext.eta_uv_dir,
        );
        let eta1 = mk(
            exit_base.eta,
            &exit_base.eta_u,
            &exit_base.eta_uv,
            &exit_ext.eta_u_dir,
            &exit_ext.eta_uv_dir,
        );
        let chi1 = mk(
            exit_base.chi,
            &exit_base.chi_u,
            &exit_base.chi_uv,
            &exit_ext.chi_u_dir,
            &exit_ext.chi_uv_dir,
        );
        let d1 = mk(
            exit_base.d,
            &exit_base.d_u,
            &exit_base.d_uv,
            &exit_ext.d_u_dir,
            &exit_ext.d_uv_dir,
        );
        let q1j = Jet3::primary(q1, primary.q1, p, dir[primary.q1]);
        let qd1j = Jet3::primary(qd1, primary.qd1, p, dir[primary.qd1]);
        let out = flex_row_nll(&eta0, &eta1, &chi1, &d1, &q1j, &qd1j, surv0, surv1, wi, di);
        Array2::from_shape_vec((p, p), out.contracted_third()).map_err(|e| e.to_string())
    }

    /// Single-source flex contracted fourth `Σ_{cd} ℓ_{abcd} u_c v_d` from the
    /// entry/exit base + both directional packs + bidirectional packs. Replaces
    /// the same canonical flex-row plan at fourth order.
    pub(crate) fn flex_row_nll_fourth_contracted(
        &self,
        row: usize,
        primary: &FlexPrimarySlices,
        q1: f64,
        qd1: f64,
        dir_u: &[f64],
        dir_v: &[f64],
        packs: FlexFourthPacks<'_>,
    ) -> Result<Array2<f64>, String> {
        let FlexFourthPacks {
            entry_base,
            exit_base,
            entry_ext_u,
            exit_ext_u,
            entry_ext_v,
            exit_ext_v,
            entry_bi,
            exit_bi,
        } = packs;
        let p = primary.total;
        let wi = self.weights[row];
        let di = self.event[row];
        let surv0 = surv_stack(entry_base.eta)?;
        let surv1 = surv_stack(exit_base.eta)?;

        // eps_del.v = uᵀ·H·v, eps_del.g = (H_dir_u)·v, eps_del.h = bi.
        let mk = |base_v: f64,
                  base_g: &[f64],
                  base_h: &[f64],
                  ext_u_g: &[f64],
                  ext_u_h: &[f64],
                  ext_v_g: &[f64],
                  ext_v_h: &[f64],
                  bi_h: &[f64]|
         -> Jet4 {
            let eps_del_v = quad_form(base_h, dir_u, dir_v, p);
            let eps_del_g = mat_vec(ext_u_h, dir_v, p);
            Jet4 {
                base: Jet2::from_parts(base_v, base_g, base_h),
                eps: Jet2::from_parts(dot(base_g, dir_u), ext_u_g, ext_u_h),
                del: Jet2::from_parts(dot(base_g, dir_v), ext_v_g, ext_v_h),
                eps_del: Jet2::from_parts(eps_del_v, &eps_del_g, bi_h),
            }
        };
        let eta0 = mk(
            entry_base.eta,
            &entry_base.eta_u,
            &entry_base.eta_uv,
            &entry_ext_u.eta_u_dir,
            &entry_ext_u.eta_uv_dir,
            &entry_ext_v.eta_u_dir,
            &entry_ext_v.eta_uv_dir,
            &entry_bi.eta_uv_uv,
        );
        let eta1 = mk(
            exit_base.eta,
            &exit_base.eta_u,
            &exit_base.eta_uv,
            &exit_ext_u.eta_u_dir,
            &exit_ext_u.eta_uv_dir,
            &exit_ext_v.eta_u_dir,
            &exit_ext_v.eta_uv_dir,
            &exit_bi.eta_uv_uv,
        );
        let chi1 = mk(
            exit_base.chi,
            &exit_base.chi_u,
            &exit_base.chi_uv,
            &exit_ext_u.chi_u_dir,
            &exit_ext_u.chi_uv_dir,
            &exit_ext_v.chi_u_dir,
            &exit_ext_v.chi_uv_dir,
            &exit_bi.chi_uv_uv,
        );
        let d1 = mk(
            exit_base.d,
            &exit_base.d_u,
            &exit_base.d_uv,
            &exit_ext_u.d_u_dir,
            &exit_ext_u.d_uv_dir,
            &exit_ext_v.d_u_dir,
            &exit_ext_v.d_uv_dir,
            &exit_bi.d_uv_uv,
        );
        let q1j = Jet4::primary(q1, primary.q1, p, dir_u[primary.q1], dir_v[primary.q1]);
        let qd1j = Jet4::primary(qd1, primary.qd1, p, dir_u[primary.qd1], dir_v[primary.qd1]);
        let out = flex_row_nll(&eta0, &eta1, &chi1, &d1, &q1j, &qd1j, surv0, surv1, wi, di);
        Array2::from_shape_vec((p, p), out.contracted_fourth()).map_err(|e| e.to_string())
    }
}

// ── #932-2 PRODUCTION jet timepoint machinery (promoted from the
// `moment_engine_tests` oracle module) ──────────────────────────────────────
//
// The single-source flex timepoint `(eta, chi, d)` jet builder
// `flex_timepoint_inputs_generic` and its helpers (the `FlexJet` moment
// recurrence, intercept lift, cell-coefficient / chi-poly / moving-edge jets, and
// the observed / calibration input bridges) live here at module scope, consumed by
// the `compute_survival_timepoint_exact_jet` Jet2 wrapper below. Independent
// scalar-FD and nested-dual gates live in `moment_engine_tests`.

// #932: the `recip`/`exp`/`add_const` jet helpers (formerly `FlexJet` default
// methods) live here as free generic fns — only the relocated moment-engine /
// Phase-C builders below consume them, so keeping them inside the test module
// avoids the orphaned-`dead_code` gate while preserving the exact derivations.
fn recip<J: FlexJet>(x: &J) -> J {
    let v = x.value();
    let inv = 1.0 / v;
    let inv2 = inv * inv;
    x.compose_unary([
        inv,
        -inv2,
        2.0 * inv2 * inv,
        -6.0 * inv2 * inv2,
        24.0 * inv2 * inv2 * inv,
    ])
}
fn exp_jet<J: FlexJet>(x: &J) -> J {
    let e = x.value().exp();
    x.compose_unary([e, e, e, e, e])
}
fn add_const<J: FlexJet>(x: &J, c: f64) -> J {
    x.compose_unary([x.value() + c, 1.0, 0.0, 0.0, 0.0])
}

/// The calibration residual term `C·M` as a **distinguished-derivative
/// projector**, NOT an ordinary product. (`C = self` the coefficient jet,
/// `M = m` the moment jet.)
///
/// ## Why a projector and not `mul`
///
/// The calibration residual is `R = ∫ η e^{−q} dz = Σ_k C_k M_k`, and its
/// derivatives must equal the calibration constraint tensors `∂_θ R = ∫ η_θ
/// e^{−q}` whose FIRST (lead) index is forced onto the coefficient η. The
/// moment carries the `e^{−q}` motion (`M_a = −∫ z^k η η_a e^{−q}`), so when
/// both `C` and `M` move with the same θ, an ordinary jet product
/// `tangent(C)·M` double-counts the shared η-motion: at order n it gives
/// every `(j,m)` split the binomial weight, which is too large by `(j+m)/j`.
///
/// ## The exact law (distinguished-derivative averaging)
///
/// Average over which of the `r = |I|` derivative slots is the distinguished
/// (lead) one; a term `C_A M_B` (A on the coefficient, B on the moment)
/// survives iff the lead slot lies in A, which happens with probability
/// `|A|/|I|`:
///
/// ```text
///   P_I(C,M) = Σ_{A⊔B=I, A≠∅}  (|A| / |I|)  C_A M_B ,   weight j/(j+m), j=|A|.
/// ```
///
/// Orders 1–4 (the `Jet2`/`Jet3`/`Jet4` impls below realise exactly these):
///
/// ```text
///   P_i    = C_i M
///   P_ij   = C_ij M + ½(C_i M_j + C_j M_i)
///   P_ijk  = C_ijk M + ⅔ Σ C_ij M_k + ⅓ Σ C_i M_jk
///   P_ijkl = C_ijkl M + ¾ Σ C_ijk M_l + ½ Σ C_ij M_kl + ¼ Σ C_i M_jkl
/// ```
///
/// Along a scalar path the law collapses to the closed form
/// `P_n = Σ_j C(n,j)·(j/n)·C^(j)M^(n−j) = Σ_j C(n−1,j−1) C^(j)M^(n−j)
///      = d^(n−1)/dt^(n−1) (C′M)` — i.e. `½/⅔,⅓/¾,½,¼` are not empirical
/// fudge factors but `binom(n−1,j−1)/binom(n,j)`. The implementation below
/// generates them for every channel as `E⁻¹((E C)M)`; no order-specific table
/// remains. It is verified channel-for-channel against the true `R_ij…`
/// integrals (gam#932).
///
/// `moment_term` was formerly a `FlexJet` trait method, but the production
/// single-source NLL assembles its residual directly. The private extension
/// trait expresses the projector once for every production and oracle algebra.
trait MomentTerm: FlexJet {
    fn moment_term(&self, moment: &Self) -> Self {
        // Let E be the Euler operator that multiplies every homogeneous
        // derivative channel of order j by j. For total order n=j+m,
        //
        //     E⁻¹((E C) M)
        //
        // assigns the ordinary Leibniz split C_A M_B the required
        // distinguished-slot weight j/n. The jet product supplies every
        // partition and its multiplicity; the two order maps below therefore
        // generate the complete projector for every represented order without
        // an order-specific coefficient table.
        const EULER: [f64; 5] = [0.0, 1.0, 2.0, 3.0, 4.0];
        const EULER_INVERSE: [f64; 5] = [0.0, 1.0, 0.5, 1.0 / 3.0, 0.25];
        self.scale_homogeneous_orders(EULER)
            .mul(moment)
            .scale_homogeneous_orders(EULER_INVERSE)
    }
}

impl<J: FlexJet> MomentTerm for J {}

/// #932 item-2 Phase B-base: the normalization base moments `M_0..M_4` as jets,
/// carrying their exact θ-derivatives (incl. the moving-edge flux), built from
/// the cell's already-computed NUMERIC moment vector (`numeric_moments`) plus the
/// cell-coefficient jets `c` and the moving edge jets `(z_left, z_right)`.
///
/// `M_n = ∫_{z_L(θ)}^{z_R(θ)} zⁿ e^{−q(z,θ)} dz`, `q = ½(z² + η(z)²)`, `η = c0+c1z
/// +c2z²+c3z³` with `(c, z_L, z_R)` all θ-dependent.
///
/// This single-sources the hand `survival_flex_base_d_u`/`_d_uv`/`f_au`/`f_aa`
/// base normalization derivatives over a generic `FlexJet` order — exact to ALL
/// jet orders (Jet2/Jet3/Jet4), not just first. The value channel is
/// bit-identical to `numeric_moments[n]`; the derivative channels are
/// finite-difference-pinned against `evaluate_cell_moments` on perturbed cells
/// (`base_moment_jets_first_derivative_matches_fd_932`,
/// `base_moment_jets_second_derivative_matches_fd_932`).
///
/// EXACTNESS to all orders (the self-consistent closure): write
/// `M_n(θ) = ∫ zⁿ e^{−q(z,θ)} dz = ∫ zⁿ e^{−q(z,θ₀)}·e^{−Δq(z)} dz`,
/// `Δq(z) = q(z,θ) − q(z,θ₀) = ½(η(z,θ)² − η(z,θ₀)²)` (the `z²` term cancels).
/// The factor `e^{−Δq}` has VALUE channel 1 (Δq=0 at θ₀) and its derivative
/// channels carry the full `(−∂q)` / `(−∂²q + (∂q)²)` / … expansion. Expanding
/// `e^{−Δq}` as a jet-coefficient polynomial in `z` (`S(z)=Σ_m S_m zᵐ`, `S_m`
/// jets) and dotting against the NUMERIC moments gives the interior
/// `Σ_m S_m·M_{n+m}^{numeric}` — exact to every order because the `e^{−Δq}`
/// expansion already contains the `(∂q)²` cross-term and higher. The truncation
/// `e^{−Δq} ≈ Σ_{k≤J::ORDER} (−Δq)^k/k!` is exact in each instantiated
/// nilpotent algebra (`Δq` has value 0, so the next power only feeds derivative
/// orders that `J` does not represent). The boundary is the Leibniz flux
/// `+ f(z_R)·z_R' − f(z_L)·z_L'`,
/// integrand VALUE at the moving endpoint times the edge θ-velocity jet (exact to
/// all orders via the edge-jet algebra).
fn base_moment_jets<J: FlexJet>(
    c: &[J; 4],
    z_left: &J,
    left_finite: bool,
    z_right: &J,
    right_finite: bool,
    numeric_moments: &[f64],
) -> [J; 5] {
    assert!(
        (1..=4).contains(&J::ORDER),
        "base_moment_jets supports exact derivative orders 1 through 4"
    );
    let required_moments = 5 + 6 * J::ORDER;
    assert!(
        numeric_moments.len() >= required_moments,
        "order-{} base-moment jet requires numeric M_0..M_{}, got only {} moments",
        J::ORDER,
        required_moments - 1,
        numeric_moments.len()
    );

    // η₀ = value-only coefficient jets; jet-polynomial convolution helper.
    let c0_const: [J; 4] = std::array::from_fn(|k| const_jet_like(&c[k], c[k].value()));
    let conv = |lhs: &[J], rhs: &[J]| -> Vec<J> {
        let mut out: Vec<J> = (0..lhs.len() + rhs.len() - 1)
            .map(|_| const_jet_like(&c[0], 0.0))
            .collect();
        for (i, li) in lhs.iter().enumerate() {
            for (j, rj) in rhs.iter().enumerate() {
                out[i + j] = out[i + j].add(&li.mul(rj));
            }
        }
        out
    };
    // −Δq(z) = −½(η² − η₀²), a jet-coefficient polynomial in z (value channel 0).
    let eta_sq = conv(c, c);
    let eta0_sq = conv(&c0_const, &c0_const);
    let neg_dq: Vec<J> = eta_sq
        .iter()
        .zip(eta0_sq.iter())
        .map(|(a, b)| a.sub(b).scale(-0.5))
        .collect();
    // S(z) = e^{−Δq} = Σ_{k=0}^{J::ORDER} (−Δq)^k / k!
    // (jet-coefficient polynomial),
    // splitting e^{−q(θ)} = e^{−q0}·e^{−Δq}, Δq = q(θ)−q0. Truncating at
    // p=J::ORDER is EXACT: value(−Δq)=0 ⇒ −Δq ∈ m (nilpotent) ⇒
    // (−Δq)^{p+1} = 0. Using the instantiated order is not an approximation:
    // evaluating the order-four polynomial in Jet1/2/3 previously spent most
    // of its time constructing channels that are identically zero.
    //
    // MOMENT-DEGREE BUDGET. η is cubic ⇒ deg_z(Δq) ≤ 6, so deg_z(S) ≤ 6p, and
    // the interior dot `Σ_m S_m·M_{n+m}` below reaches `M_{n+6p}`. An order-`p`
    // jet for `M_n` therefore needs numeric base moments through `n + 6p`: for
    // p=4 that is `n+24` (n≤4 base moments → M_28; n≤3 calibration → M_27). The
    // cached partition builds to 32 (margin), which is why 27/32 are not magic.
    let mut s_poly: Vec<J> = vec![const_jet_like(&c[0], 1.0)];
    let mut power: Vec<J> = s_poly.clone();
    let factorials = [1.0_f64, 1.0, 2.0, 6.0, 24.0];
    for fact in factorials.iter().take(J::ORDER + 1).skip(1) {
        power = conv(&power, &neg_dq);
        for (m, coeff) in power.iter().enumerate() {
            let term = coeff.scale(1.0 / fact);
            if m < s_poly.len() {
                s_poly[m] = s_poly[m].add(&term);
            } else {
                s_poly.push(term);
            }
        }
    }
    // The interior `Σ_m S_m·M_{n+m}^{numeric}` integrates `g(z,θ)=zⁿe^{−q(z,θ)}`
    // over the FIXED value-channel limits `[z_L0, z_R0]` (the numeric moments are
    // those fixed-limit integrals). The MOVING-limit correction is the thin
    // sliver `∫_{z_R0}^{z_R(θ)} g dz − ∫_{z_L0}^{z_L(θ)} g dz` (`edge_sliver_jet`),
    // exact to all jet orders.
    //
    // SHARED-EDGE JUMP COLLAPSE: when the caller sums these per-cell moments over
    // a partition, an INTERIOR edge shared by cells `i`,`i+1` enters as `+sliver`
    // (cell i's right) and `−sliver` (cell i+1's left) at the SAME moving `z` with
    // the SAME `g` — so the two flux contributions telescope to zero automatically.
    // Only GENUINE boundaries (the timepoint Crossing edge with no cancel partner,
    // §D) survive. No hand jump/flux formula is needed; the cancellation is exact
    // in the jet algebra because both slivers are the identical jet with opposite
    // sign.
    std::array::from_fn(|n| {
        let mut acc = const_jet_like(&c[0], 0.0);
        for (m, s_m) in s_poly.iter().enumerate() {
            let m_npm = numeric_moments[n + m];
            if m_npm != 0.0 {
                acc = acc.add(&s_m.scale(m_npm));
            }
        }
        if let Some(sr) = edge_sliver_jet(n, c, z_right, right_finite) {
            acc = acc.add(&sr);
        }
        if let Some(sl) = edge_sliver_jet(n, c, z_left, left_finite) {
            acc = acc.sub(&sl);
        }
        acc
    })
}

/// The moving-edge sliver `∫_{z_E0}^{z_E(θ)} zⁿ e^{−q(z,θ)} dz` as a jet (value
/// 0, derivative channels = the §D moving-boundary flux to all orders). With
/// `δ = z_E − z_E0` (jet, value 0) and `g(z) = zⁿ e^{−q}`,
/// `∫_{z_E0}^{z_E} g dz = g·δ + ½ g_z δ² + ⅙ g_zz δ³ + (1/24) g_zzz δ⁴` (Taylor
/// in δ; the instantiated [`FlexJet::ORDER`] selects the exact prefix because
/// the next δ power vanishes in that nilpotent quotient). `g`, `g_z`, … are
/// evaluated at the FIXED edge `z_E0` but with the θ-dependent coefficient jets
/// `c`, so the sliver carries the full coefficient × edge cross-motion.
/// `q = ½(z² + η²)`,
/// `q_z = z + η η_z`, `η_z = c1 + 2c2 z + 3c3 z²`; the `g`-stack follows from
/// `g_z = (n/z − q_z) g` by the product/chain rule.
///
/// The four `gδ`/`½g_z δ²`/`⅙g_zz δ³`/`(1/24)g_zzz δ⁴` terms are JET products, so
/// the θ-jet of the sliver automatically contains every coefficient×edge cross
/// channel of the full Faà di Bruno expansion. Concretely, writing `d_k = δ^(k)`
/// and `G_r^[s] = ∂_t^s ∂_z^r g`, the 4th θ-derivative is
/// `S'''' = G_0 d_4 + 4G_0^[1] d_3 + 6G_0^[2] d_2 + 4G_0^[3] d_1 + 4G_1 d_1 d_3
///        + 3G_1 d_2² + 12G_1^[1] d_1 d_2 + 6G_1^[2] d_1² + 6G_2 d_1² d_2
///        + 4G_2^[1] d_1³ + G_3 d_1⁴`. So a 4th-ORDER-only crossing-edge mismatch
/// is NOT uniquely the `g_zzz δ⁴` term — it can equally be a wrong `z_4` (edge
/// 4th deriv) or a coefficient-edge CROSS channel (`G_1^[2] d_1²`, `G_2^[1] d_1³`,
/// `G_1 d_2²`). NOTE: the `n/z` `g`-stack form has a removable singularity at
/// `z_E0=0` (special-cased); the singularity-free polynomial form
/// `g_z = e^{−q}(n z^{n−1} − q_z z^n)`, `g_zz = e^{−q}(n(n−1)z^{n−2} − 2n q_z z^{n−1}
/// + (q_z²−q_zz)z^n)`, … is preferable when `z_E0` may be near 0.
fn edge_sliver_jet<J: FlexJet>(n: usize, c: &[J; 4], z_e: &J, finite: bool) -> Option<J> {
    if !finite {
        return None;
    }
    let z0 = z_e.value();
    let zc = const_jet_like(z_e, z0); // fixed edge, value-only
    // η at the fixed edge as a jet in c. Higher z-derivatives are constructed
    // lazily below only when the instantiated nilpotent order can consume them.
    let eta = c[3]
        .mul(&zc)
        .add(&c[2])
        .mul(&zc)
        .add(&c[1])
        .mul(&zc)
        .add(&c[0]);
    // g = zⁿ e^{−q}.
    let z_pow = {
        let mut zk = const_jet_like(z_e, 1.0);
        for _ in 0..n {
            zk = zk.mul(&zc);
        }
        zk
    };
    let q = zc.mul(&zc).add(&eta.mul(&eta)).scale(0.5);
    let w = exp_jet(&q.scale(-1.0));
    let g = z_pow.mul(&w);
    let delta = tangent_jet(z_e);
    let mut sliver = g.mul(&delta);
    if J::ORDER == 1 {
        return Some(sliver);
    }

    // η_z and q_z are needed starting at the δ² term.
    let eta_z = c[2]
        .scale(2.0)
        .add(&c[3].scale(3.0).mul(&zc))
        .mul(&zc)
        .add(&c[1]); // c1 + 2c2 z + 3c3 z²
    let q_z = zc.add(&eta.mul(&eta_z));
    // n/z^k constants (z held at the fixed edge); 0 when n=0 or z0=0.
    let nz = |power: i32| -> J {
        if n == 0 || z0 == 0.0 {
            const_jet_like(z_e, 0.0)
        } else {
            const_jet_like(z_e, n as f64 / z0.powi(power))
        }
    };
    // g_z/g = a1 = n/z − q_z.
    let a1 = nz(1).sub(&q_z);
    let g_z = a1.mul(&g);
    let d2 = delta.mul(&delta);
    sliver = sliver.add(&g_z.mul(&d2).scale(0.5));
    if J::ORDER == 2 {
        return Some(sliver);
    }

    // η_zz, q_zz and a1' first contribute through the δ³ term.
    let eta_zz = c[2].scale(2.0).add(&c[3].scale(6.0).mul(&zc)); // 2c2 + 6c3 z
    let q_zz = add_const(&eta_z.mul(&eta_z).add(&eta.mul(&eta_zz)), 1.0);
    let a1p = nz(2).scale(-1.0).sub(&q_zz);
    // g_zz/g = b2 = a1' + a1².
    let b2 = a1p.add(&a1.mul(&a1));
    let g_zz = b2.mul(&g);
    let d3 = d2.mul(&delta);
    sliver = sliver.add(&g_zz.mul(&d3).scale(1.0 / 6.0));
    if J::ORDER == 3 {
        return Some(sliver);
    }

    // The fourth-order quotient is the only one that can observe g_zzz·δ⁴.
    assert_eq!(
        J::ORDER,
        4,
        "edge sliver supports derivative orders 1 through 4"
    );
    let eta_zzz = c[3].scale(6.0); // 6c3
    let q_zzz = eta_z.scale(3.0).mul(&eta_zz).add(&eta.mul(&eta_zzz));
    let a1pp = nz(3).scale(2.0).sub(&q_zzz);
    // g_zzz/g = b2' + a1 b2, b2' = a1'' + 2 a1 a1'.
    let b2p = a1pp.add(&a1.mul(&a1p).scale(2.0));
    let g_zzz = b2p.add(&a1.mul(&b2)).mul(&g);
    let d4 = d3.mul(&delta);
    Some(sliver.add(&g_zzz.mul(&d4).scale(1.0 / 24.0)))
}

/// #932 item-2 STEP 3c: the GENERIC-order timepoint `(eta, chi, d)` builder over
/// ANY `FlexJet` order (`Jet2`/`Jet3`/`Jet4`). It consumes only jet algebra, so
/// instantiating it at `Jet3` (one directional seed) yields the directional
/// extension `D_dir(eta,chi,d)` in the `eps` channel, and at `Jet4` (two seeds)
/// the mixed second-directional `D_d1 D_d2` in the `eps_del` channel.
///
/// The caller pre-seeds `b_jet` (the slope `g` primary), `du[u]` (the unit
/// per-primary jets), `template` (a zero jet shaped at the right order/`p`), and
/// `q_jet` (the complete time-quantile jet, including both coefficient and
/// family-owned directions), plus `scale_ratio_jet` (the current probit scale
/// divided by the f64 scale already baked into the cached coefficient packs),
/// and
/// supplies the OBSERVED-channel jets `rho_jet`/`tau_jet` (the `h`/`w`/`infl`
/// linear channels added to `eta`/`chi`; pass zero jets for a pure `g` model,
/// where the full `(a,b)` observed-coeff pack already carries every `g` order).
/// The full `(a,b)` Taylor runs against the REAL `b_jet` here (no `db=0`), so the
/// `g`-axis is single-sourced through the pack at every order.
///
/// Returns the three output jets `(eta, chi, d)`; the caller extracts the value /
/// gradient / Hessian / directional channels it needs.
fn flex_timepoint_inputs_generic<J: FlexJet + MomentTerm>(
    template: &J,
    b_jet: &J,
    du: &[J],
    a0: f64,
    d_check: f64,
    primary_g: usize,
    infl: Option<usize>,
    q_jet: &J,
    scale_ratio_jet: &J,
    z_obs: f64,
    o_infl: f64,
    obs_coeff: [f64; 4],
    obs_fixed: &DenestedCellPrimaryFixedPartials,
    cells: &[CalibrationCellJetInputs<'_>],
) -> Result<(J, J, J), String> {
    // Intercept lift to order `J` (value/grad/Hess/… per the seed). The lift's
    // residual closure rebuilds the per-cell coefficient + moment jets at the
    // current iterate, so the lifted `a_jet` carries the intercept's full
    // θ-jet (incl. directional channels) to order `J` automatically.
    //
    // The filtered (frozen-inverse) Newton chord gains exactly ONE derivative
    // order per iteration, so the iterate count must reach the highest jet
    // order in play: 2 for `Jet2`, 3 for the `Jet3` directional Hessian, 4 for
    // the `Jet4` mixed-second-directional channel. Use that algebraic order
    // directly. Although a later correction is mathematically zero once every
    // represented order has converged, evaluating it still rebuilds the full
    // per-cell residual program; an unconditional fourth pass therefore wasted
    // one third of the Jet3 lift work and half of the Jet2 lift work. (A
    // hardcoded 2 left the Jet3/Jet4 mixed intercept derivatives one iteration
    // short — `eta_uv` converged but `eta_uv_dir` did not; gam#932.)
    let residual =
        |a: &J| calibration_residual_jet(a, b_jet, primary_g, du, q_jet, scale_ratio_jet, cells);
    let a_jet = lift_intercept_flex(template, a0, 1.0 / d_check, J::ORDER, residual);

    // Observed eta/chi: the OBSERVED cell coefficient `c_k(a, {θ_u})` and its
    // `∂_a` (= χ) built as MULTIVARIATE jets over ALL primaries (g/h/w) via
    // `cell_coeff_jets`/`cell_chi_poly_jets` on the OBSERVED-point fixed pack
    // `obs_fixed` (the analogue of the calibration cells' pack: `coeff_u[g]=dc_db`,
    // `coeff_u[h]=b·H(z_obs)`, `coeff_u[w]=link_basis(a,b)`, with their a/b
    // partials). Composing with the lifted `a_jet` + the directional `du` seeds
    // carries the h/w cross-derivatives to ALL orders automatically — replacing
    // the (a,b)-only `observed_coeff_component_jet` + frozen-scalar channels.
    // `eta = Σ_k c_k·z_obs^k + o_infl (+ the infl primary's unit partial)`.
    let da = tangent_jet(&a_jet);
    let eta_coeff_base = cell_coeff_jets(&a_jet, obs_coeff, obs_fixed, primary_g, &da, du);
    let chi_coeff_base = cell_chi_poly_jets(&a_jet, obs_fixed, primary_g, &da, du);
    let eta_coeff =
        std::array::from_fn(|coefficient| eta_coeff_base[coefficient].mul(scale_ratio_jet));
    let chi_coeff =
        std::array::from_fn(|coefficient| chi_coeff_base[coefficient].mul(scale_ratio_jet));
    let mut eta = add_const(&eval_coeff_jet_at(&eta_coeff, z_obs), o_infl);
    if let Some(infl_axis) = infl {
        // ∂η₁/∂o_infl = 1: the absorbed-influence offset shifts η₁ additively
        // (#461), independent of the calibration cells, so its only partial is
        // the unit slope on its own primary.
        eta = eta.add(&du[infl_axis]);
    }
    let chi = eval_coeff_jet_at(&chi_coeff, z_obs);

    // D normalization = Σ_cells INV_TWO_PI·Σ_k χ_k·M_k, with the cell coeff /
    // chi-poly jets through the lifted `a_jet` (the `da` tangent above) and the
    // moving-edge jets through `(a_jet, b_jet)`.
    let mut d = const_jet_like(template, 0.0);
    for cell in cells {
        let c_pos_base =
            cell_coeff_jets(&a_jet, cell.base_pos_coeffs, cell.fixed, primary_g, &da, du);
        let chi_jets_base = cell_chi_poly_jets(&a_jet, cell.fixed, primary_g, &da, du);
        let c_pos = std::array::from_fn(|coefficient| c_pos_base[coefficient].mul(scale_ratio_jet));
        let chi_jets =
            std::array::from_fn(|coefficient| chi_jets_base[coefficient].mul(scale_ratio_jet));
        let edge_l = cell_edge_jet(&a_jet, b_jet, cell.left_edge, cell.cell_left);
        let edge_r = cell_edge_jet(&a_jet, b_jet, cell.right_edge, cell.cell_right);
        d = d.add(&flex_timepoint_d_cell(
            template,
            &c_pos,
            &chi_jets,
            &edge_l,
            cell.cell_left.is_finite(),
            &edge_r,
            cell.cell_right.is_finite(),
            cell.numeric_moments,
        ));
    }

    Ok((eta, chi, d))
}

/// A value-zero "tangent" jet `x_jet − x.value()`: value 0, derivative channels
/// preserved. Used as the perturbation argument of the bivariate Taylor below.
#[inline]
fn tangent_jet<J: FlexJet>(x: &J) -> J {
    add_const(x, -x.value())
}

/// A constant jet (value `v`, all derivative channels zero), shaped like
/// `template` (so it carries the right runtime primary count).
#[inline]
fn const_jet_like<J: FlexJet>(template: &J, v: f64) -> J {
    add_const(&template.scale(0.0), v)
}

/// #932 item-2 Phase C STEP 2: the generic-order intercept Newton lift over a
/// runtime `FlexJet` — the linchpin that produces the 3rd/4th intercept
/// θ-derivatives the base Hessian lacks. Mirrors `lift_intercept_order2` /
/// `filtered_implicit_solve_scalar` but over a runtime `Jet2`/`Jet3`/`Jet4`.
///
/// The calibration constraint `F(a(θ), θ) = 0` is solved by the filtered Newton
/// step `A ← A − R(A)·inv_fa` (`inv_fa = 1/D`, `D = |F_a|`), iterated `iters`
/// times (the jet nilpotency order). `R(A)` is the calibration RESIDUAL JET built
/// by the caller-supplied `residual` closure from the per-cell coefficient jets
/// and moment jets:
///
///   R(A) = Σ_cells INV_TWO_PI · Σ_k tangent(c_posₖ(A)) · Mₖ(A)   (+ q self-term)
///
/// where `c_posₖ(A)` are the POSITIVE cell coefficients as jets in `A` (and the
/// primaries) and `Mₖ(A)` the cell's normalization moment jets. This is the EXACT
/// calibration θ-jet to all orders: `∂_θ R = INV_TWO_PI ∫ η_θ e^{−q} = −f_u`,
/// `∂²_θ R = INV_TWO_PI ∫ (η_θθ − η η_θ²) e^{−q}` (the `−η η_θ²` falling out of
/// `Mₖ`'s own `e^{−Δq}` motion `M_θ = −∫ η η_θ e^{−q}`), reproducing the hand
/// `f_u`/`f_uv`/`f_aa` moment dots and their 3rd/4th extensions automatically. The
/// value channel is the scalar calibration `f` (driven to ~0 by seeding
/// `A.value = a0` from the scalar solve), so only the derivative channels solve.
///
/// ## What the iteration converges to: the implicit-function tower
///
/// The fixed point is the exact `a(θ)` of `F(a(θ),θ) = 0`. Differentiating
/// `F` repeatedly (with `F_{pq} = ∂^{p+q}F/∂a^p∂t^q` along a path, `A=a_1`,
/// `B=a_2`, `C=a_3`, `D=a_4`) gives the standard IFT recursion the jet recovers
/// channel-for-channel — only `F_a·a_n` carries `a_n` linearly, all else is the
/// already-known lower orders:
/// ```text
///   a_i   = −F_i / F_a
///   a_ij  = −(F_ij + F_ai a_j + F_aj a_i + F_aa a_i a_j) / F_a
///   A = −F_01/F_10;  B = −(F_02 + 2F_11 A + F_20 A²)/F_10
///   C = −(F_03 + 3F_12 A + 3F_21 A² + F_30 A³ + 3(F_11+F_20 A)B)/F_10
///   D = −(F_04 + 4F_13 A + 6F_22 A² + 4F_31 A³ + F_40 A⁴
///         + 6F_12 B + 12F_21 A B + 6F_30 A² B + 3F_20 B²
///         + 4(F_11+F_20 A)C) / F_10
/// ```
///
/// ## Why an order-`p` jet needs exactly `p` iterations (NOT quadratic Newton)
///
/// `inv_fa` is the FROZEN scalar inverse `1/F_a(a0,0)` — its derivative
/// channels are dropped — so this is a chord/modified-Newton step, not true
/// Newton. Let `m` be the nilpotent ideal of the order-`p` jet algebra
/// (`m^{p+1} = 0`), and `e_r = A_r − a*` the jet error against the exact root.
/// Taylor-expanding `F(a*+e_r) = F_a·e_r + O(e_r²)`,
///
/// ```text
///   e_{r+1} = (1 − inv_fa·F_a(a*,θ))·e_r + O(e_r²).
/// ```
///
/// The constant part of `1 − inv_fa·F_a` vanishes (`inv_fa·F_a(a0,0) = 1`), so
/// `1 − inv_fa·F_a ∈ m`; and `e_r² ∈ m^{2k} ⊆ m^{k+1}`. Hence
/// `e_r ∈ m^k ⟹ e_{r+1} ∈ m^{k+1}`. The seed `A_0 = const(a0)` has no nilpotent
/// channels (`e_0 ∈ m`), so by induction `e_r ∈ m^{r+1}` and `e_p = 0`:
/// **each iteration recovers exactly one additional homogeneous Taylor degree.**
/// So `Jet2 → 2`, `Jet3 → 3`, `Jet4 → 4` (and any extra passes are exact no-ops,
/// since `R(a*) = 0` once converged). A hardcoded `2` left the Jet3/Jet4 mixed
/// intercept derivatives one+ iterations short (gam#932). Callers pass `iters = 4`.
///
/// `template` carries the runtime primary count; `a0` the solved intercept value.
fn lift_intercept_flex<J: FlexJet>(
    template: &J,
    a0: f64,
    inv_fa: f64,
    iters: usize,
    residual: impl Fn(&J) -> J,
) -> J {
    let mut a = const_jet_like(template, a0);
    for _ in 0..iters {
        let r = residual(&a);
        a = a.sub(&r.scale(inv_fa));
    }
    a
}

/// The per-row calibration residual jet `R(A)` for [`lift_intercept_flex`],
/// summed over a timepoint's cells: `Σ_cells INV_TWO_PI·Σ_k tangent(c_posₖ(A))·
/// Mₖ(A)` plus the q-marginal self-term carried by the complete generic `q_jet`
/// and the complete generic probit `scale_ratio_jet` (the
/// historical `f_u[q] += φ(q)` boundary term of the calibration). The cells are
/// supplied as `(base_pos_coeffs, fixed, edges, finiteness, numeric_moments)` so
/// the coefficient jets and moment jets are rebuilt at the current iterate `A`.
fn calibration_residual_jet<J: FlexJet + MomentTerm>(
    a_jet: &J,
    b_jet: &J,
    g_axis: usize,
    du: &[J],
    q_jet: &J,
    scale_ratio_jet: &J,
    cells: &[CalibrationCellJetInputs<'_>],
) -> J {
    let da = tangent_jet(a_jet);
    let inv_two_pi = std::f64::consts::TAU.recip();
    let mut r = const_jet_like(a_jet, 0.0);
    for cell in cells {
        // Positive cell coefficients as jets in (A, primaries).
        let c_pos_base = cell_coeff_jets(a_jet, cell.base_pos_coeffs, cell.fixed, g_axis, &da, du);
        let c_pos = std::array::from_fn(|coefficient| c_pos_base[coefficient].mul(scale_ratio_jet));
        // Moving edge jets: Crossing edges move with A/b, Fixed edges are static.
        let edge_l = cell_edge_jet(a_jet, b_jet, cell.left_edge, cell.cell_left);
        let edge_r = cell_edge_jet(a_jet, b_jet, cell.right_edge, cell.cell_right);
        let m = base_moment_jets(
            &c_pos,
            &edge_l,
            cell.cell_left.is_finite(),
            &edge_r,
            cell.cell_right.is_finite(),
            cell.numeric_moments,
        );
        // Σ_k moment_term(c_posₖ, Mₖ): the EXACT de-nested calibration residual
        // `∫ η_θ e^{−q}`. `moment_term` strips c's value (F's VALUE is carried by
        // the scalar seed) AND applies the `j/(j+m)` Leibniz weights so the lead
        // derivative always lands on the coefficient polynomial η — a plain
        // `tangent(c)·M` over-counts every split-derivative term by its binomial
        // weight, doubling the lifted intercept Hessian `a_uv` (gam#932 base gates).
        let mut cell_r = const_jet_like(a_jet, 0.0);
        for k in 0..4 {
            cell_r = cell_r.add(&c_pos[k].moment_term(&m[k]));
        }
        r = r.add(&cell_r.scale(inv_two_pi));
    }
    // q-marginal self-term, carried to ALL orders as the derivative channels of
    // `g(q) = Φ(−q)` composed with the q-primary jet `q_jet = q + δq`. The hand
    // adds, to the calibration F, `f_u[q] += φ(q)`, `f_uv[[q,q]] += −q·φ(q)`, and
    // the directional `f_uv_dir[[q,q]] += dir[q]·(q²−1)·φ(q)` (first_full.rs:711,
    // directional.rs:351). With `R = −F` and `g'(q)=−φ(q)`, `g''(q)=q·φ(q)`,
    // `g'''(q)=(1−q²)·φ(q)`, `g''''(q)=(q³−3q)·φ(q)`, ADDING `g(q_jet)` (minus its
    // value, to keep this term's value contribution 0 as the scalar seed already
    // drives R≈0) reproduces every order: grad[q]=−φ(q), Hess[q,q]=q·φ(q), and the
    // ε/εδ channels carry the directional `(q²−1)φ` / `(q³−3q)φ` q-self terms the
    // FLAT `−φ(q)·δq` form dropped (the bug the Jet3/Jet4 gates pin).
    let q = q_jet.value();
    let phi_q = crate::probability::normal_pdf(q);
    let g0 = crate::probability::normal_cdf(-q);
    let g1 = -phi_q;
    let g2 = q * phi_q;
    let g3 = (1.0 - q * q) * phi_q;
    let g4 = (q * q * q - 3.0 * q) * phi_q;
    let q_self = add_const(&q_jet.compose_unary([g0, g1, g2, g3, g4]), -g0);
    r = r.add(&q_self);
    r
}

/// Per-cell inputs for [`calibration_residual_jet`]: the positive base
/// coefficients, the fixed-partial pack, the cell edges (location + provenance),
/// and the numeric moment vector. Borrowed from the cached partition.
struct CalibrationCellJetInputs<'a> {
    base_pos_coeffs: [f64; 4],
    fixed: &'a DenestedCellPrimaryFixedPartials,
    cell_left: f64,
    cell_right: f64,
    left_edge: crate::cubic_cell_kernel::PartitionEdge,
    right_edge: crate::cubic_cell_kernel::PartitionEdge,
    numeric_moments: &'a [f64],
}

/// The moving cell-edge `z` as a jet: a `Crossing { tau }` edge sits at
/// `z = (τ − a)/b` and moves with the intercept jet `a_jet` and slope jet
/// `b_jet`; a `Fixed(z)` edge is static (a constant jet, no θ-motion).
///
/// Evaluating `(τ−a)·(1/b)` in the jet algebra reproduces the entire §C
/// crossing-edge velocity recursion for free — no hand flux formula. From the
/// defining identity `b·z = τ − a`, differentiating `n` times along a path
/// gives `Σ_{k=0}^n binom(n,k) b^(k) z^(n−k) = τ^(n) − a^(n)`, i.e.
/// `z^(n) = (τ^(n) − a^(n) − Σ_{k=1}^n binom(n,k) b^(k) z^(n−k)) / b`
/// (`z_1 = (τ_1−a_1−b_1 z)/b`, …, `z_4 = (τ_4−a_4−4b_1 z_3−6b_2 z_2−4b_3 z_1−b_4 z)/b`).
/// That is exactly what `sub` + `mul(&recip(b))` compute channel-for-channel,
/// so the moving-boundary edge velocities the hand `directional`/`bidirectional`
/// assemble by explicit flux drop out of the seed.
fn cell_edge_jet<J: FlexJet>(
    a_jet: &J,
    b_jet: &J,
    edge: crate::cubic_cell_kernel::PartitionEdge,
    z_value: f64,
) -> J {
    match edge {
        crate::cubic_cell_kernel::PartitionEdge::Crossing { tau } => {
            // z = (τ − a)·(1/b).
            const_jet_like(a_jet, tau).sub(a_jet).mul(&recip(b_jet))
        }
        crate::cubic_cell_kernel::PartitionEdge::Fixed(_) => const_jet_like(a_jet, z_value),
    }
}

/// The per-cell de-nested coefficient `c_k` (k = 0..4) as a jet, built from the
/// cell's `DenestedCellPrimaryFixedPartials` pack composed with the intercept
/// perturbation `da = tangent(a_jet)` and the per-primary perturbations
/// `du[u] = tangent(primary_u)`. This is the cell analogue of
/// `observed_coeff_component_jet`, carrying ALL primaries (not just a,b): it is
/// the multivariate Taylor of `c_k(a, {θ_u})` whose cross-partials are the pack
/// fields. Matches the hand `eta_u_poly`/`eta_uv_poly`/`chi_*` assembly in
/// `first_full`/`directional`/`bidirectional` term for term — the FlexJet algebra
/// raises it to the contracted third/fourth automatically.
///
/// Taylor structure (per k, `g_axis` = the slope `b` primary):
///   c = c0
///     + dc_da·da + ½dc_daa·da² + ⅙dc_daaa·da³                       (pure a)
///     + Σ_u coeff_u[u]·du                                           (pure u, lin)
///     + Σ_u coeff_au[u]·da·du + ½Σ_u coeff_aau[u]·da²·du            (a×u)
///     + Σ_u coeff_bu[u]·db·du + Σ_u coeff_abu[u]·da·db·du           (b×u)
///       + ½Σ_u coeff_bbu[u]·db²·du
///     + ⅙Σ_u coeff_aaau[u]·da³·du + ½Σ_u coeff_aabu[u]·da²·db·du    (3rd in a/b ×u)
///       + ½Σ_u coeff_abbu[u]·da·db²·du + ⅙Σ_u coeff_bbbu[u]·db³·du
/// where `db = du[g_axis]` (the slope perturbation). The `coeff_u`-family terms
/// are LINEAR in `du` (each cell coefficient is at most linear in any single
/// non-a/non-b primary), so no `du²` term is needed beyond the b-channel ones.
fn cell_coeff_jets<J: FlexJet>(
    template: &J,
    base_c: [f64; 4],
    fixed: &DenestedCellPrimaryFixedPartials,
    g_axis: usize,
    da: &J,
    du: &[J],
) -> [J; 4] {
    let p = du.len();
    let dada = da.mul(da);
    let dadada = dada.mul(da);
    let db = &du[g_axis];
    let dadb = da.mul(db);
    let dbdb = db.mul(db);
    std::array::from_fn(|k| {
        let mut c = const_jet_like(template, base_c[k]);
        // Pure-a chain.
        c = c
            .add(&da.scale(fixed.dc_da[k]))
            .add(&dada.scale(0.5 * fixed.dc_daa[k]))
            .add(&dadada.scale(fixed.dc_daaa[k] / 6.0));
        // Per-primary chains for the LINEAR axes (u != g): each cell coefficient
        // is at most linear in any single non-a/non-b primary, so every
        // `coeff_*u[u]·…·du[u]` term is genuinely BILINEAR in `du[u]` (factor 1,
        // off-diagonal — no Taylor factorial on `du[u]`). The slope axis `g`
        // (= `b`) is handled separately below because there `du[g] == db` appears
        // as a REPEATED factor: `coeff_bu[g]·db·du[g] = dc_dbb·db²` would
        // DOUBLE-count the pure-`b²` Taylor term (Jet2::mul gives `db·db` a
        // Hessian of 2 — gam#932 g-diagonal fix), and likewise `coeff_abu[g]`
        // (`a·b²`, needs ½) and `coeff_bbu[g]` (`b³`, needs ⅙ not ½).
        for u in 0..p {
            if u == g_axis {
                continue;
            }
            let duu = &du[u];
            let mut chain = duu.scale(fixed.coeff_u[u][k]);
            chain = chain
                .add(&da.mul(duu).scale(fixed.coeff_au[u][k]))
                .add(&dada.mul(duu).scale(0.5 * fixed.coeff_aau[u][k]));
            chain = chain
                .add(&db.mul(duu).scale(fixed.coeff_bu[u][k]))
                .add(&dadb.mul(duu).scale(fixed.coeff_abu[u][k]))
                .add(&dbdb.mul(duu).scale(0.5 * fixed.coeff_bbu[u][k]));
            chain = chain
                .add(&dadada.mul(duu).scale(fixed.coeff_aaau[u][k] / 6.0))
                .add(&dada.mul(db).mul(duu).scale(0.5 * fixed.coeff_aabu[u][k]))
                .add(&dadb.mul(db).mul(duu).scale(0.5 * fixed.coeff_abbu[u][k]))
                .add(&dbdb.mul(db).mul(duu).scale(fixed.coeff_bbbu[u][k] / 6.0));
            c = c.add(&chain);
        }
        // Slope-axis (`b`) chain with the correct Taylor factorials (the
        // `coeff_*u[g]` pack values are `dc_db`/`dc_dab`/`dc_dbb`/`dc_daab`/
        // `dc_dabb`/`dc_dbbb`; the third-order `aaau/aabu/abbu/bbbu[g]` are 0):
        //   dc_db·db + dc_dab·(da·db) + ½dc_daab·(da²·db)
        //            + ½dc_dbb·db² + ½dc_dabb·(da·db²) + ⅙dc_dbbb·db³.
        // This matches `observed_coeff_component_jet`'s b-terms exactly.
        c = c
            .add(&db.scale(fixed.coeff_u[g_axis][k]))
            .add(&dadb.scale(fixed.coeff_au[g_axis][k]))
            .add(&dada.mul(db).scale(0.5 * fixed.coeff_aau[g_axis][k]))
            .add(&dbdb.scale(0.5 * fixed.coeff_bu[g_axis][k]))
            .add(&dadb.mul(db).scale(0.5 * fixed.coeff_abu[g_axis][k]))
            .add(&dbdb.mul(db).scale(fixed.coeff_bbu[g_axis][k] / 6.0));
        c
    })
}

/// The per-cell `χ = ∂η/∂a` polynomial coefficients `dc_da[k]` (k = 0..4) as
/// jets, the `∂_a`-shifted analogue of [`cell_coeff_jets`]: the cell coefficient
/// family whose base is `dc_da`, whose `a`-derivatives are `dc_daa`/`dc_daaa`,
/// whose per-primary derivatives are `coeff_au`/`coeff_aau` (= `∂(dc_da)/∂u` and
/// `∂²(dc_da)/∂a∂u`), and whose `b`-cross is `coeff_abu` (= `∂²(dc_da)/∂b∂u`).
/// These are the `χ_u`/`χ_uv` chains the hand `first_full` assembles by hand
/// (`chi_u_poly = dc_daa·a_u + coeff_au`); the FlexJet algebra raises them.
fn cell_chi_poly_jets<J: FlexJet>(
    template: &J,
    fixed: &DenestedCellPrimaryFixedPartials,
    g_axis: usize,
    da: &J,
    du: &[J],
) -> [J; 4] {
    let p = du.len();
    let dada = da.mul(da);
    let db = &du[g_axis];
    std::array::from_fn(|k| {
        // Base = dc_da; a-chain = dc_daa·da + ½dc_daaa·da².
        let mut c = const_jet_like(template, fixed.dc_da[k]);
        c = c
            .add(&da.scale(fixed.dc_daa[k]))
            .add(&dada.scale(0.5 * fixed.dc_daaa[k]));
        // Linear axes (u != g): χ per-primary is bilinear in du[u] (factor 1).
        // The slope axis g (= b) is handled separately: there `coeff_abu[g]·db·
        // du[g] = dc_dabb·db²` repeats the b factor and would DOUBLE-count χ's
        // pure-`b²` Taylor term (gam#932 g-diagonal fix, mirroring cell_coeff_jets).
        let dbdb = db.mul(db);
        let dadb = da.mul(db);
        for u in 0..p {
            if u == g_axis {
                continue;
            }
            let duu = &du[u];
            // χ = ∂_a η, so χ's per-primary chain is ∂_a of η's per-primary chain
            // (`cell_coeff_jets`), dropping one a-order:
            //   coeff_au·du + coeff_aau·da·du + coeff_abu·db·du
            //   + ½coeff_aaau·da²·du + coeff_aabu·(da·db)·du + ½coeff_abbu·db²·du.
            // The three second-order terms are zero for a g-only family but
            // NON-zero on h/w channels, where χ_uv's directional (Jet3) / mixed
            // (Jet4) channel needs them — without them χ_uv_dir under-counts
            // (gam#932 ghw gate).
            let chain = duu
                .scale(fixed.coeff_au[u][k])
                .add(&da.mul(duu).scale(fixed.coeff_aau[u][k]))
                .add(&db.mul(duu).scale(fixed.coeff_abu[u][k]))
                .add(&dada.mul(duu).scale(0.5 * fixed.coeff_aaau[u][k]))
                .add(&dadb.mul(duu).scale(fixed.coeff_aabu[u][k]))
                .add(&dbdb.mul(duu).scale(0.5 * fixed.coeff_abbu[u][k]));
            c = c.add(&chain);
        }
        // Slope-axis (b) χ-chain with correct factorials: coeff_au[g]·db +
        // coeff_aau[g]·(da·db) + ½coeff_abu[g]·db²  (= dc_dab·db + dc_daab·da·db
        // + ½dc_dabb·db²); the higher χ b-terms (coeff for b³/a²b on g) are 0.
        c = c
            .add(&db.scale(fixed.coeff_au[g_axis][k]))
            .add(&da.mul(db).scale(fixed.coeff_aau[g_axis][k]))
            .add(&dbdb.scale(0.5 * fixed.coeff_abu[g_axis][k]));
        c
    })
}

/// #932 item-2 Phase C: the per-row density normalization `D = Σ_cells ∫ G0 dz`
/// (`G0 = χ·w`, `w = e^{−q}/2π`) as a jet at any `FlexJet` order, carrying its
/// exact θ-derivatives (the hand D-path `d_u`/`d_uv` are this jet's grad/Hess).
///
/// Per cell `D_cell = INV_TWO_PI · Σ_k χ_k · M_k`, where `χ_k` are the cell's
/// `dc_da` polynomial coefficients as jets ([`cell_chi_poly_jets`]) and `M_k` are
/// the cell's normalization moments as jets ([`base_moment_jets`], carrying both
/// the coefficient motion and the moving-edge sliver). The single-source magic:
/// the hand path forms `d_u` by EXPLICITLY assembling `χ_u − χ·η·η_u` + boundary
/// flux; the jet product `χ_k·M_k` reproduces all three terms automatically —
/// `χ_u` from `χ_k`'s motion, `−χ·η·η_u` from `M_k`'s interior `e^{−Δq}` factor
/// (`∂M_k = −Σ_m(η∂η)_m M_{k+m}`), and the boundary flux from `M_k`'s edge
/// sliver. `c_jets` are the cell's `c0..c3` jets ([`cell_coeff_jets`]) feeding the
/// moment exponent; `edge_l`/`edge_r` the moving edge jets; `moments` the cell's
/// NUMERIC moment vector (≥ `4 + 6` entries for the `e^{−Δq}` expansion).
fn flex_timepoint_d_cell<J: FlexJet>(
    template: &J,
    c_jets: &[J; 4],
    chi_jets: &[J; 4],
    edge_l: &J,
    left_finite: bool,
    edge_r: &J,
    right_finite: bool,
    numeric_moments: &[f64],
) -> J {
    let m = base_moment_jets(
        c_jets,
        edge_l,
        left_finite,
        edge_r,
        right_finite,
        numeric_moments,
    );
    let mut acc = const_jet_like(template, 0.0);
    for (k, chi_k) in chi_jets.iter().enumerate() {
        acc = acc.add(&chi_k.mul(&m[k]));
    }
    acc.scale(std::f64::consts::TAU.recip())
}

/// Evaluate a 4-coefficient cell polynomial jet `Σ_k coeff_jet[k]·z^k` at the
/// fixed observation point `z` (the jet image of `eval_coeff4_at`).
#[inline]
fn eval_coeff_jet_at<J: FlexJet>(coeff_jet: &[J; 4], z: f64) -> J {
    let mut zk = 1.0;
    let mut acc = const_jet_like(&coeff_jet[0], 0.0);
    for c in coeff_jet.iter() {
        acc = acc.add(&c.scale(zk));
        zk *= z;
    }
    acc
}

/// Build the `flex_timepoint_inputs_generic` cell inputs (`CalibrationCellJet
/// Inputs`) for a timepoint from a cached partition — the `cached → jet-inputs`
/// bridge the production cutover will promote. Borrows the cached cells.
fn cells_from_cached(cached: &CachedPartitionCells) -> Vec<CalibrationCellJetInputs<'_>> {
    cached
        .cells
        .iter()
        .map(|entry| {
            let cell = entry.partition_cell.cell;
            CalibrationCellJetInputs {
                base_pos_coeffs: [cell.c0, cell.c1, cell.c2, cell.c3],
                fixed: &entry.fixed,
                cell_left: cell.left,
                cell_right: cell.right,
                left_edge: entry.partition_cell.left_edge,
                right_edge: entry.partition_cell.right_edge,
                numeric_moments: entry.state.moments.as_slice(),
            }
        })
        .collect()
}

/// The OBSERVED-point coefficient + per-primary fixed-partial pack for the generic
/// builder — the observed-point analogue of `denested_cell_primary_fixed_partials`
/// (the calibration cells' pack). Returns `(obs_coeff, obs_fixed)` where:
///   - the `(a,b)` columns (the `g` slope axis) come from `observed_denested_cell
///     _partials` (`coeff_u[g]=dc_db`, `coeff_au[g]=dc_dab`, `coeff_bu[g]=dc_dbb`,
///     `coeff_aau[g]=dc_daab`, `coeff_abu[g]=dc_dabb`, `coeff_bbu[g]=dc_dbbb`),
///   - the score-warp `h` columns from `observed_score_basis_coefficients` at
///     `z_obs` (`coeff_u[h]=b·H(z_obs)`, `coeff_bu[h]=H(z_obs)`; a-independent, so
///     every `a`-cross column is zero),
///   - the link-dev `w` columns from `link_basis_cell_coefficients` at `u_obs`
///     (`coeff_u[w]`) and its first/second/third `(a,b)` partials.
/// Feeding this to `cell_coeff_jets`/`cell_chi_poly_jets` builds the observed
/// `eta`/`chi` as multivariate jets over g/h/w to ALL orders — the same machinery
/// the calibration cells / D path use. `scale` = the probit-frailty scale.
fn observed_fixed_for(
    family: &SurvivalMarginalSlopeFamily,
    primary: &FlexPrimarySlices,
    row: usize,
    a: f64,
    b: f64,
    beta_h: Option<&Array1<f64>>,
    beta_w: Option<&Array1<f64>>,
) -> Result<([f64; 4], DenestedCellPrimaryFixedPartials), String> {
    let r = primary.total;
    let scale = family.probit_frailty_scale();
    let z_obs = family.observed_score_projection(row);
    let u_obs = a + b * z_obs;
    let obs = family.observed_denested_cell_partials(row, a, b, beta_h, beta_w)?;

    let mut coeff_u = vec![[0.0; 4]; r];
    let mut coeff_au = vec![[0.0; 4]; r];
    let mut coeff_bu = vec![[0.0; 4]; r];
    let mut coeff_aau = vec![[0.0; 4]; r];
    let mut coeff_abu = vec![[0.0; 4]; r];
    let mut coeff_bbu = vec![[0.0; 4]; r];
    let mut coeff_aaau = vec![[0.0; 4]; r];
    let mut coeff_aabu = vec![[0.0; 4]; r];
    let mut coeff_abbu = vec![[0.0; 4]; r];
    let mut coeff_bbbu = vec![[0.0; 4]; r];

    // g (slope) axis = the observed (a,b) pack columns.
    coeff_u[primary.g] = obs.dc_db;
    coeff_au[primary.g] = obs.dc_dab;
    coeff_bu[primary.g] = obs.dc_dbb;
    coeff_aau[primary.g] = obs.dc_daab;
    coeff_abu[primary.g] = obs.dc_dabb;
    coeff_bbu[primary.g] = obs.dc_dbbb;

    // h (score-warp) axis: `coeff_h(z_obs) = b·H(z_obs)` — linear in b, a-free.
    if let Some(h_range) = primary.h.as_ref().filter(|_| family.score_warp.is_some()) {
        for local_idx in 0..h_range.len() {
            let idx = h_range.start + local_idx;
            coeff_u[idx] = scale_coeff4(
                family.observed_score_basis_coefficients(row, local_idx, z_obs, b)?,
                scale,
            );
            coeff_bu[idx] = scale_coeff4(
                family.observed_score_basis_coefficients(row, local_idx, z_obs, 1.0)?,
                scale,
            );
        }
    }

    // w (link-dev) axis: `coeff_w = link_basis(u_obs, a, b)` + its (a,b) partials.
    if let (Some(w_range), Some(runtime)) = (primary.w.as_ref(), family.link_dev.as_ref()) {
        for local_idx in 0..w_range.len() {
            let span = runtime.basis_cubic_at(local_idx, u_obs)?;
            let idx = w_range.start + local_idx;
            coeff_u[idx] = scale_coeff4(
                exact_kernel::link_basis_cell_coefficients(span, a, b),
                scale,
            );
            let (dc_aw, dc_bw) = exact_kernel::link_basis_cell_coefficient_partials(span, a, b);
            let (dc_aaw, dc_abw, dc_bbw) =
                exact_kernel::link_basis_cell_second_partials(span, a, b);
            let (dc_aaaw, dc_aabw, dc_abbw, dc_bbbw) =
                exact_kernel::link_basis_cell_third_partials(span);
            coeff_au[idx] = scale_coeff4(dc_aw, scale);
            coeff_bu[idx] = scale_coeff4(dc_bw, scale);
            coeff_aau[idx] = scale_coeff4(dc_aaw, scale);
            coeff_abu[idx] = scale_coeff4(dc_abw, scale);
            coeff_bbu[idx] = scale_coeff4(dc_bbw, scale);
            coeff_aaau[idx] = scale_coeff4(dc_aaaw, scale);
            coeff_aabu[idx] = scale_coeff4(dc_aabw, scale);
            coeff_abbu[idx] = scale_coeff4(dc_abbw, scale);
            coeff_bbbu[idx] = scale_coeff4(dc_bbbw, scale);
        }
    }

    let fixed = DenestedCellPrimaryFixedPartials {
        dc_da: obs.dc_da,
        dc_daa: obs.dc_daa,
        dc_daaa: obs.dc_daaa,
        coeff_u,
        coeff_au,
        coeff_bu,
        coeff_aau,
        coeff_abu,
        coeff_bbu,
        coeff_aaau,
        coeff_aabu,
        coeff_abbu,
        coeff_bbbu,
    };
    Ok((obs.coeff, fixed))
}

impl SurvivalMarginalSlopeFamily {
    /// #932-2 PRODUCTION cutover: the exact timepoint `(eta, chi, d)` value /
    /// gradient / Hessian via the single-source `flex_timepoint_inputs_generic`
    /// jet builder at [`Jet2`]. Independent finite differences pin its value,
    /// gradient, and Hessian channels in `moment_engine_tests`.
    pub(crate) fn compute_survival_timepoint_exact_jet(
        &self,
        row: usize,
        primary: &FlexPrimarySlices,
        q: f64,
        q_index: usize,
        a: f64,
        b: f64,
        beta_h: Option<&Array1<f64>>,
        beta_w: Option<&Array1<f64>>,
        o_infl: f64,
    ) -> Result<SurvivalFlexTimepointExact, String> {
        let cached = self.build_cached_partition(primary, a, b, beta_h, beta_w)?;
        self.compute_survival_timepoint_exact_jet_from_cached(
            row, primary, q, q_index, a, b, beta_h, beta_w, o_infl, &cached,
        )
    }

    /// `compute_survival_timepoint_exact_jet` over a pre-built cached partition.
    pub(crate) fn compute_survival_timepoint_exact_jet_from_cached(
        &self,
        row: usize,
        primary: &FlexPrimarySlices,
        q: f64,
        q_index: usize,
        a: f64,
        b: f64,
        beta_h: Option<&Array1<f64>>,
        beta_w: Option<&Array1<f64>>,
        o_infl: f64,
        cached: &CachedPartitionCells,
    ) -> Result<SurvivalFlexTimepointExact, String> {
        let p = primary.total;
        let d_check = self.evaluate_survival_denom_d(a, b, beta_h, beta_w)?;
        let z_obs = self.observed_score_projection(row);
        let (obs_coeff, obs_fixed) = observed_fixed_for(self, primary, row, a, b, beta_h, beta_w)?;
        let cells = cells_from_cached(cached);

        let template = Jet2::primary(0.0, usize::MAX, p);
        let b_jet = Jet2::primary(b, primary.g, p);
        let du: Vec<Jet2> = (0..p).map(|u| Jet2::primary(0.0, u, p)).collect();
        let q_jet = add_const(&du[q_index], q);
        let (eta, chi, d) = flex_timepoint_inputs_generic(
            &template,
            &b_jet,
            &du,
            a,
            d_check,
            primary.g,
            primary.infl,
            &q_jet,
            &const_jet_like(&template, 1.0),
            z_obs,
            o_infl,
            obs_coeff,
            &obs_fixed,
            &cells,
        )?;

        let to_g = |j: &Jet2| Array1::from(j.g.clone());
        let to_h = |j: &Jet2| -> Result<Array2<f64>, String> {
            Array2::from_shape_vec((p, p), j.h.clone()).map_err(|e| e.to_string())
        };
        Ok(SurvivalFlexTimepointExact {
            eta: eta.value(),
            chi: chi.value(),
            d: d.value(),
            eta_u: to_g(&eta),
            eta_uv: to_h(&eta)?,
            chi_u: to_g(&chi),
            chi_uv: to_h(&chi)?,
            d_u: to_g(&d),
            d_uv: to_h(&d)?,
        })
    }

    /// #932 grad-only single-source: the exact timepoint `(eta, chi, d)` VALUE +
    /// GRADIENT via the SAME single-source `flex_timepoint_inputs_generic` jet
    /// builder as [`Self::compute_survival_timepoint_exact_jet`], instantiated at
    /// [`Jet1`] (no second-order channel). This replaces the hand first-order
    /// cell-moment / IFT `a_u` / moving-flux `d_u` / `ρ`-`τ` `eta_u`/`chi_u`
    /// assembly that used to live in `first_full`: there is now ONE definition of
    /// the flex timepoint geometry, and the grad-only path is its order-≤1
    /// truncation. Because `Jet1` shares `add`/`sub`/`mul`/`scale`/`compose_unary`
    /// and the `moment_term` gradient line with `Jet2` op-for-op, the returned
    /// value/gradient are bit-identical to the [`Jet2`] path's base + gradient
    /// channels; the identity is pinned by
    /// `flex_timepoint_first_order_matches_jet2_and_fd_932`.
    pub(crate) fn compute_survival_timepoint_first_order_exact(
        &self,
        row: usize,
        primary: &FlexPrimarySlices,
        q: f64,
        q_index: usize,
        a: f64,
        b: f64,
        beta_h: Option<&Array1<f64>>,
        beta_w: Option<&Array1<f64>>,
        o_infl: f64,
    ) -> Result<SurvivalFlexTimepointFirstOrderExact, String> {
        let cached = self.build_cached_partition(primary, a, b, beta_h, beta_w)?;
        let p = primary.total;
        let d_check = self.evaluate_survival_denom_d(a, b, beta_h, beta_w)?;
        let z_obs = self.observed_score_projection(row);
        let (obs_coeff, obs_fixed) = observed_fixed_for(self, primary, row, a, b, beta_h, beta_w)?;
        let cells = cells_from_cached(&cached);

        let template = Jet1::primary(0.0, usize::MAX, p);
        let b_jet = Jet1::primary(b, primary.g, p);
        let du: Vec<Jet1> = (0..p).map(|u| Jet1::primary(0.0, u, p)).collect();
        let q_jet = add_const(&du[q_index], q);
        let (eta, chi, d) = flex_timepoint_inputs_generic(
            &template,
            &b_jet,
            &du,
            a,
            d_check,
            primary.g,
            primary.infl,
            &q_jet,
            &const_jet_like(&template, 1.0),
            z_obs,
            o_infl,
            obs_coeff,
            &obs_fixed,
            &cells,
        )?;

        let to_g = |j: &Jet1| Array1::from(j.g.clone());
        Ok(SurvivalFlexTimepointFirstOrderExact {
            eta: eta.value(),
            chi: chi.value(),
            d: d.value(),
            eta_u: to_g(&eta),
            chi_u: to_g(&chi),
            d_u: to_g(&d),
        })
    }
}

// #932-2 increment 2: Jet3 directional and Jet4 mixed-second-directional
// channels instantiate the same Euler-generated `j/(j+m)` projector as the
// order-one/two and nested-dual algebras.

impl SurvivalMarginalSlopeFamily {
    /// #932-2 PRODUCTION cutover (increment 2): the directional timepoint
    /// extension `D_dir(eta_u/eta_uv/chi_u/chi_uv/d_u/d_uv)` via the single-source
    /// `flex_timepoint_inputs_generic` jet builder at [`Jet3`] (one nilpotent ε
    /// seed = the contraction direction). Returns the directional pack
    /// directly (the ε channel `.eps.g`/`.eps.h` of the `(eta, chi, d)` jets).
    /// The row-level contracted tensor is pinned by independent rigid-tower and
    /// finite-difference witnesses.
    pub(crate) fn compute_survival_timepoint_directional_jet_from_cached(
        &self,
        row: usize,
        primary: &FlexPrimarySlices,
        q: f64,
        q_index: usize,
        a: f64,
        b: f64,
        beta_h: Option<&Array1<f64>>,
        beta_w: Option<&Array1<f64>>,
        o_infl: f64,
        cached: &CachedPartitionCells,
        dir: &Array1<f64>,
        arena: &DynamicJetArena,
    ) -> Result<(FlexTimepointBasePack, FlexTimepointDirectionalPack), String> {
        let p = primary.total;
        let d_check = self.evaluate_survival_denom_d(a, b, beta_h, beta_w)?;
        let z_obs = self.observed_score_projection(row);
        let (obs_coeff, obs_fixed) = observed_fixed_for(self, primary, row, a, b, beta_h, beta_w)?;
        let cells = cells_from_cached(cached);

        macro_rules! evaluate {
            ($template:expr, $b_jet:expr, $du:expr) => {{
                let template = $template;
                let b_jet = $b_jet;
                let du = $du;
                let q_jet = add_const(&du[q_index], q);
                let (eta, chi, d) = flex_timepoint_inputs_generic(
                    &template,
                    &b_jet,
                    &du,
                    a,
                    d_check,
                    primary.g,
                    primary.infl,
                    &q_jet,
                    &const_jet_like(&template, 1.0),
                    z_obs,
                    o_infl,
                    obs_coeff,
                    &obs_fixed,
                    &cells,
                )?;
                Ok(FlexThirdOutput::pack_timepoint_outputs(&eta, &chi, &d))
            }};
        }

        match p {
            8 => evaluate!(
                FixedJet3::<8>::primary(0.0, usize::MAX, p, 0.0),
                FixedJet3::<8>::primary(b, primary.g, p, dir[primary.g]),
                (0..p)
                    .map(|axis| FixedJet3::<8>::primary(0.0, axis, p, dir[axis]))
                    .collect::<Vec<_>>()
            ),
            _ => evaluate!(
                ArenaJet3::primary(0.0, usize::MAX, p, 0.0, arena),
                ArenaJet3::primary(b, primary.g, p, dir[primary.g], arena),
                (0..p)
                    .map(|axis| ArenaJet3::primary(0.0, axis, p, dir[axis], arena))
                    .collect::<Vec<_>>()
            ),
        }
    }

    /// #932-2 PRODUCTION cutover (increment 2): the mixed second-directional
    /// timepoint extension `D_{d1} D_{d2}(eta_uv/chi_uv/d_uv)` via the single-source
    /// builder at [`Jet4`] (two nilpotent seeds ε = `dir1`, δ = `dir2`). Returns the
    /// bidirectional pack directly (the εδ-Hessian channel `.eps_del.h`).
    /// Nested-dual and scalar finite-difference gates independently pin this
    /// fourth-order channel.
    pub(crate) fn compute_survival_timepoint_bidirectional_jet_from_cached(
        &self,
        row: usize,
        primary: &FlexPrimarySlices,
        q: f64,
        q_index: usize,
        a: f64,
        b: f64,
        beta_h: Option<&Array1<f64>>,
        beta_w: Option<&Array1<f64>>,
        cached: &CachedPartitionCells,
        dir1: &Array1<f64>,
        dir2: &Array1<f64>,
    ) -> Result<FlexTimepointBidirectionalPack, String> {
        let p = primary.total;
        let d_check = self.evaluate_survival_denom_d(a, b, beta_h, beta_w)?;
        let z_obs = self.observed_score_projection(row);
        let (obs_coeff, obs_fixed) = observed_fixed_for(self, primary, row, a, b, beta_h, beta_w)?;
        let cells = cells_from_cached(cached);

        let template = Jet4::primary(0.0, usize::MAX, p, 0.0, 0.0);
        let b_jet = Jet4::primary(b, primary.g, p, dir1[primary.g], dir2[primary.g]);
        let du: Vec<Jet4> = (0..p)
            .map(|u| Jet4::primary(0.0, u, p, dir1[u], dir2[u]))
            .collect();
        let q_jet = add_const(&du[q_index], q);
        let (eta, chi, d) = flex_timepoint_inputs_generic(
            &template,
            &b_jet,
            &du,
            a,
            d_check,
            primary.g,
            primary.infl,
            &q_jet,
            &const_jet_like(&template, 1.0),
            z_obs,
            0.0,
            obs_coeff,
            &obs_fixed,
            &cells,
        )?;

        Ok(FlexTimepointBidirectionalPack {
            eta_uv_uv: eta.eps_del.h.clone(),
            chi_uv_uv: chi.eps_del.h.clone(),
            d_uv_uv: d.eps_del.h.clone(),
        })
    }
}

struct FlexFamilyCoefficientJets<J: FlexCoefficientJet> {
    template: Dual2<J>,
    q0: Dual2<J>,
    q1: Dual2<J>,
    qd1: Dual2<J>,
    g: Dual2<J>,
    scale_ratio: Dual2<J>,
    du: Vec<Dual2<J>>,
    o_infl: f64,
}

enum FlexCoefficientRowDirection<'a> {
    /// Move the canonical flattened coefficient vector while holding every
    /// coefficient-to-row map fixed.
    Beta(&'a Array1<f64>),
    /// Move one coefficient-to-row design map.  The epsilon seed owns both
    /// `X_psi beta` and `X_psi`, so the resulting Jet3 channel includes the
    /// derivative of the score/Hessian pullback, not only row-value motion.
    Design {
        block: usize,
        derivative_row: &'a Array1<f64>,
        beta: &'a Array1<f64>,
        coefficient_range: std::ops::Range<usize>,
    },
}

fn add_coefficient_row(
    gradient: &mut [f64],
    range: &std::ops::Range<usize>,
    row: ndarray::ArrayView1<'_, f64>,
    channel: &str,
) -> Result<(), String> {
    if range.len() != row.len() {
        return Err(format!(
            "survival marginal-slope FLEX family {channel} coefficient row width {} != flattened range width {}",
            row.len(),
            range.len(),
        ));
    }
    for (axis, value) in range.clone().zip(row.iter().copied()) {
        gradient[axis] += value;
    }
    Ok(())
}

fn lifted_coefficient_affine<J: FlexCoefficientJet>(
    value: f64,
    gradient: Vec<f64>,
    coefficient_direction: Option<&FlexCoefficientRowDirection<'_>>,
    design_affected: bool,
    family_first: f64,
    family_second: f64,
) -> Dual2<J> {
    let dimension = gradient.len();
    let mut directional_gradient = vec![0.0; dimension];
    let directional_value = match coefficient_direction {
        None => 0.0,
        Some(FlexCoefficientRowDirection::Beta(direction)) => gradient
            .iter()
            .zip(direction.iter())
            .map(|(&coefficient, &step)| coefficient * step)
            .sum(),
        Some(FlexCoefficientRowDirection::Design {
            derivative_row,
            beta,
            coefficient_range,
            ..
        }) if design_affected => {
            for (axis, value) in coefficient_range
                .clone()
                .zip(derivative_row.iter().copied())
            {
                directional_gradient[axis] = value;
            }
            derivative_row.dot(*beta)
        }
        Some(FlexCoefficientRowDirection::Design { .. }) => 0.0,
    };
    Dual2 {
        v: J::affine(value, gradient, directional_value, directional_gradient),
        g: J::constant(family_first, dimension),
        h: J::constant(family_second, dimension),
    }
}

fn one_hot_coefficient_gradient(dimension: usize, axis: usize) -> Vec<f64> {
    let mut gradient = vec![0.0; dimension];
    gradient[axis] = 1.0;
    gradient
}

impl SurvivalMarginalSlopeFamily {
    fn validate_flex_family_coefficient_state(
        &self,
        row: usize,
        block_states: &[ParameterBlockState],
        slices: &BlockSlices,
        first: FlexFamilyRowDirection,
        second: FlexFamilyRowDirection,
        coefficient_direction: Option<&FlexCoefficientRowDirection<'_>>,
    ) -> Result<(), String> {
        if row >= self.n {
            return Err(format!(
                "survival marginal-slope FLEX family row {row} is out of range for n={}",
                self.n
            ));
        }
        let directions = [
            first.entry,
            first.exit,
            first.derivative_exit,
            first.probit_scale,
            second.entry,
            second.exit,
            second.derivative_exit,
            second.probit_scale,
        ];
        if directions.iter().any(|value| !value.is_finite()) {
            return Err(
                "survival marginal-slope FLEX family row directions must be finite".to_string(),
            );
        }
        match coefficient_direction {
            Some(FlexCoefficientRowDirection::Beta(direction)) => {
                if direction.len() != slices.total {
                    return Err(format!(
                        "survival marginal-slope FLEX family beta direction length {} != flattened coefficient width {}",
                        direction.len(),
                        slices.total,
                    ));
                }
                if direction.iter().any(|value| !value.is_finite()) {
                    return Err(
                        "survival marginal-slope FLEX family beta direction must be finite"
                            .to_string(),
                    );
                }
            }
            Some(FlexCoefficientRowDirection::Design {
                block,
                derivative_row,
                beta,
                coefficient_range,
            }) => {
                if !matches!(*block, 1 | 2) {
                    return Err(format!(
                        "survival marginal-slope FLEX family design direction supports marginal/logslope blocks 1 or 2, got block {block}"
                    ));
                }
                let expected_range = if *block == 1 {
                    &slices.marginal
                } else {
                    &slices.logslope
                };
                if coefficient_range != expected_range {
                    return Err(format!(
                        "survival marginal-slope FLEX family design direction block {block} range {:?} != canonical {:?}",
                        coefficient_range, expected_range,
                    ));
                }
                if derivative_row.len() != coefficient_range.len()
                    || beta.len() != coefficient_range.len()
                {
                    return Err(format!(
                        "survival marginal-slope FLEX family design direction block {block} widths disagree: derivative={}, beta={}, range={}",
                        derivative_row.len(),
                        beta.len(),
                        coefficient_range.len(),
                    ));
                }
                if coefficient_range.end > slices.total {
                    return Err(format!(
                        "survival marginal-slope FLEX family design direction range {:?} exceeds flattened width {}",
                        coefficient_range, slices.total,
                    ));
                }
                if derivative_row.iter().any(|value| !value.is_finite()) {
                    return Err(
                        "survival marginal-slope FLEX family design derivative row must be finite"
                            .to_string(),
                    );
                }
            }
            None => {}
        }

        let mut expected = vec![
            ("time", slices.time.clone()),
            ("marginal", slices.marginal.clone()),
            ("logslope", slices.logslope.clone()),
        ];
        if let Some(range) = slices.score_warp.as_ref() {
            expected.push(("score warp", range.clone()));
        }
        if let Some(range) = slices.link_dev.as_ref() {
            expected.push(("link deviation", range.clone()));
        }
        if let Some(range) = slices.influence.as_ref() {
            expected.push(("influence", range.clone()));
        }
        if block_states.len() != expected.len() {
            return Err(format!(
                "survival marginal-slope FLEX family coefficient map expects {} block states, got {}",
                expected.len(),
                block_states.len(),
            ));
        }
        for (block_index, (block_state, (name, range))) in
            block_states.iter().zip(expected.iter()).enumerate()
        {
            if block_state.beta.len() != range.len() {
                return Err(format!(
                    "survival marginal-slope FLEX family {name} block {block_index} beta width {} != layout width {}",
                    block_state.beta.len(),
                    range.len(),
                ));
            }
        }
        for (block, name) in [(0usize, "time"), (1, "marginal"), (2, "logslope")] {
            if block_states[block].eta.len() <= row {
                return Err(format!(
                    "survival marginal-slope FLEX family {name} block eta length {} does not contain row {row}",
                    block_states[block].eta.len(),
                ));
            }
        }
        Ok(())
    }

    fn build_flex_family_coefficient_jets<J: FlexCoefficientJet>(
        &self,
        row: usize,
        block_states: &[ParameterBlockState],
        primary: &FlexPrimarySlices,
        slices: &BlockSlices,
        first: FlexFamilyRowDirection,
        second: FlexFamilyRowDirection,
        coefficient_direction: Option<&FlexCoefficientRowDirection<'_>>,
    ) -> Result<FlexFamilyCoefficientJets<J>, String> {
        let dimension = slices.total;
        let design_targets_marginal = matches!(
            coefficient_direction,
            Some(FlexCoefficientRowDirection::Design { block: 1, .. })
        );
        let design_targets_logslope = matches!(
            coefficient_direction,
            Some(FlexCoefficientRowDirection::Design { block: 2, .. })
        );
        let q_values = self.row_dynamic_q_values(row, block_states)?;
        let time_entry_chunk = self
            .design_entry
            .try_row_chunk(row..row + 1)
            .map_err(|error| format!("FLEX family design_entry row: {error}"))?;
        let time_exit_chunk = self
            .design_exit
            .try_row_chunk(row..row + 1)
            .map_err(|error| format!("FLEX family design_exit row: {error}"))?;
        let time_derivative_chunk = self
            .design_derivative_exit
            .try_row_chunk(row..row + 1)
            .map_err(|error| format!("FLEX family design_derivative_exit row: {error}"))?;
        let marginal_chunk = self
            .marginal_design
            .try_row_chunk(row..row + 1)
            .map_err(|error| format!("FLEX family marginal_design row: {error}"))?;
        let logslope_chunk = self
            .logslope_layout
            .coefficient_design()
            .try_row_chunk(row..row + 1)
            .map_err(|error| format!("FLEX family logslope design row: {error}"))?;
        let entry_row = time_entry_chunk.row(0);
        let exit_row = time_exit_chunk.row(0);
        let derivative_row = time_derivative_chunk.row(0);
        let marginal_row = marginal_chunk.row(0);
        let logslope_row = logslope_chunk.row(0);

        let mut q0_gradient = vec![0.0; dimension];
        let mut q1_gradient = vec![0.0; dimension];
        let mut qd1_gradient = vec![0.0; dimension];
        let (q0, q1, qd1) = if self.flex_timewiggle_active() {
            let time_tail = self.time_wiggle_range();
            let base_width = time_tail.start;
            let base_range = slices.time.start..slices.time.start + base_width;
            add_coefficient_row(
                &mut q0_gradient,
                &base_range,
                entry_row.slice(s![..base_width]),
                "timewiggle entry base",
            )?;
            add_coefficient_row(
                &mut q1_gradient,
                &base_range,
                exit_row.slice(s![..base_width]),
                "timewiggle exit base",
            )?;
            add_coefficient_row(
                &mut qd1_gradient,
                &base_range,
                derivative_row.slice(s![..base_width]),
                "timewiggle derivative base",
            )?;
            add_coefficient_row(
                &mut q0_gradient,
                &slices.marginal,
                marginal_row,
                "timewiggle entry marginal",
            )?;
            add_coefficient_row(
                &mut q1_gradient,
                &slices.marginal,
                marginal_chunk.row(0),
                "timewiggle exit marginal",
            )?;

            let beta_time = &block_states[0].beta;
            let beta_time_base = beta_time.slice(s![..base_width]);
            let beta_time_wiggle = beta_time.slice(s![time_tail.clone()]);
            let h0 = entry_row.slice(s![..base_width]).dot(&beta_time_base)
                + self.offset_entry[row]
                + block_states[1].eta[row];
            let h1 = exit_row.slice(s![..base_width]).dot(&beta_time_base)
                + self.offset_exit[row]
                + block_states[1].eta[row];
            let d_raw = derivative_row.slice(s![..base_width]).dot(&beta_time_base)
                + self.derivative_offset_exit[row];
            let h0_jet = lifted_coefficient_affine::<J>(
                h0,
                q0_gradient,
                coefficient_direction,
                design_targets_marginal,
                first.entry,
                second.entry,
            );
            let h1_jet = lifted_coefficient_affine::<J>(
                h1,
                q1_gradient,
                coefficient_direction,
                design_targets_marginal,
                first.exit,
                second.exit,
            );
            let d_raw_jet = lifted_coefficient_affine::<J>(
                d_raw,
                qd1_gradient,
                coefficient_direction,
                false,
                first.derivative_exit,
                second.derivative_exit,
            );
            let beta_wiggle_jets: Vec<Dual2<J>> = time_tail
                .clone()
                .map(|local_axis| {
                    lifted_coefficient_affine::<J>(
                        beta_time[local_axis],
                        one_hot_coefficient_gradient(dimension, slices.time.start + local_axis),
                        coefficient_direction,
                        false,
                        0.0,
                        0.0,
                    )
                })
                .collect();
            let (entry_geometry, entry_basis_d5) = self
                .time_wiggle_geometry_with_basis_d5(
                    Array1::from_vec(vec![h0]).view(),
                    beta_time_wiggle,
                )?
                .ok_or_else(|| {
                    "FLEX family timewiggle entry geometry is unavailable".to_string()
                })?;
            let (exit_geometry, exit_basis_d5) = self
                .time_wiggle_geometry_with_basis_d5(
                    Array1::from_vec(vec![h1]).view(),
                    beta_time.slice(s![time_tail]),
                )?
                .ok_or_else(|| "FLEX family timewiggle exit geometry is unavailable".to_string())?;
            let entry_basis =
                TimewiggleBasisDerivativeRows::from_geometry(&entry_geometry, &entry_basis_d5, 0);
            let exit_basis =
                TimewiggleBasisDerivativeRows::from_geometry(&exit_geometry, &exit_basis_d5, 0);
            let q = timewiggle_q_from_basis_derivative_rows(
                &h0_jet,
                &h1_jet,
                &d_raw_jet,
                &beta_wiggle_jets,
                &entry_basis,
                &exit_basis,
                TimewiggleQBaseValues {
                    q0: q_values.q0,
                    q1: q_values.q1,
                    dq1_dh1: exit_geometry.dq_dq0[0],
                },
            )?;
            if q.q0.value().to_bits() != q_values.q0.to_bits()
                || q.q1.value().to_bits() != q_values.q1.to_bits()
                || q.qd1.value().to_bits() != q_values.qd1.to_bits()
            {
                return Err(
                    "FLEX family generic timewiggle q values drifted from the current f64 row"
                        .to_string(),
                );
            }
            (q.q0, q.q1, q.qd1)
        } else {
            add_coefficient_row(&mut q0_gradient, &slices.time, entry_row, "entry time")?;
            add_coefficient_row(&mut q1_gradient, &slices.time, exit_row, "exit time")?;
            add_coefficient_row(
                &mut qd1_gradient,
                &slices.time,
                derivative_row,
                "derivative time",
            )?;
            add_coefficient_row(
                &mut q0_gradient,
                &slices.marginal,
                marginal_row,
                "entry marginal",
            )?;
            add_coefficient_row(
                &mut q1_gradient,
                &slices.marginal,
                marginal_chunk.row(0),
                "exit marginal",
            )?;
            (
                lifted_coefficient_affine::<J>(
                    q_values.q0,
                    q0_gradient,
                    coefficient_direction,
                    design_targets_marginal,
                    first.entry,
                    second.entry,
                ),
                lifted_coefficient_affine::<J>(
                    q_values.q1,
                    q1_gradient,
                    coefficient_direction,
                    design_targets_marginal,
                    first.exit,
                    second.exit,
                ),
                lifted_coefficient_affine::<J>(
                    q_values.qd1,
                    qd1_gradient,
                    coefficient_direction,
                    false,
                    first.derivative_exit,
                    second.derivative_exit,
                ),
            )
        };

        let mut g_gradient = vec![0.0; dimension];
        add_coefficient_row(&mut g_gradient, &slices.logslope, logslope_row, "logslope")?;
        let g = lifted_coefficient_affine::<J>(
            block_states[2].eta[row],
            g_gradient,
            coefficient_direction,
            design_targets_logslope,
            0.0,
            0.0,
        );
        let zero =
            || lifted_coefficient_affine::<J>(0.0, vec![0.0; dimension], None, false, 0.0, 0.0);
        let template = zero();
        let mut du = vec![template.clone(); primary.total];
        du[primary.q0] = tangent_jet(&q0);
        du[primary.q1] = tangent_jet(&q1);
        du[primary.qd1] = tangent_jet(&qd1);
        du[primary.g] = tangent_jet(&g);

        if let (Some(primary_range), Some(coefficient_range), Some(beta_h)) = (
            primary.h.as_ref(),
            slices.score_warp.as_ref(),
            self.flex_score_beta(block_states)?,
        ) {
            if primary_range.len() != coefficient_range.len() {
                return Err("FLEX family score-warp primary/coefficient widths differ".to_string());
            }
            for local_axis in 0..primary_range.len() {
                let coefficient_axis = coefficient_range.start + local_axis;
                let coefficient = lifted_coefficient_affine::<J>(
                    beta_h[local_axis],
                    one_hot_coefficient_gradient(dimension, coefficient_axis),
                    coefficient_direction,
                    false,
                    0.0,
                    0.0,
                );
                du[primary_range.start + local_axis] = tangent_jet(&coefficient);
            }
        }
        if let (Some(primary_range), Some(coefficient_range), Some(beta_w)) = (
            primary.w.as_ref(),
            slices.link_dev.as_ref(),
            self.flex_link_beta(block_states)?,
        ) {
            if primary_range.len() != coefficient_range.len() {
                return Err(
                    "FLEX family link-deviation primary/coefficient widths differ".to_string(),
                );
            }
            for local_axis in 0..primary_range.len() {
                let coefficient_axis = coefficient_range.start + local_axis;
                let coefficient = lifted_coefficient_affine::<J>(
                    beta_w[local_axis],
                    one_hot_coefficient_gradient(dimension, coefficient_axis),
                    coefficient_direction,
                    false,
                    0.0,
                    0.0,
                );
                du[primary_range.start + local_axis] = tangent_jet(&coefficient);
            }
        }

        let o_infl = self.influence_index_offset(row, block_states)?;
        if let (Some(primary_axis), Some(coefficient_range), Some(influence)) = (
            primary.infl,
            slices.influence.as_ref(),
            self.influence_absorber.as_ref(),
        ) {
            let mut influence_gradient = vec![0.0; dimension];
            add_coefficient_row(
                &mut influence_gradient,
                coefficient_range,
                influence.row(row),
                "influence",
            )?;
            let influence_jet = lifted_coefficient_affine::<J>(
                o_infl,
                influence_gradient,
                coefficient_direction,
                false,
                0.0,
                0.0,
            );
            du[primary_axis] = tangent_jet(&influence_jet);
        }

        let probit_scale = self.probit_frailty_scale();
        if !probit_scale.is_finite() || probit_scale <= 0.0 {
            return Err(format!(
                "survival marginal-slope FLEX family probit scale must be finite and positive, got {probit_scale}"
            ));
        }
        let scale_ratio = Dual2 {
            v: J::constant(1.0, dimension),
            g: J::constant(first.probit_scale / probit_scale, dimension),
            h: J::constant(second.probit_scale / probit_scale, dimension),
        };
        Ok(FlexFamilyCoefficientJets {
            template,
            q0,
            q1,
            qd1,
            g,
            scale_ratio,
            du,
            o_infl,
        })
    }

    fn flex_family_direction_row_terms_generic<J: FlexCoefficientJet>(
        &self,
        row: usize,
        block_states: &[ParameterBlockState],
        first: FlexFamilyRowDirection,
        second: FlexFamilyRowDirection,
        coefficient_direction: Option<&FlexCoefficientRowDirection<'_>>,
    ) -> Result<FlexFamilyDirectionRowTerms, String> {
        self.ensure_scalar_flex_exact_score_geometry("FLEX family-direction row program")?;
        let expected_blocks = 3
            + usize::from(self.score_warp.is_some())
            + usize::from(self.link_dev.is_some())
            + usize::from(self.influence_absorber.is_some());
        if block_states.len() != expected_blocks {
            return Err(format!(
                "survival marginal-slope FLEX family coefficient map expects {expected_blocks} block states, got {}",
                block_states.len(),
            ));
        }
        let primary = flex_primary_slices(self);
        let slices = block_slices(self, block_states);
        self.validate_flex_family_coefficient_state(
            row,
            block_states,
            &slices,
            first,
            second,
            coefficient_direction,
        )?;
        let jets = self.build_flex_family_coefficient_jets::<J>(
            row,
            block_states,
            &primary,
            &slices,
            first,
            second,
            coefficient_direction,
        )?;
        if survival_derivative_guard_violated(jets.qd1.value(), self.derivative_guard) {
            return Err(SurvivalMarginalSlopeError::MonotonicityViolation {
                reason: format!(
                    "survival marginal-slope monotonicity violated at row {row}: qd1={:.3e} < guard={:.3e}",
                    jets.qd1.value(),
                    self.derivative_guard,
                ),
            }
            .into());
        }

        let g_value = jets.g.value();
        let beta_h = self.flex_score_beta(block_states)?;
        let beta_w = self.flex_link_beta(block_states)?;
        let (a0, _) = self.solve_row_survival_intercept_with_slot(
            jets.q0.value(),
            g_value,
            beta_h,
            beta_w,
            Some((row, SurvivalInterceptSlotKind::Entry)),
        )?;
        let (a1, _) = self.solve_row_survival_intercept_with_slot(
            jets.q1.value(),
            g_value,
            beta_h,
            beta_w,
            Some((row, SurvivalInterceptSlotKind::Exit)),
        )?;
        let entry_cached = self.build_cached_partition(&primary, a0, g_value, beta_h, beta_w)?;
        let exit_cached = self.build_cached_partition(&primary, a1, g_value, beta_h, beta_w)?;
        let evaluate_timepoint =
            |q: &Dual2<J>, a: f64, cached: &CachedPartitionCells| -> Result<_, String> {
                let d_check = self.evaluate_survival_denom_d(a, g_value, beta_h, beta_w)?;
                let (obs_coeff, obs_fixed) =
                    observed_fixed_for(self, &primary, row, a, g_value, beta_h, beta_w)?;
                let cells = cells_from_cached(cached);
                flex_timepoint_inputs_generic(
                    &jets.template,
                    &jets.g,
                    &jets.du,
                    a,
                    d_check,
                    primary.g,
                    primary.infl,
                    q,
                    &jets.scale_ratio,
                    self.observed_score_projection(row),
                    jets.o_infl,
                    obs_coeff,
                    &obs_fixed,
                    &cells,
                )
            };
        let (eta0, _, _) = evaluate_timepoint(&jets.q0, a0, &entry_cached)?;
        let (eta1, chi1, d1) = evaluate_timepoint(&jets.q1, a1, &exit_cached)?;
        if !chi1.value().is_finite() || chi1.value() <= 0.0 {
            return Err(SurvivalMarginalSlopeError::NumericalFailure {
                reason: format!(
                    "survival marginal-slope row {row} produced non-positive observed chi1={:.3e}",
                    chi1.value(),
                ),
            }
            .into());
        }
        let output = flex_row_nll(
            &eta0,
            &eta1,
            &chi1,
            &d1,
            &jets.q1,
            &jets.qd1,
            surv_stack(eta0.value())?,
            surv_stack(eta1.value())?,
            self.weights[row],
            self.event[row],
        );
        Ok(FlexFamilyDirectionRowTerms {
            first: output.g.owned_base_terms(),
            second: output.h.owned_base_terms(),
            directional: output.g.owned_directional_terms(),
        })
    }

    /// Evaluate one complete FLEX row under one arbitrary family direction.
    ///
    /// The inner width is the canonical flattened coefficient layout
    /// `time | marginal | logslope | score-warp? | link-dev? | influence?`.
    /// Consequently `first.gradient` is the complete family-by-coefficient
    /// mixed-partial row in one evaluation.  This is distinct from a
    /// family-by-design-hyper partial: the latter must use
    /// [`Self::flex_family_design_direction_row_terms`] so `X_psi beta` and
    /// the `X_psi` pullback drift are both represented.
    /// The outer [`Dual2`] owns the supplied family first/second motion. With no
    /// beta direction the row runs as `Dual2<Jet2>`; with one it runs as
    /// `Dual2<Jet3>` and returns the exact directional drift of the first family
    /// value/score/Hessian channel. Baseline offsets, nonlinear time wiggle,
    /// learned probit scale, calibration, moving moments, and the row likelihood
    /// are all evaluated by this one program.
    pub(crate) fn flex_family_direction_row_terms(
        &self,
        row: usize,
        block_states: &[ParameterBlockState],
        first: FlexFamilyRowDirection,
        second: FlexFamilyRowDirection,
        beta_direction: Option<&Array1<f64>>,
    ) -> Result<FlexFamilyDirectionRowTerms, String> {
        if let Some(beta_direction) = beta_direction {
            let coefficient_direction = FlexCoefficientRowDirection::Beta(beta_direction);
            self.flex_family_direction_row_terms_generic::<Jet3>(
                row,
                block_states,
                first,
                second,
                Some(&coefficient_direction),
            )
        } else {
            self.flex_family_direction_row_terms_generic::<Jet2>(
                row,
                block_states,
                first,
                second,
                None,
            )
        }
    }

    /// Evaluate the derivative of the complete family row channel with respect
    /// to one marginal/logslope design coordinate at fixed coefficients.
    ///
    /// `derivative_row` is one row of `X_psi`.  Its Jet3 epsilon part is seeded
    /// with both `X_psi beta` and the coefficient gradient `X_psi`; therefore
    /// `directional` includes `X_psi^T score` and both Hessian pullback-map
    /// drift terms automatically, including their nonlinear time-wiggle
    /// composition.
    pub(crate) fn flex_family_design_direction_row_terms(
        &self,
        row: usize,
        block_states: &[ParameterBlockState],
        first: FlexFamilyRowDirection,
        second: FlexFamilyRowDirection,
        block: usize,
        derivative_row: &Array1<f64>,
    ) -> Result<FlexFamilyDirectionRowTerms, String> {
        let slices = block_slices(self, block_states);
        let (beta, coefficient_range) = match block {
            1 => (&block_states[1].beta, slices.marginal),
            2 => (&block_states[2].beta, slices.logslope),
            _ => {
                return Err(format!(
                    "survival marginal-slope FLEX family design direction supports marginal/logslope blocks 1 or 2, got block {block}"
                ));
            }
        };
        let coefficient_direction = FlexCoefficientRowDirection::Design {
            block,
            derivative_row,
            beta,
            coefficient_range,
        };
        self.flex_family_direction_row_terms_generic::<Jet3>(
            row,
            block_states,
            first,
            second,
            Some(&coefficient_direction),
        )
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// #932 nested-dual ORACLE instantiation of the single-source flex geometry.
//
// `gam_math::nested_dual::Dual22 = Dual2<Dual2<f64>>` carries a truncation-FREE
// forward-over-forward derivative in TWO independent scalar directions `(s, t)`,
// each to 2nd order (2 + 2 = 4th-order bidirectional). Instantiating the SAME
// `flex_timepoint_inputs_generic` geometry over it — with every primary seeded
// as `base_i + s·d1_i + t·d2_i` — makes the `∂²_s ∂²_t` channel (`channels()[8]`)
// equal to the full arbitrary-weight bidirectional contraction
//   Σ_abcd ℓ_abcd · d1_a d1_b d2_c d2_d
// via a DIFFERENT composition ordering than the production p-primary `Jet4`.
// This is the truncation-free replacement for the flex jet4 bidirectional's
// scalar-FD sanity gate (the last FD-limited seam in the #932 tower). It is an
// ORACLE only — never used on the production sweep — so it lives beside, not
// inside, the p-primary jet types.
use gam_math::nested_dual::{Dual2, JetField};

#[cfg(test)]
mod moment_engine_tests {
    use super::*;
    use crate::cubic_cell_kernel::{DenestedCubicCell, reduce_sextic_moments};
    use crate::marginal_slope_shared::eval_coeff4_at;
    use gam_math::nested_dual::Dual22;
    use std::hint::black_box;
    use std::time::Instant;

    #[test]
    fn dual2_flexjet_scales_runtime_channels_by_total_homogeneous_order() {
        let factors = [2.0, 3.0, 5.0, 7.0, 11.0];
        let original = Dual2 {
            v: Jet2::from_parts(1.0, &[2.0, 3.0], &[4.0, 5.0, 6.0, 7.0]),
            g: Jet2::from_parts(8.0, &[9.0, 10.0], &[11.0, 12.0, 13.0, 14.0]),
            h: Jet2::from_parts(15.0, &[16.0, 17.0], &[18.0, 19.0, 20.0, 21.0]),
        };
        let scaled = original.scale_homogeneous_orders(factors);
        let assert_part = |actual: &Jet2, expected: &Jet2, outer_order: usize| {
            assert_eq!(actual.v, factors[outer_order] * expected.v);
            for axis in 0..expected.g.len() {
                assert_eq!(actual.g[axis], factors[outer_order + 1] * expected.g[axis]);
            }
            for axis in 0..expected.h.len() {
                assert_eq!(actual.h[axis], factors[outer_order + 2] * expected.h[axis]);
            }
        };
        assert_eq!(<Dual2<Jet2> as FlexJet>::ORDER, 4);
        assert_part(&scaled.v, &original.v, 0);
        assert_part(&scaled.g, &original.g, 1);
        assert_part(&scaled.h, &original.h, 2);
    }

    #[test]
    fn recursive_dual22_flexjet_scaling_matches_nested_total_order() {
        let factors = [2.0, 3.0, 5.0, 7.0, 11.0];
        let original_channels = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0];
        let scaled = Dual22::from_channels(original_channels)
            .scale_homogeneous_orders(factors)
            .channels();
        // `(outer order, inner order)` in `Dual22::channels()` order.
        let total_orders = [0usize, 1, 1, 2, 2, 2, 3, 3, 4];
        for channel in 0..scaled.len() {
            assert_eq!(
                scaled[channel],
                factors[total_orders[channel]] * original_channels[channel]
            );
        }
    }

    #[test]
    fn generic_q_jet_carries_exact_beta_family_calibration_channels() {
        let q = 0.37;
        let zero = Jet2::from_parts(0.0, &[0.0], &[]);
        let template = Dual2 {
            v: zero.clone(),
            g: zero.clone(),
            h: zero.clone(),
        };
        // q = q0 + beta + theta: independent unit inner-beta and outer-family
        // directions, with no curvature in the input chart itself.
        let q_jet = Dual2 {
            v: Jet2::primary(q, 0, 1),
            g: Jet2::from_parts(1.0, &[0.0], &[]),
            h: zero,
        };
        let scale_ratio = const_jet_like(&template, 1.0);
        let residual =
            calibration_residual_jet(&template, &template, 0, &[], &q_jet, &scale_ratio, &[]);
        let phi = crate::probability::normal_pdf(q);
        let expected = [
            -phi,
            q * phi,
            (1.0 - q * q) * phi,
            (q * q * q - 3.0 * q) * phi,
        ];
        let check = |actual: f64, wanted: f64, channel: &str| {
            let tolerance = 256.0 * f64::EPSILON * (1.0 + actual.abs().max(wanted.abs()));
            assert!(
                (actual - wanted).abs() <= tolerance,
                "{channel}: actual={actual:.17e}, wanted={wanted:.17e}, tolerance={tolerance:.3e}"
            );
        };
        check(residual.v.v, 0.0, "value");
        check(residual.v.g[0], expected[0], "beta first");
        check(residual.v.h[0], expected[1], "beta second");
        check(residual.g.v, expected[0], "family first");
        check(residual.g.g[0], expected[1], "family-beta");
        check(residual.g.h[0], expected[2], "family-beta-beta");
        check(residual.h.v, expected[1], "family second");
        check(residual.h.g[0], expected[2], "family-family-beta");
        check(residual.h.h[0], expected[3], "family-family-beta-beta");
    }

    /// Test-only execution policy that runs the historical order-four moment
    /// construction over a lower-order algebra. The wrapped arithmetic is
    /// unchanged, so this is an exact pre-optimization timing baseline rather
    /// than a separately re-derived moment formula.
    #[derive(Clone)]
    struct ForcedOrder4<J>(J);

    impl<J: FlexJet> JetField for ForcedOrder4<J> {
        #[inline(always)]
        fn value(&self) -> f64 {
            self.0.value()
        }

        #[inline(always)]
        fn add(&self, other: &Self) -> Self {
            Self(self.0.add(&other.0))
        }

        #[inline(always)]
        fn sub(&self, other: &Self) -> Self {
            Self(self.0.sub(&other.0))
        }

        #[inline(always)]
        fn mul(&self, other: &Self) -> Self {
            Self(self.0.mul(&other.0))
        }

        #[inline(always)]
        fn neg(&self) -> Self {
            Self(self.0.neg())
        }

        #[inline(always)]
        fn scale(&self, scale: f64) -> Self {
            Self(self.0.scale(scale))
        }

        #[inline(always)]
        fn compose_unary(&self, derivatives: [f64; 5]) -> Self {
            Self(self.0.compose_unary(derivatives))
        }
    }

    impl<J: FlexJet> FlexJet for ForcedOrder4<J> {
        const ORDER: usize = 4;

        fn scale_homogeneous_orders(&self, factors: [f64; 5]) -> Self {
            Self(self.0.scale_homogeneous_orders(factors))
        }
    }

    // ── §B moment engine: the de-nested cell moments over a FlexJet ─────────────
    //
    // #932 Item 2 (doc §D). The per-cell moments `M_n = ∫_{z_L}^{z_R} z^n e^{−q(z)} dz`
    // (sextic `q`, no closed antiderivative) satisfy the SAME raising recurrence the
    // numeric `cubic_cell_kernel::reduce_sextic_moments` uses —
    //   `M_{n+5} = (n·M_{n−1} − Σ_{j=0}^{4} d[j]·M_{n+j} − b_n) / d[5]`,
    // with `d = q'(z)` coefficients (`sextic_qprime_coefficients`) and boundary term
    // `b_n = z_R^n e^{−q(z_R)} − z_L^n e^{−q(z_L)}` — so it ports to ANY `FlexJet`
    // scalar verbatim. Carrying the cell coefficients `c0..c3` and the (moving) edges
    // `z_L,z_R` as jets propagates the moments' θ-derivatives mechanically: the
    // `Σ d[j]·M_{n+j}` term is the interior coefficient sensitivity and the boundary
    // term `b_n` is exactly the §D moving-boundary flux (its edge-jet derivatives are
    // the Leibniz `[z^n e^{−q}·z_edge']` contributions the hand `directional` path
    // assembles by hand). The base moments `M_0..M_4` (the normalization integrals)
    // arrive as jets from the cell evaluator — those carry the only transcendental
    // (erf/series) content; the algebra owns the rest.

    /// `q'(z)` coefficient jets `[d0..d5]` for `q = ½(z² + η²)`, `η = c0+c1 z+c2 z²+
    /// c3 z³`, over `FlexJet` cell-coefficient jets — the jet image of
    /// [`crate::cubic_cell_kernel::sextic_qprime_coefficients`].
    fn qprime_coeffs_jet<J: FlexJet>(c: &[J; 4]) -> [J; 6] {
        let (c0, c1, c2, c3) = (&c[0], &c[1], &c[2], &c[3]);
        // d0 = c0·c1
        let d0 = c0.mul(c1);
        // d1 = 1 + c1² + 2·c0·c2   (the leading `+z` of q' supplies the constant 1)
        let d1 = add_const(&c1.mul(c1).add(&c0.mul(c2).scale(2.0)), 1.0);
        // d2 = 3·c0·c3 + 3·c1·c2
        let d2 = c0.mul(c3).add(&c1.mul(c2)).scale(3.0);
        // d3 = 4·c1·c3 + 2·c2²
        let d3 = c1.mul(c3).scale(4.0).add(&c2.mul(c2).scale(2.0));
        // d4 = 5·c2·c3
        let d4 = c2.mul(c3).scale(5.0);
        // d5 = 3·c3²
        let d5 = c3.mul(c3).scale(3.0);
        [d0, d1, d2, d3, d4, d5]
    }

    /// `q(z) = ½(z² + η(z)²)` evaluated at an edge jet `z`, with `η` from the cell
    /// coefficient jets — the exponent whose `e^{−q}` is the boundary weight.
    fn cell_q_at_jet<J: FlexJet>(c: &[J; 4], z: &J) -> J {
        // η = c0 + c1 z + c2 z² + c3 z³  (Horner)
        let eta = c[3].mul(z).add(&c[2]).mul(z).add(&c[1]).mul(z).add(&c[0]);
        // ½(z² + η²)
        z.mul(z).add(&eta.mul(&eta)).scale(0.5)
    }

    /// One boundary term `z^n·e^{−q(z)}` at a (possibly infinite) moving edge jet.
    /// An infinite edge contributes nothing (matching the numeric
    /// `moment_boundary_term_with_powers` short-circuit).
    fn boundary_edge_term_jet<J: FlexJet>(
        c: &[J; 4],
        z: &J,
        z_pow_n: &J,
        finite: bool,
    ) -> Option<J> {
        if !finite {
            return None;
        }
        let q = cell_q_at_jet(c, z);
        let w = exp_jet(&q.scale(-1.0));
        Some(z_pow_n.mul(&w))
    }

    /// The sextic moment recurrence over a `FlexJet`: given the cell coefficient
    /// jets `c`, the moving edge jets `(z_left, z_right)` with their finiteness, and
    /// the base moment jets `M_0..M_4`, return `M_0..M_max` as jets. Bit-faithful to
    /// `reduce_sextic_moments` term for term, but every operation in the `FlexJet`
    /// algebra so the moments carry their exact θ-derivatives.
    fn cell_moment_recurrence_jet<J: FlexJet>(
        c: &[J; 4],
        z_left: &J,
        left_finite: bool,
        z_right: &J,
        right_finite: bool,
        base_m0_m4: &[J; 5],
        max_degree: usize,
    ) -> Vec<J> {
        let d = qprime_coeffs_jet(c);
        let inv_lead = recip(&d[5]);
        let mut moments: Vec<J> = base_m0_m4.iter().cloned().collect();
        if max_degree < 5 {
            moments.truncate(max_degree + 1);
            return moments;
        }
        // Rolling z^n at each edge (jets), starting at n = 0 (z^0 = 1 = z/z).
        let one_l = recip(z_left).mul(z_left);
        let one_r = recip(z_right).mul(z_right);
        let mut left_pow = one_l;
        let mut right_pow = one_r;
        for n in 0..=(max_degree - 5) {
            let b_left = boundary_edge_term_jet(c, z_left, &left_pow, left_finite);
            let b_right = boundary_edge_term_jet(c, z_right, &right_pow, right_finite);
            // b_n = right − left, missing edges contribute zero.
            let mut b_n = match (b_right, b_left) {
                (Some(r), Some(l)) => r.sub(&l),
                (Some(r), None) => r,
                (None, Some(l)) => l.scale(-1.0),
                (None, None) => moments[0].scale(0.0),
            };
            // numer = n·M_{n−1} − Σ_{j=0}^{4} d[j]·M_{n+j} − b_n
            let mut numer = if n == 0 {
                moments[0].scale(0.0)
            } else {
                moments[n - 1].scale(n as f64)
            };
            for j in 0..=4 {
                numer = numer.sub(&d[j].mul(&moments[n + j]));
            }
            numer = numer.sub(&b_n);
            moments.push(numer.mul(&inv_lead));
            // Roll powers: z^{n+1} = z^n · z.
            left_pow = if left_finite {
                left_pow.mul(z_left)
            } else {
                b_n.scale(0.0)
            };
            right_pow = if right_finite {
                right_pow.mul(z_right)
            } else {
                // reuse b_n as a zero-jet scratch source of the right `p`
                b_n = b_n.scale(0.0);
                b_n
            };
        }
        moments
    }

    // ── §C: observed cell-coefficient jets + eta/chi point-eval (Phase C core) ──
    //
    // The observed cell coefficients `coeff[k]` are a smooth function of the
    // intercept `a(θ)` and the slope `b` (= the `g` primary), with the score-warp
    // (`h`) and link-dev (`w`) channels entering linearly on top. Their full
    // bivariate Taylor in `(a,b)` is exactly the `observed_denested_cell_partials`
    // pack (`dc_da…dc_dbbb`). Composing that Taylor with the intercept jet `a_jet`
    // and the slope jet `b_jet` (both carrying their θ-derivatives) yields each
    // `coeff[k]` AS a jet — so `eta = Σ_k coeff[k]·z_obs^k` and `chi = Σ_k
    // dc_da[k]·z_obs^k` (point-evals at the fixed observation `z_obs`) carry their
    // exact θ-derivatives mechanically, replacing the hand `eta_u = chi·a_u + rho`
    // / `eta_uv = …` chain in `first_full`/`directional`/`bidirectional`.

    /// One observed cell coefficient `coeff[k]` as a jet: the bivariate `(a,b)`
    /// Taylor (up to 3rd order, matching the `dc_d{a,b}…` pack) composed with the
    /// intercept tangent `da` and slope tangent `db` jets. Terms with a 0/6/2/… are
    /// the multinomial Taylor weights `coeff + Σ (1/(i!j!)) ∂^{i+j}coeff/∂a^i∂b^j ·
    /// da^i db^j`.
    fn observed_coeff_component_jet<J: FlexJet>(
        template: &J,
        k: usize,
        coeff: [f64; 4],
        dc_da: [f64; 4],
        dc_db: [f64; 4],
        dc_daa: [f64; 4],
        dc_dab: [f64; 4],
        dc_dbb: [f64; 4],
        dc_daaa: [f64; 4],
        dc_daab: [f64; 4],
        dc_dabb: [f64; 4],
        dc_dbbb: [f64; 4],
        da: &J,
        db: &J,
    ) -> J {
        let dada = da.mul(da);
        let dadb = da.mul(db);
        let dbdb = db.mul(db);
        let mut c = const_jet_like(template, coeff[k]);
        c = c.add(&da.scale(dc_da[k])).add(&db.scale(dc_db[k]));
        c = c
            .add(&dada.scale(0.5 * dc_daa[k]))
            .add(&dadb.scale(dc_dab[k]))
            .add(&dbdb.scale(0.5 * dc_dbb[k]));
        let inv6 = 1.0 / 6.0;
        let half = 0.5;
        c = c
            .add(&dada.mul(da).scale(inv6 * dc_daaa[k]))
            .add(&dada.mul(db).scale(half * dc_daab[k]))
            .add(&dadb.mul(db).scale(half * dc_dabb[k]))
            .add(&dbdb.mul(db).scale(inv6 * dc_dbbb[k]));
        c
    }

    /// The observed cell-coefficient partial pack (`coeff`/`dc_d{a,b}…/dbbb`) passed
    /// through `observed_denested_cell_partials`, bundled so the generic eta/chi
    /// builder stays under the argument-count gate.
    struct ObservedCoeffPack {
        coeff: [f64; 4],
        dc_da: [f64; 4],
        dc_db: [f64; 4],
        dc_daa: [f64; 4],
        dc_dab: [f64; 4],
        dc_dbb: [f64; 4],
        dc_daaa: [f64; 4],
        dc_daab: [f64; 4],
        dc_dabb: [f64; 4],
        dc_dbbb: [f64; 4],
    }

    /// Phase C-complete (generic order): the observed timepoint `eta` and `chi` as
    /// jets at ANY `FlexJet` order, from the intercept jet `a_jet` (carrying its
    /// θ-derivatives to that order) and the slope jet `b_jet`, the observed
    /// cell-coefficient pack, and pre-built score-warp(`h`)/link-dev(`w`) `rho`/`tau`
    /// channel jets. `eta`/`chi` carry their exact θ-derivatives by composing the
    /// coefficients' bivariate `(a,b)` Taylor with the intercept/slope jets, then
    /// adding the linear `h`/`w`/`infl` channels — replacing the hand
    /// `eta_u = chi·a_u + rho`, `eta_uv = …` chains in
    /// `first_full`/`directional`/`bidirectional`.
    ///
    /// `rho_jet`/`tau_jet` are the already-seeded jets carrying the linear `h`/`w`/
    /// `infl` channels' θ-dependence on their own primaries (the caller builds them
    /// at the correct order with the right directional seeds — order-specific
    /// seeding context lives at the call site, not here). `eta += rho_jet`,
    /// `chi += tau_jet`.
    fn flex_timepoint_eta_chi<J: FlexJet>(
        a_jet: &J,
        b_jet: &J,
        z_obs: f64,
        o_infl: f64,
        pack: &ObservedCoeffPack,
        rho_jet: &J,
        tau_jet: &J,
    ) -> (J, J) {
        let da = tangent_jet(a_jet);
        let db = tangent_jet(b_jet);
        let zero4 = [0.0_f64; 4];

        // eta coefficients: the coeff pack composed with (da, db).
        let coeff_jets: [J; 4] = std::array::from_fn(|k| {
            observed_coeff_component_jet(
                a_jet,
                k,
                pack.coeff,
                pack.dc_da,
                pack.dc_db,
                pack.dc_daa,
                pack.dc_dab,
                pack.dc_dbb,
                pack.dc_daaa,
                pack.dc_daab,
                pack.dc_dabb,
                pack.dc_dbbb,
                &da,
                &db,
            )
        });
        let eta = add_const(&eval_coeff_jet_at(&coeff_jets, z_obs), o_infl).add(rho_jet);

        // chi = ∂eta/∂a coefficients = the dc_da pack, whose own (a,b)-Taylor is the
        // once-`a`-shifted pack (dc_daa as ∂/∂a, dc_dab as ∂/∂b, dc_daaa/daab/dabb as
        // the seconds; the dc_da pack carries no third-order term, so those are 0).
        let chi_jets: [J; 4] = std::array::from_fn(|k| {
            observed_coeff_component_jet(
                a_jet,
                k,
                pack.dc_da,
                pack.dc_daa,
                pack.dc_dab,
                pack.dc_daaa,
                pack.dc_daab,
                pack.dc_dabb,
                zero4,
                zero4,
                zero4,
                zero4,
                &da,
                &db,
            )
        });
        let chi = eval_coeff_jet_at(&chi_jets, z_obs).add(tau_jet);

        (eta, chi)
    }

    /// #932 item-2 increment 1: the FlexJet moment recurrence must reproduce the
    /// numeric `reduce_sextic_moments` on the VALUE channel term-for-term (a
    /// generic non-degenerate sextic cell), proving the port of the raising
    /// recurrence + boundary term to the jet algebra is exact. Independent
    /// finite-difference and nested-dual gates exercise the derivative channels.
    #[test]
    fn cell_moment_recurrence_jet_value_matches_numeric_932() {
        let cell = DenestedCubicCell {
            left: -1.5,
            right: 2.0,
            c0: 0.3,
            c1: -0.4,
            c2: 0.5,
            c3: 0.2,
        };
        let base = [1.0_f64, 0.1, 0.6, -0.05, 0.4];
        let max_degree = 12usize;
        let reference =
            reduce_sextic_moments(cell, base, max_degree).expect("numeric sextic moments");

        let p = 3usize;
        let konst = |x: f64| Jet2::from_parts(x, &vec![0.0; p], &[]);
        let c = [
            konst(cell.c0),
            konst(cell.c1),
            konst(cell.c2),
            konst(cell.c3),
        ];
        let zl = konst(cell.left);
        let zr = konst(cell.right);
        let base_jets = [
            konst(base[0]),
            konst(base[1]),
            konst(base[2]),
            konst(base[3]),
            konst(base[4]),
        ];
        let moments = cell_moment_recurrence_jet(
            &c,
            &zl,
            cell.left.is_finite(),
            &zr,
            cell.right.is_finite(),
            &base_jets,
            max_degree,
        );
        assert_eq!(moments.len(), reference.len(), "moment count");
        for (n, (m, r)) in moments.iter().zip(reference.iter()).enumerate() {
            assert!(
                (m.value() - r).abs() <= 1e-9 * (1.0 + r.abs()),
                "moment {n}: jet value {} != numeric {}",
                m.value(),
                r
            );
        }
    }

    /// The order-aware nilpotent schedule must preserve every represented
    /// channel while eliminating the historical order-four work from Jet1/2.
    /// `ForcedOrder4` delegates to the identical underlying arithmetic and only
    /// overrides the execution order, making it an exact pre-change baseline.
    #[test]
    fn measure_base_moment_instantiated_order_vs_forced_four_932() {
        use crate::cubic_cell_kernel::evaluate_cell_moments;

        let cell = DenestedCubicCell {
            left: -1.2,
            right: 1.7,
            c0: 0.25,
            c1: -0.35,
            c2: 0.4,
            c3: 0.15,
        };
        let numeric = evaluate_cell_moments(cell, 28)
            .expect("numeric cell moments")
            .moments
            .into_vec();
        let p = 6usize;
        let gradient = |scale: f64| -> Vec<f64> {
            (0..p)
                .map(|axis| scale * (axis as f64 + 1.0) / p as f64)
                .collect()
        };
        let hessian = |scale: f64| -> Vec<f64> {
            let mut out = vec![0.0; p * p];
            for i in 0..p {
                for j in 0..p {
                    out[i * p + j] = scale * (i + j + 1) as f64 / (p * p) as f64;
                }
            }
            out
        };

        let c1: [Jet1; 4] = [
            Jet1 {
                v: cell.c0,
                g: gradient(0.13),
            },
            Jet1 {
                v: cell.c1,
                g: gradient(-0.21),
            },
            Jet1 {
                v: cell.c2,
                g: gradient(0.17),
            },
            Jet1 {
                v: cell.c3,
                g: gradient(0.09),
            },
        ];
        let left1 = Jet1 {
            v: cell.left,
            g: gradient(-0.23),
        };
        let right1 = Jet1 {
            v: cell.right,
            g: gradient(0.31),
        };
        let forced_c1 = c1.clone().map(ForcedOrder4);
        let forced_left1 = ForcedOrder4(left1.clone());
        let forced_right1 = ForcedOrder4(right1.clone());

        let c2: [Jet2; 4] = [
            Jet2::from_parts(cell.c0, &gradient(0.13), &hessian(0.017)),
            Jet2::from_parts(cell.c1, &gradient(-0.21), &hessian(-0.011)),
            Jet2::from_parts(cell.c2, &gradient(0.17), &hessian(0.019)),
            Jet2::from_parts(cell.c3, &gradient(0.09), &hessian(-0.007)),
        ];
        let left2 = Jet2::from_parts(cell.left, &gradient(-0.23), &hessian(0.013));
        let right2 = Jet2::from_parts(cell.right, &gradient(0.31), &hessian(-0.015));
        let forced_c2 = c2.clone().map(ForcedOrder4);
        let forced_left2 = ForcedOrder4(left2.clone());
        let forced_right2 = ForcedOrder4(right2.clone());

        let native1 = base_moment_jets(&c1, &left1, true, &right1, true, &numeric);
        let historical1 = base_moment_jets(
            &forced_c1,
            &forced_left1,
            true,
            &forced_right1,
            true,
            &numeric,
        );
        let native2 = base_moment_jets(&c2, &left2, true, &right2, true, &numeric);
        let historical2 = base_moment_jets(
            &forced_c2,
            &forced_left2,
            true,
            &forced_right2,
            true,
            &numeric,
        );
        let close = |got: f64, want: f64, label: &str| {
            let tolerance = 1e-12 * got.abs().max(want.abs()).max(1.0);
            assert!((got - want).abs() <= tolerance, "{label}: {got} != {want}");
        };
        for n in 0..5 {
            close(
                native1[n].v,
                historical1[n].0.v,
                &format!("Jet1 M{n} value"),
            );
            for i in 0..p {
                close(
                    native1[n].g[i],
                    historical1[n].0.g[i],
                    &format!("Jet1 M{n} gradient[{i}]"),
                );
            }
            close(
                native2[n].v,
                historical2[n].0.v,
                &format!("Jet2 M{n} value"),
            );
            for i in 0..p {
                close(
                    native2[n].g[i],
                    historical2[n].0.g[i],
                    &format!("Jet2 M{n} gradient[{i}]"),
                );
                for j in 0..p {
                    close(
                        native2[n].h[i * p + j],
                        historical2[n].0.h[i * p + j],
                        &format!("Jet2 M{n} Hessian[{i},{j}]"),
                    );
                }
            }
        }

        let iterations = if cfg!(debug_assertions) { 4 } else { 5_000 };
        let mut native1_best = f64::INFINITY;
        let mut historical1_best = f64::INFINITY;
        let mut native2_best = f64::INFINITY;
        let mut historical2_best = f64::INFINITY;
        for _ in 0..5 {
            let start = Instant::now();
            for _ in 0..iterations {
                black_box(base_moment_jets(
                    black_box(&c1),
                    black_box(&left1),
                    true,
                    black_box(&right1),
                    true,
                    black_box(&numeric),
                ));
            }
            native1_best = native1_best.min(start.elapsed().as_secs_f64());

            let start = Instant::now();
            for _ in 0..iterations {
                black_box(base_moment_jets(
                    black_box(&forced_c1),
                    black_box(&forced_left1),
                    true,
                    black_box(&forced_right1),
                    true,
                    black_box(&numeric),
                ));
            }
            historical1_best = historical1_best.min(start.elapsed().as_secs_f64());

            let start = Instant::now();
            for _ in 0..iterations {
                black_box(base_moment_jets(
                    black_box(&c2),
                    black_box(&left2),
                    true,
                    black_box(&right2),
                    true,
                    black_box(&numeric),
                ));
            }
            native2_best = native2_best.min(start.elapsed().as_secs_f64());

            let start = Instant::now();
            for _ in 0..iterations {
                black_box(base_moment_jets(
                    black_box(&forced_c2),
                    black_box(&forced_left2),
                    true,
                    black_box(&forced_right2),
                    true,
                    black_box(&numeric),
                ));
            }
            historical2_best = historical2_best.min(start.elapsed().as_secs_f64());
        }
        let to_ns = |seconds: f64| seconds * 1e9 / iterations as f64;
        let native1_ns = to_ns(native1_best);
        let historical1_ns = to_ns(historical1_best);
        let native2_ns = to_ns(native2_best);
        let historical2_ns = to_ns(historical2_best);
        eprintln!(
            "FLEX-MOMENT-ORDER-932 jet1={native1_ns:.2} ns historical-order4-jet1={historical1_ns:.2} ns speedup1={:.3}x jet2={native2_ns:.2} ns historical-order4-jet2={historical2_ns:.2} ns speedup2={:.3}x",
            historical1_ns / native1_ns,
            historical2_ns / native2_ns,
        );
    }

    /// #932 item-2 Phase B-base: the base-moment jet builder `base_moment_jets`
    /// must reproduce the FIRST θ-derivatives of the normalization base moments
    /// `M_0..M_4` (interior `Σ_m S_m M_{n+m}` + moving-edge sliver flux) against a
    /// central finite difference of `evaluate_cell_moments` on a smooth one-
    /// parameter cell family `c_k(θ)=c_k0+θ·dc_k`, `z_{L,R}(θ)=z0+θ·v`. The
    /// gradient channel of the order-exact `Jet1` (seeded with `dc`/`v` in primary slot 0) is
    /// the analytic `dM_n/dθ`; the value channel is the numeric `M_n`.
    #[test]
    fn base_moment_jets_first_derivative_matches_fd_932() {
        use crate::cubic_cell_kernel::evaluate_cell_moments;

        // Smooth one-parameter family (θ scalar). Edges move; coefficients move.
        let c0 = [0.25_f64, -0.35, 0.4, 0.15];
        let zl0 = -1.2_f64;
        let zr0 = 1.7_f64;
        let dc = [0.13_f64, 0.21, -0.17, 0.09];
        let v_l = -0.23_f64;
        let v_r = 0.31_f64;
        let cell_at = |theta: f64| DenestedCubicCell {
            left: zl0 + theta * v_l,
            right: zr0 + theta * v_r,
            c0: c0[0] + theta * dc[0],
            c1: c0[1] + theta * dc[1],
            c2: c0[2] + theta * dc[2],
            c3: c0[3] + theta * dc[3],
        };
        let max_degree = 10usize;
        let moments_at = |theta: f64| -> Vec<f64> {
            evaluate_cell_moments(cell_at(theta), max_degree)
                .expect("numeric cell moments")
                .moments
                .into_vec()
        };
        let numeric0 = moments_at(0.0);

        // Seed the jets in primary slot 0 of a width-1 primary space: each
        // coefficient/edge jet carries its θ-velocity as its slot-0 gradient.
        let p = 1usize;
        let seeded = |x: f64, vel: f64| {
            let mut g = vec![0.0; p];
            g[0] = vel;
            Jet1 { v: x, g }
        };
        let c_jets = [
            seeded(c0[0], dc[0]),
            seeded(c0[1], dc[1]),
            seeded(c0[2], dc[2]),
            seeded(c0[3], dc[3]),
        ];
        let zl_jet = seeded(zl0, v_l);
        let zr_jet = seeded(zr0, v_r);
        let m_jets = base_moment_jets(&c_jets, &zl_jet, true, &zr_jet, true, &numeric0);

        // Central finite difference of each M_n.
        let h = 1e-6_f64;
        let mp = moments_at(h);
        let mm = moments_at(-h);
        for n in 0..5 {
            let fd = (mp[n] - mm[n]) / (2.0 * h);
            let jet = &m_jets[n];
            assert!(
                (jet.value() - numeric0[n]).abs() <= 1e-12 * (1.0 + numeric0[n].abs()),
                "M_{n} value {} != numeric {}",
                jet.value(),
                numeric0[n]
            );
            assert!(
                (jet.g[0] - fd).abs() <= 1e-5 * (1.0 + fd.abs()),
                "M_{n} dθ analytic {} != FD {}",
                jet.g[0],
                fd
            );
        }
    }

    /// #932 item-2 Phase B-base closure: the SECOND θ-derivative (the self-
    /// consistent `e^{−Δq}` interior `(∂q)²` cross-term + the second-order moving-
    /// edge sliver) must match a central finite difference of the analytic FIRST
    /// derivative. Probes the `Jet2` Hessian channel `h[0]` (= `d²M_n/dθ²`) of
    /// `base_moment_jets`, the all-orders exactness the Jet3/Jet4 contractions
    /// depend on.
    #[test]
    fn base_moment_jets_second_derivative_matches_fd_932() {
        use crate::cubic_cell_kernel::evaluate_cell_moments;

        let c0 = [0.25_f64, -0.35, 0.4, 0.15];
        let zl0 = -1.2_f64;
        let zr0 = 1.7_f64;
        let dc = [0.13_f64, 0.21, -0.17, 0.09];
        let v_l = -0.23_f64;
        let v_r = 0.31_f64;
        let cell_at = |theta: f64| DenestedCubicCell {
            left: zl0 + theta * v_l,
            right: zr0 + theta * v_r,
            c0: c0[0] + theta * dc[0],
            c1: c0[1] + theta * dc[1],
            c2: c0[2] + theta * dc[2],
            c3: c0[3] + theta * dc[3],
        };
        // The order-two `e^{−Δq}` interior closure retains
        // `S(z)=Σ_{k≤2}(−Δq)^k/k!`. Its `(−Δq)²` term is degree 12 in z (η is
        // cubic, hence Δq degree 6) and reaches `M_{n+12}`, up to `M_16` for
        // n≤4. Production builds cached moments beyond that; match the complete
        // budget so every Jet2 Hessian channel is exact.
        let max_degree = 27usize;
        let moments_at = |theta: f64| -> Vec<f64> {
            evaluate_cell_moments(cell_at(theta), max_degree)
                .expect("numeric cell moments")
                .moments
                .into_vec()
        };
        // Analytic first derivative dM_n/dθ from base_moment_jets at parameter θ.
        let analytic_first = |theta: f64, n: usize| -> f64 {
            let numeric = moments_at(theta);
            let seeded = |x: f64, vel: f64| {
                let g = vec![vel];
                Jet2::from_parts(x, &g, &[])
            };
            let cell = cell_at(theta);
            let c_jets = [
                seeded(cell.c0, dc[0]),
                seeded(cell.c1, dc[1]),
                seeded(cell.c2, dc[2]),
                seeded(cell.c3, dc[3]),
            ];
            let zl_jet = seeded(cell.left, v_l);
            let zr_jet = seeded(cell.right, v_r);
            let m = base_moment_jets(&c_jets, &zl_jet, true, &zr_jet, true, &numeric);
            m[n].g[0]
        };

        // Analytic second derivative from the Jet2 Hessian channel at θ=0.
        let numeric0 = moments_at(0.0);
        let seeded = |x: f64, vel: f64| {
            let g = vec![vel];
            Jet2::from_parts(x, &g, &[])
        };
        let c_jets = [
            seeded(c0[0], dc[0]),
            seeded(c0[1], dc[1]),
            seeded(c0[2], dc[2]),
            seeded(c0[3], dc[3]),
        ];
        let zl_jet = seeded(zl0, v_l);
        let zr_jet = seeded(zr0, v_r);
        let m_jets = base_moment_jets(&c_jets, &zl_jet, true, &zr_jet, true, &numeric0);

        let h = 1e-5_f64;
        for n in 0..5 {
            let fd2 = (analytic_first(h, n) - analytic_first(-h, n)) / (2.0 * h);
            let hess = m_jets[n].h[0];
            assert!(
                (hess - fd2).abs() <= 2e-4 * (1.0 + fd2.abs()),
                "M_{n} d²θ analytic {} != FD-of-analytic {}",
                hess,
                fd2
            );
        }
    }

    /// #932 item-2 Phase C: the generic `flex_timepoint_eta_chi<J>` builder must
    /// reproduce `eta = eval_coeff4_at(coeff, z) + o_infl + rho` and `chi =
    /// eval_coeff4_at(dc_da, z) + tau` on the VALUE channel, and the a/b θ-motion
    /// on the gradient channel vs a central finite difference of the same scalar
    /// expression along a smooth `(a,b)` family. Pins the bivariate-Taylor compose
    /// + the linear rho/tau add at `Jet2`.
    #[test]
    fn flex_timepoint_eta_chi_value_and_grad_932() {
        let z_obs = 0.7_f64;
        let o_infl = 0.05_f64;
        let pack = ObservedCoeffPack {
            coeff: [0.2, -0.3, 0.15, 0.05],
            dc_da: [1.1, 0.2, 0.03, 0.0],
            dc_db: [0.4, 1.05, 0.1, 0.02],
            dc_daa: [0.07, 0.02, 0.0, 0.0],
            dc_dab: [0.2, 0.09, 0.01, 0.0],
            dc_dbb: [0.11, 0.04, 0.005, 0.0],
            dc_daaa: [0.003, 0.0, 0.0, 0.0],
            dc_daab: [0.006, 0.001, 0.0, 0.0],
            dc_dabb: [0.004, 0.002, 0.0, 0.0],
            dc_dbbb: [0.008, 0.001, 0.0, 0.0],
        };
        // Single-primary family θ: a(θ)=a0+θ·a_u, b(θ)=b0+θ·b_u.
        let a0 = 0.3_f64;
        let b0 = 1.2_f64;
        let a_u = 0.25_f64;
        let b_u = -0.4_f64;
        let p = 1usize;
        let a_jet = Jet2::from_parts(a0, &[a_u], &[]);
        let b_jet = Jet2::from_parts(b0, &[b_u], &[]);
        // No rho/tau channels for this probe.
        let zero = Jet2::from_parts(0.0, &vec![0.0; p], &[]);
        let (eta, chi) = flex_timepoint_eta_chi(&a_jet, &b_jet, z_obs, o_infl, &pack, &zero, &zero);

        // Scalar reference: eta(a,b) = Σ_k c_k(a,b) z^k, c_k composed from the
        // bivariate Taylor of the pack about (a0,b0).
        let coeff_scalar = |da: f64, db: f64| -> [f64; 4] {
            std::array::from_fn(|k| {
                pack.coeff[k]
                    + pack.dc_da[k] * da
                    + pack.dc_db[k] * db
                    + 0.5 * pack.dc_daa[k] * da * da
                    + pack.dc_dab[k] * da * db
                    + 0.5 * pack.dc_dbb[k] * db * db
                    + pack.dc_daaa[k] * da * da * da / 6.0
                    + 0.5 * pack.dc_daab[k] * da * da * db
                    + 0.5 * pack.dc_dabb[k] * da * db * db
                    + pack.dc_dbbb[k] * db * db * db / 6.0
            })
        };
        let eta_scalar = |theta: f64| -> f64 {
            let c = coeff_scalar(a_u * theta, b_u * theta);
            eval_coeff4_scalar(&c, z_obs) + o_infl
        };
        let chi_scalar = |theta: f64| -> f64 {
            let dc = coeff_scalar_da(&pack, a_u * theta, b_u * theta);
            eval_coeff4_scalar(&dc, z_obs)
        };
        assert!(
            (eta.value() - eta_scalar(0.0)).abs() <= 1e-12 * (1.0 + eta_scalar(0.0).abs()),
            "eta value {} != {}",
            eta.value(),
            eta_scalar(0.0)
        );
        assert!(
            (chi.value() - chi_scalar(0.0)).abs() <= 1e-12 * (1.0 + chi_scalar(0.0).abs()),
            "chi value {} != {}",
            chi.value(),
            chi_scalar(0.0)
        );
        let h = 1e-6_f64;
        let eta_fd = (eta_scalar(h) - eta_scalar(-h)) / (2.0 * h);
        let chi_fd = (chi_scalar(h) - chi_scalar(-h)) / (2.0 * h);
        assert!(
            (eta.g[0] - eta_fd).abs() <= 1e-5 * (1.0 + eta_fd.abs()),
            "eta grad {} != FD {}",
            eta.g[0],
            eta_fd
        );
        assert!(
            (chi.g[0] - chi_fd).abs() <= 1e-5 * (1.0 + chi_fd.abs()),
            "chi grad {} != FD {}",
            chi.g[0],
            chi_fd
        );
    }

    /// Scalar Horner `Σ_k c[k] z^k` (the `f64` image of `eval_coeff4_at`).
    fn eval_coeff4_scalar(c: &[f64; 4], z: f64) -> f64 {
        let mut acc = 0.0;
        for &ck in c.iter().rev() {
            acc = acc * z + ck;
        }
        acc
    }

    /// Scalar `∂_a coeff` Taylor (the dc_da pack composed about (a0,b0)) — the
    /// reference for `chi`'s value/grad in the test above.
    fn coeff_scalar_da(pack: &ObservedCoeffPack, da: f64, db: f64) -> [f64; 4] {
        std::array::from_fn(|k| {
            pack.dc_da[k]
                + pack.dc_daa[k] * da
                + pack.dc_dab[k] * db
                + 0.5 * pack.dc_daaa[k] * da * da
                + pack.dc_daab[k] * da * db
                + 0.5 * pack.dc_dabb[k] * db * db
        })
    }

    /// #932 item-2 Phase C: `cell_coeff_jets` must reproduce the hand cell-coeff
    /// total θ-derivatives `c_k(a(θ), θ)` value + gradient (the `eta_u_poly =
    /// dc_da·a_u + coeff_u` / `coeff_bu·db` structure) vs a central FD of the
    /// scalar multivariate Taylor along a smooth `(a, {θ_u})` family. p=3 with the
    /// g-slope at axis 1.
    #[test]
    fn cell_coeff_jets_value_and_grad_932() {
        let p = 3usize;
        let g_axis = 1usize;
        let base_c = [0.2_f64, -0.3, 0.15, 0.05];
        // Minimal but fully-populated fixed pack (per-primary length p).
        let mk_run = |seed: f64| -> Vec<[f64; 4]> {
            (0..p)
                .map(|u| std::array::from_fn(|k| seed * (1.0 + u as f64) * (1.0 + k as f64) * 0.01))
                .collect()
        };
        let fixed = DenestedCellPrimaryFixedPartials {
            dc_da: [1.1, 0.2, 0.03, 0.0],
            dc_daa: [0.07, 0.02, 0.0, 0.0],
            dc_daaa: [0.003, 0.0, 0.0, 0.0],
            coeff_u: mk_run(0.9),
            coeff_au: mk_run(0.4),
            coeff_bu: mk_run(0.5),
            coeff_aau: mk_run(0.12),
            coeff_abu: mk_run(0.16),
            coeff_bbu: mk_run(0.11),
            coeff_aaau: mk_run(0.02),
            coeff_aabu: mk_run(0.03),
            coeff_abbu: mk_run(0.04),
            coeff_bbbu: mk_run(0.05),
        };
        // Smooth family θ: a(θ)=a0+θ·a_u, θ_u(θ)=u0[u]+θ·v[u].
        let a0 = 0.3_f64;
        let a_u = 0.25_f64;
        let v = [0.2_f64, -0.4, 0.33];

        let seeded = |x: f64, vel: f64| {
            let g = vec![vel];
            Jet2::from_parts(x, &g, &[])
        };
        let a_jet = seeded(a0, a_u);
        let da = tangent_jet(&a_jet);
        // du[u] = value-0 tangent carrying velocity v[u] in slot 0.
        let du: Vec<Jet2> = (0..p).map(|u| seeded(0.0, v[u])).collect();
        let jets = cell_coeff_jets(&a_jet, base_c, &fixed, g_axis, &da, &du);

        // Scalar reference: the TRUE multivariate Taylor `c_k(a(θ), {θ_u(θ)})` with
        // CORRECT factorials on every repeated axis. The non-g axes are linear in
        // `du[u]` (factor 1). The slope axis `g` (= `b`) carries its own pure-`b`
        // powers `½dc_dbb·db²`, `½dc_dabb·da·db²`, `⅙dc_dbbb·db³` (Taylor 1/n!) — NOT
        // the `coeff_bu[g]·db·du[g]` bilinear form, which would double/triple-count
        // the g-diagonal (the gam#932 fix the jet now implements).
        let scalar_c = |theta: f64| -> [f64; 4] {
            let da = a_u * theta;
            let db = v[g_axis] * theta;
            std::array::from_fn(|k| {
                let mut acc = base_c[k]
                    + fixed.dc_da[k] * da
                    + 0.5 * fixed.dc_daa[k] * da * da
                    + fixed.dc_daaa[k] * da * da * da / 6.0;
                // Linear (u != g) axes: bilinear in du[u].
                for u in 0..p {
                    if u == g_axis {
                        continue;
                    }
                    let duu = v[u] * theta;
                    acc += fixed.coeff_u[u][k] * duu
                        + fixed.coeff_au[u][k] * da * duu
                        + 0.5 * fixed.coeff_aau[u][k] * da * da * duu
                        + fixed.coeff_bu[u][k] * db * duu
                        + fixed.coeff_abu[u][k] * da * db * duu
                        + 0.5 * fixed.coeff_bbu[u][k] * db * db * duu
                        + fixed.coeff_aaau[u][k] * da * da * da * duu / 6.0
                        + 0.5 * fixed.coeff_aabu[u][k] * da * da * db * duu
                        + 0.5 * fixed.coeff_abbu[u][k] * da * db * db * duu
                        + fixed.coeff_bbbu[u][k] * db * db * db * duu / 6.0;
                }
                // Slope axis g (= b): pure-b Taylor with 1/n! factorials.
                acc += fixed.coeff_u[g_axis][k] * db
                    + fixed.coeff_au[g_axis][k] * da * db
                    + 0.5 * fixed.coeff_aau[g_axis][k] * da * da * db
                    + 0.5 * fixed.coeff_bu[g_axis][k] * db * db
                    + 0.5 * fixed.coeff_abu[g_axis][k] * da * db * db
                    + fixed.coeff_bbu[g_axis][k] * db * db * db / 6.0;
                acc
            })
        };
        let h = 1e-6_f64;
        let c0 = scalar_c(0.0);
        let cp = scalar_c(h);
        let cm = scalar_c(-h);
        for k in 0..4 {
            assert!(
                (jets[k].value() - c0[k]).abs() <= 1e-12 * (1.0 + c0[k].abs()),
                "c_{k} value {} != {}",
                jets[k].value(),
                c0[k]
            );
            let fd = (cp[k] - cm[k]) / (2.0 * h);
            assert!(
                (jets[k].g[0] - fd).abs() <= 1e-5 * (1.0 + fd.abs()),
                "c_{k} grad {} != FD {}",
                jets[k].g[0],
                fd
            );
        }

        // gam#932 g-DIAGONAL Hessian: with each primary in its OWN slot, the cell
        // coefficient jet's `Hess[g,g] = ∂²c/∂b²` MUST equal `coeff_bu[g] = dc_dbb`
        // EXACTLY — NOT `2·dc_dbb`. The pre-fix `coeff_bu[g]·db·du[g]` term gave
        // `dc_dbb·db²` whose Jet2 Hessian is `2·dc_dbb` (mul's symmetric 2×); the
        // ½-factorial fix restores the true second partial. (`da` here is a pure
        // intercept perturbation with NO primary grad, so it does not leak into the
        // g-slot Hessian — isolating `∂²c/∂b²` cleanly.)
        let da_iso = Jet2::from_parts(0.0, &vec![0.0; p], &[]);
        let du_iso: Vec<Jet2> = (0..p).map(|u| Jet2::primary(0.0, u, p)).collect();
        let jets_iso = cell_coeff_jets(&da_iso, base_c, &fixed, g_axis, &da_iso, &du_iso);
        for k in 0..4 {
            let hgg = jets_iso[k].h[g_axis * p + g_axis];
            assert!(
                (hgg - fixed.coeff_bu[g_axis][k]).abs()
                    <= 1e-12 * (1.0 + fixed.coeff_bu[g_axis][k].abs()),
                "c_{k} Hess[g,g] {} != dc_dbb {} (2× = the pre-fix g-diagonal bug)",
                hgg,
                fixed.coeff_bu[g_axis][k]
            );
        }
    }

    /// #932 item-2 Phase C STEP 1: `flex_timepoint_d_cell` (the per-cell density
    /// normalization `D_cell = INV_TWO_PI·Σ_k χ_k·M_k`) must reproduce the value
    /// `INV_TWO_PI·Σ_k dc_da[k]·M_k` and the θ-gradient `d_u` (the hand
    /// `survival_flex_base_d_u` quantity) vs a central FD of the same scalar `D(θ)`
    /// on a smooth intercept-only family `a(θ)=a0+θ` with FIXED edges (isolates
    /// the interior coefficient motion + the M_k `e^{−Δq}` `−χηη_u` term — the edge
    /// flux is exercised by the moving-edge `base_moment_jets` tests). The cell's
    /// `c_k` and `dc_da_k` move with `a` per the chosen `dc_daa`/`dc_daaa` pack.
    #[test]
    fn flex_timepoint_d_cell_value_and_grad_932() {
        use crate::cubic_cell_kernel::evaluate_cell_moments;

        let zl = -1.1_f64;
        let zr = 1.6_f64;
        // a-only family: c_k and dc_da_k are cubic/quadratic in θ via the pack.
        let c_base = [0.2_f64, -0.3, 0.18, 0.06];
        let dc_da = [1.05_f64, 0.22, 0.04, 0.0];
        let dc_daa = [0.08_f64, 0.03, 0.0, 0.0];
        let dc_daaa = [0.004_f64, 0.0, 0.0, 0.0];
        let cell_at = |theta: f64| {
            let c: [f64; 4] = std::array::from_fn(|k| {
                c_base[k]
                    + dc_da[k] * theta
                    + 0.5 * dc_daa[k] * theta * theta
                    + dc_daaa[k] * theta * theta * theta / 6.0
            });
            DenestedCubicCell {
                left: zl,
                right: zr,
                c0: c[0],
                c1: c[1],
                c2: c[2],
                c3: c[3],
            }
        };
        let dc_da_at = |theta: f64| -> [f64; 4] {
            std::array::from_fn(|k| dc_da[k] + dc_daa[k] * theta + 0.5 * dc_daaa[k] * theta * theta)
        };
        let max_degree = 10usize;
        let moments_at = |theta: f64| -> Vec<f64> {
            evaluate_cell_moments(cell_at(theta), max_degree)
                .expect("numeric cell moments")
                .moments
                .into_vec()
        };
        let d_scalar = |theta: f64| -> f64 {
            let m = moments_at(theta);
            let chi = dc_da_at(theta);
            let mut acc = 0.0;
            for k in 0..4 {
                acc += chi[k] * m[k];
            }
            acc * std::f64::consts::TAU.recip()
        };

        // Jet build: single primary (slot 0) = the intercept axis, velocity 1.
        let seeded = |x: f64, vel: f64| {
            let g = vec![vel];
            Jet1 { v: x, g }
        };
        let cell0 = cell_at(0.0);
        let c_jets = [
            seeded(cell0.c0, dc_da[0]),
            seeded(cell0.c1, dc_da[1]),
            seeded(cell0.c2, dc_da[2]),
            seeded(cell0.c3, dc_da[3]),
        ];
        // chi_jets carry dc_da value + dc_daa motion (a-only family).
        let dc_da0 = dc_da_at(0.0);
        let chi_jets = [
            seeded(dc_da0[0], dc_daa[0]),
            seeded(dc_da0[1], dc_daa[1]),
            seeded(dc_da0[2], dc_daa[2]),
            seeded(dc_da0[3], dc_daa[3]),
        ];
        let template = seeded(0.0, 0.0);
        let edge_l = seeded(zl, 0.0); // fixed edge: no motion
        let edge_r = seeded(zr, 0.0);
        let numeric0 = moments_at(0.0);
        let d_jet = flex_timepoint_d_cell(
            &template, &c_jets, &chi_jets, &edge_l, true, &edge_r, true, &numeric0,
        );

        assert!(
            (d_jet.value() - d_scalar(0.0)).abs() <= 1e-10 * (1.0 + d_scalar(0.0).abs()),
            "D value {} != {}",
            d_jet.value(),
            d_scalar(0.0)
        );
        let h = 1e-6_f64;
        let fd = (d_scalar(h) - d_scalar(-h)) / (2.0 * h);
        assert!(
            (d_jet.g[0] - fd).abs() <= 1e-4 * (1.0 + fd.abs()),
            "D grad (d_u) {} != FD {}",
            d_jet.g[0],
            fd
        );
    }

    /// #932 item-2 Phase C: `cell_chi_poly_jets` (the `∂η/∂a = dc_da` family as
    /// jets) value channel == `dc_da[k]`, gradient channel == the hand
    /// `chi_u_poly = dc_daa·a_u + coeff_au` chain, vs a central FD of the scalar
    /// `dc_da_k(a(θ), {θ_u})` Taylor. p=2 with the g-slope at axis 1.
    #[test]
    fn cell_chi_poly_jets_value_and_grad_932() {
        let p = 2usize;
        let g_axis = 1usize;
        let mk_run = |seed: f64| -> Vec<[f64; 4]> {
            (0..p)
                .map(|u| std::array::from_fn(|k| seed * (1.0 + u as f64) * (1.0 + k as f64) * 0.01))
                .collect()
        };
        let fixed = DenestedCellPrimaryFixedPartials {
            dc_da: [1.05, 0.22, 0.04, 0.0],
            dc_daa: [0.08, 0.03, 0.0, 0.0],
            dc_daaa: [0.004, 0.0, 0.0, 0.0],
            coeff_u: mk_run(0.9),
            coeff_au: mk_run(0.4),
            coeff_bu: mk_run(0.5),
            coeff_aau: mk_run(0.12),
            coeff_abu: mk_run(0.16),
            coeff_bbu: mk_run(0.11),
            coeff_aaau: mk_run(0.02),
            coeff_aabu: mk_run(0.03),
            coeff_abbu: mk_run(0.04),
            coeff_bbbu: mk_run(0.05),
        };
        let a_u = 0.25_f64;
        let v = [0.2_f64, -0.4];
        let seeded = |x: f64, vel: f64| {
            let g = vec![vel];
            Jet2::from_parts(x, &g, &[])
        };
        let a_jet = seeded(0.3, a_u);
        let da = tangent_jet(&a_jet);
        let du: Vec<Jet2> = (0..p).map(|u| seeded(0.0, v[u])).collect();
        let chi = cell_chi_poly_jets(&a_jet, &fixed, g_axis, &da, &du);

        let chi_scalar = |theta: f64| -> [f64; 4] {
            let da = a_u * theta;
            let db = v[g_axis] * theta;
            std::array::from_fn(|k| {
                let mut acc =
                    fixed.dc_da[k] + fixed.dc_daa[k] * da + 0.5 * fixed.dc_daaa[k] * da * da;
                for u in 0..p {
                    let duu = v[u] * theta;
                    acc += fixed.coeff_au[u][k] * duu
                        + fixed.coeff_aau[u][k] * da * duu
                        + fixed.coeff_abu[u][k] * db * duu;
                }
                acc
            })
        };
        let h = 1e-6_f64;
        let c0 = chi_scalar(0.0);
        let cp = chi_scalar(h);
        let cm = chi_scalar(-h);
        for k in 0..4 {
            assert!(
                (chi[k].value() - c0[k]).abs() <= 1e-12 * (1.0 + c0[k].abs()),
                "chi_{k} value {} != {}",
                chi[k].value(),
                c0[k]
            );
            let fd = (cp[k] - cm[k]) / (2.0 * h);
            assert!(
                (chi[k].g[0] - fd).abs() <= 1e-5 * (1.0 + fd.abs()),
                "chi_{k} grad {} != FD {}",
                chi[k].g[0],
                fd
            );
        }
    }
    // ── §3c: real-family finite-difference and nested-dual gates ──────────────
    /// A minimal g-only survival marginal-slope family for the §3c directional gates:
    /// scalar score covariance, raw `z`, a 1-col marginal + 1-col logslope design, no
    /// score-warp/link-dev/wiggle/absorber. Deterministic synthetic data.
    fn make_g_only_flex_family(n: usize) -> SurvivalMarginalSlopeFamily {
        let event: Array1<f64> =
            Array1::from_iter((0..n).map(|i| if (i * 31 + 7) % 5 >= 3 { 1.0 } else { 0.0 }));
        let weights: Array1<f64> =
            Array1::from_iter((0..n).map(|i| 0.5 + ((i * 13 + 4) % 5) as f64 * 0.1));
        let z: Array1<f64> = Array1::from_iter(
            (0..n).map(|i| -1.0 + 2.0 * (((i * 17 + 5) % n) as f64 + 0.5) / (n as f64)),
        );
        let offset_entry: Array1<f64> = Array1::from_iter(
            (0..n).map(|i| -0.4 + 0.7 * (((i * 11 + 3) % n) as f64 + 0.5) / (n as f64)),
        );
        let offset_exit: Array1<f64> = Array1::from_iter(
            (0..n).map(|i| 0.1 + 0.6 * (((i * 19 + 7) % n) as f64 + 0.5) / (n as f64)),
        );
        let derivative_offset_exit: Array1<f64> =
            Array1::from_iter((0..n).map(|i| 0.5 + 0.05 * ((i * 23 + 1) % 3) as f64));
        let marginal_design = Array2::from_shape_fn((n, 1), |(i, _)| {
            0.3 + 0.4 * (((i * 29 + 11) % n) as f64) / (n as f64)
        });
        let logslope_design = Array2::from_shape_fn((n, 1), |(i, _)| {
            0.2 + 0.5 * (((i * 37 + 9) % n) as f64) / (n as f64)
        });
        SurvivalMarginalSlopeFamily {
            n,
            event: Arc::new(event),
            weights: Arc::new(weights),
            z: Arc::new(z.insert_axis(Axis(1))),
            score_covariance: MarginalSlopeCovariance::diagonal(Array1::from(vec![1.0])).unwrap(),
            gaussian_frailty_sd: None,
            family_hyper: SurvivalMarginalSlopeFamilyHyperState::default(),
            derivative_guard: 1e-6,
            design_entry: DesignMatrix::from(Array2::zeros((n, 0))),
            design_exit: DesignMatrix::from(Array2::zeros((n, 0))),
            design_derivative_exit: DesignMatrix::from(Array2::zeros((n, 0))),
            offset_entry: Arc::new(offset_entry),
            offset_exit: Arc::new(offset_exit),
            derivative_offset_exit: Arc::new(derivative_offset_exit),
            marginal_design: DesignMatrix::from(marginal_design),
            logslope_layout: DesignMatrix::from(logslope_design).into(),
            score_warp: None,
            link_dev: None,
            influence_absorber: None,
            time_linear_constraints: None,
            time_wiggle_knots: None,
            time_wiggle_degree: None,
            time_wiggle_ncols: 0,
            intercept_warm_starts: None,
            auto_subsample_phase_counter: Arc::new(AtomicUsize::new(0)),
            auto_subsample_last_rho: Arc::new(Mutex::new(None)),
        }
    }

    /// The runtime Jet3 arena retains one bounded tape per worker and reuses it
    /// for an identical-width production row.
    #[test]
    fn flex_third_arena_reuses_warmed_tape_932() {
        let family = make_g_only_flex_family(16);
        let primary = flex_primary_slices(&family);
        let row = 5usize;
        let g = 0.21_f64;
        let q1 = family.offset_exit[row] + family.marginal_design.to_dense()[[row, 0]] * 0.15;
        let a1 = family
            .solve_row_survival_intercept_with_slot(
                q1,
                g,
                None,
                None,
                Some((row, SurvivalInterceptSlotKind::Exit)),
            )
            .expect("intercept solve")
            .0;
        let cached = family
            .build_cached_partition(&primary, a1, g, None, None)
            .expect("cached partition");
        let dir = Array1::from_iter((0..primary.total).map(|axis| 0.1 + 0.03 * axis as f64));

        let run = || {
            with_flex_third_jet_arena(|arena| {
                family
                    .compute_survival_timepoint_directional_jet_from_cached(
                        row, &primary, q1, primary.q1, a1, g, None, None, 0.0, &cached, &dir, arena,
                    )
                    .expect("production third-order timepoint")
            })
        };
        let retained_bytes = || with_flex_third_jet_arena(|arena| arena.allocated_bytes());
        run();
        let first = retained_bytes();
        assert!(first > 0, "FLEX third arena did not retain its warm tape");
        run();
        assert_eq!(
            retained_bytes(),
            first,
            "same-width FLEX third row grew its warmed arena"
        );
    }

    /// #932 grad-only cutover: the production grad-only timepoint
    /// (`compute_survival_timepoint_first_order_exact`, [`Jet1`]) is pinned two ways.
    /// (1) PARITY: its value + `eta_u`/`chi_u`/`d_u` equal the grad+Hessian
    /// production path (`compute_survival_timepoint_exact_jet`, [`Jet2`]) base +
    /// gradient channels to ≤1e-9 relative — the single-source claim (both drive the
    /// one `flex_timepoint_inputs_generic` builder). (2) INDEPENDENT FD WITNESS: the
    /// TOTAL derivatives `∂(eta,chi,d)/∂g` and `∂(eta,chi,d)/∂q` — each threading the
    /// per-row intercept CALIBRATION re-solve `a(g,q)` the audit flagged — match a
    /// central finite difference of the production-returned VALUE channels.
    #[test]
    fn flex_timepoint_first_order_matches_jet2_and_fd_932() {
        let n = 16usize;
        let family = make_g_only_flex_family(n);
        let primary = flex_primary_slices(&family);
        let p = primary.total;
        let row = 6usize;
        let g = 0.19_f64;
        let o_infl = 0.0_f64;

        let m_beta = 0.15_f64;
        let q1 = family.offset_exit[row] + family.marginal_design.to_dense()[[row, 0]] * m_beta;

        // Base-point intercept solve + both production timepoint packs.
        let (a1, _d1) = family
            .solve_row_survival_intercept_with_slot(
                q1,
                g,
                None,
                None,
                Some((row, SurvivalInterceptSlotKind::Exit)),
            )
            .expect("intercept solve");
        let first = family
            .compute_survival_timepoint_first_order_exact(
                row, &primary, q1, primary.q1, a1, g, None, None, o_infl,
            )
            .expect("grad-only jet1");
        let full = family
            .compute_survival_timepoint_exact_jet(
                row, &primary, q1, primary.q1, a1, g, None, None, o_infl,
            )
            .expect("grad+hess jet2");

        // (1) Parity against the Jet2 production path (single-source).
        let rel = |a: f64, b: f64| (a - b).abs() <= 1e-9 * (1.0 + b.abs());
        assert!(
            rel(first.eta, full.eta),
            "eta {} != {}",
            first.eta,
            full.eta
        );
        assert!(
            rel(first.chi, full.chi),
            "chi {} != {}",
            first.chi,
            full.chi
        );
        assert!(rel(first.d, full.d), "d {} != {}", first.d, full.d);
        for u in 0..p {
            assert!(
                rel(first.eta_u[u], full.eta_u[u]),
                "eta_u[{u}] {} != {}",
                first.eta_u[u],
                full.eta_u[u]
            );
            assert!(
                rel(first.chi_u[u], full.chi_u[u]),
                "chi_u[{u}] {} != {}",
                first.chi_u[u],
                full.chi_u[u]
            );
            assert!(
                rel(first.d_u[u], full.d_u[u]),
                "d_u[{u}] {} != {}",
                first.d_u[u],
                full.d_u[u]
            );
        }

        // (2) Independent central-FD witness of the returned VALUE channels. The
        // closure re-solves the calibration intercept `a(g,q)` exactly as production
        // does, so the FD is the genuine TOTAL derivative (intercept chain included).
        let eval = |gg: f64, qq: f64| -> (f64, f64, f64) {
            let (aa, _) = family
                .solve_row_survival_intercept_with_slot(
                    qq,
                    gg,
                    None,
                    None,
                    Some((row, SurvivalInterceptSlotKind::Exit)),
                )
                .expect("fd intercept solve");
            let tp = family
                .compute_survival_timepoint_first_order_exact(
                    row, &primary, qq, primary.q1, aa, gg, None, None, o_infl,
                )
                .expect("fd grad-only");
            (tp.eta, tp.chi, tp.d)
        };
        let h = 1e-6_f64;
        let (eta_gp, chi_gp, d_gp) = eval(g + h, q1);
        let (eta_gm, chi_gm, d_gm) = eval(g - h, q1);
        let (eta_qp, chi_qp, d_qp) = eval(g, q1 + h);
        let (eta_qm, chi_qm, d_qm) = eval(g, q1 - h);
        let fd = |plus: f64, minus: f64| (plus - minus) / (2.0 * h);
        let check = |label: &str, analytic: f64, numeric: f64| {
            assert!(
                (analytic - numeric).abs() <= 1e-5 * (1.0 + analytic.abs()),
                "{label}: analytic {analytic} != fd {numeric}"
            );
        };
        check("d eta/dg", first.eta_u[primary.g], fd(eta_gp, eta_gm));
        check("d chi/dg", first.chi_u[primary.g], fd(chi_gp, chi_gm));
        check("d d/dg", first.d_u[primary.g], fd(d_gp, d_gm));
        check("d eta/dq", first.eta_u[primary.q1], fd(eta_qp, eta_qm));
        check("d chi/dq", first.chi_u[primary.q1], fd(chi_qp, chi_qm));
        check("d d/dq", first.d_u[primary.q1], fd(d_qp, d_qm));
    }

    /// #932 item-2 STEP 4 (TRUNCATION-FREE gate): the nested-dual ORACLE `Dual22`
    /// instantiation of `flex_timepoint_inputs_generic` reproduces the production
    /// p-primary `Jet4` instantiation's mixed 4th-order bidirectional contraction
    /// EXACTLY, via an INDEPENDENT `2 + 2` composition order (not `2 + 1 + 1`).
    ///
    /// `Dual22` seeds two scalar directions `s = d1`, `t = d2` (each to 2nd order)
    /// and reads the `∂²_s ∂²_t` channel `= Σ_abcd ℓ_abcd d1_a d1_b d2_c d2_d`.
    /// The `Jet4` path seeds `eps = del = d2` — matrix `Σ_cd ℓ_uvcd d2_c d2_d` —
    /// then contracts both free axes by `d1`; the same scalar by ℓ's symmetry.
    /// Neither path uses a finite difference nor the incomplete §D hand oracle, so
    /// this replaces the flex jet4 bidirectional's 1e-3 scalar-FD sanity (the last
    /// FD-limited seam in the #932 tower) with a machine-precision independent
    /// check. Several random `(d1, d2)` pin the whole tensor, not one slice.
    #[test]
    fn flex_timepoint_inputs_nested_dual_matches_jet4_contraction_932() {
        let n = 16usize;
        let family = make_ghw_flex_family(n);
        let primary = flex_primary_slices(&family);
        let p = primary.total;
        let row = 6usize;
        let g = 0.2_f64;

        let h_len = primary.h.as_ref().map(|r| r.len()).unwrap_or(0);
        let w_len = primary.w.as_ref().map(|r| r.len()).unwrap_or(0);
        let beta_h = Array1::from_iter(
            (0..h_len).map(|i| 0.1 + 0.05 * (i as f64) - 0.02 * ((i % 2) as f64)),
        );
        let beta_w = Array1::from_iter(
            (0..w_len).map(|i| -0.08 + 0.04 * (i as f64) + 0.01 * ((i % 3) as f64)),
        );
        let bh = Some(&beta_h);
        let bw = Some(&beta_w);

        let m_beta = 0.15_f64;
        let q1 = family.offset_exit[row] + family.marginal_design.to_dense()[[row, 0]] * m_beta;
        let o_infl = 0.0_f64;
        let a1 = family
            .solve_row_survival_intercept_with_slot(
                q1,
                g,
                bh,
                bw,
                Some((row, SurvivalInterceptSlotKind::Exit)),
            )
            .expect("intercept solve")
            .0;
        let cached = family
            .build_cached_partition(&primary, a1, g, bh, bw)
            .expect("cached partition");
        let (obs_coeff, obs_fixed) =
            observed_fixed_for(&family, &primary, row, a1, g, bh, bw).expect("obs fixed");
        let cells = cells_from_cached(&cached);
        let z_obs = family.observed_score_projection(row);
        let d_check = family
            .evaluate_survival_denom_d(a1, g, bh, bw)
            .expect("denom");

        for trial in 0..4usize {
            let f = trial as f64;
            let d1 =
                Array1::from_iter((0..p).map(|c| {
                    0.11 + 0.03 * (c as f64) - 0.02 * (((c + trial) % 2) as f64) + 0.01 * f
                }));
            let d2 = Array1::from_iter((0..p).map(|c| {
                -0.06 + 0.045 * (((c + trial) % 3) as f64) + 0.02 * (c as f64) - 0.015 * f
            }));

            // Production p-primary Jet4: eps = del = d2 ⇒ matrix Σ_cd ℓ_uvcd d2_c d2_d.
            let tpl4 = Jet4::primary(0.0, usize::MAX, p, 0.0, 0.0);
            let b4 = Jet4::primary(g, primary.g, p, d2[primary.g], d2[primary.g]);
            let du4: Vec<Jet4> = (0..p)
                .map(|u| Jet4::primary(0.0, u, p, d2[u], d2[u]))
                .collect();
            let q4 = add_const(&du4[primary.q1], q1);
            let (eta4, chi4, d4) = flex_timepoint_inputs_generic(
                &tpl4,
                &b4,
                &du4,
                a1,
                d_check,
                primary.g,
                primary.infl,
                &q4,
                &const_jet_like(&tpl4, 1.0),
                z_obs,
                o_infl,
                obs_coeff,
                &obs_fixed,
                &cells,
            )
            .expect("generic jet4");
            let contract = |m: &Vec<f64>| -> f64 {
                let mut s = 0.0;
                for u in 0..p {
                    for v in 0..p {
                        s += d1[u] * d1[v] * m[u * p + v];
                    }
                }
                s
            };
            let eta_ref = contract(&eta4.eps_del.h);
            let chi_ref = contract(&chi4.eps_del.h);
            let d_ref = contract(&d4.eps_del.h);

            // Nested-dual ORACLE: s = d1, t = d2 ⇒ channel ∂²_s ∂²_t.
            let tpl2 = Dual22::seed_directional(0.0, 0.0, 0.0);
            let b2 = Dual22::seed_directional(g, d1[primary.g], d2[primary.g]);
            let du2: Vec<Dual22> = (0..p)
                .map(|u| Dual22::seed_directional(0.0, d1[u], d2[u]))
                .collect();
            let q2 = add_const(&du2[primary.q1], q1);
            let (eta2, chi2, d2n) = flex_timepoint_inputs_generic(
                &tpl2,
                &b2,
                &du2,
                a1,
                d_check,
                primary.g,
                primary.infl,
                &q2,
                &const_jet_like(&tpl2, 1.0),
                z_obs,
                o_infl,
                obs_coeff,
                &obs_fixed,
                &cells,
            )
            .expect("generic dual22");
            let eta_got = eta2.channels()[8];
            let chi_got = chi2.channels()[8];
            let d_got = d2n.channels()[8];

            let check = |label: &str, got: f64, refv: f64| {
                assert!(
                    (got - refv).abs() <= 1e-9 * (1.0 + refv.abs()),
                    "trial {trial} {label}: nested-dual {got} != jet4 contraction {refv}"
                );
            };
            check("eta_uv_uv", eta_got, eta_ref);
            check("chi_uv_uv", chi_got, chi_ref);
            check("d_uv_uv", d_got, d_ref);
        }
    }

    // ── §3c h/w channels: g+h+w scalar-FD gate ────────────────────────────────
    //
    // With score-warp(`h`) AND link-dev(`w`) active, the OBSERVED eta/chi carry the
    // `h`/`w` primaries, and their bidirectional derivatives involve the
    // h/w channel weights' OWN (a,b)-Taylor (w: `link_basis_cell_*partials`; h:
    // a-independent, `coeff_u[h]=b·H(z_obs)`/`coeff_bu[h]=H(z_obs)`). `observed_fixed_
    // for` packs these into a `DenestedCellPrimaryFixedPartials` at the observed point;
    // `cell_coeff_jets`/`cell_chi_poly_jets` raise them to all orders. This gate pins
    // the g+h+w Jet4 contraction against an independent scalar finite difference.

    /// A score-warp / link-dev deviation runtime for the g+h+w gate.
    fn flex_test_deviation_runtime() -> DeviationRuntime {
        build_score_warp_deviation_block_from_seed(
            &Array1::from(vec![-1.0, 0.0, 1.0]),
            &DeviationBlockConfig {
                degree: 3,
                num_internal_knots: 1,
                penalty_order: 2,
                penalty_orders: vec![1, 2, 3],
                double_penalty: false,
                monotonicity_eps: 1e-4,
            },
        )
        .expect("build test deviation runtime")
        .runtime
    }

    /// A g+h+w survival family: like `make_g_only_flex_family` but with BOTH a
    /// score-warp and a link-dev runtime installed (scalar score dim).
    fn make_ghw_flex_family(n: usize) -> SurvivalMarginalSlopeFamily {
        let mut family = make_g_only_flex_family(n);
        family.score_warp = Some(flex_test_deviation_runtime());
        family.link_dev = Some(flex_test_deviation_runtime());
        family
    }

    fn make_complete_family_map_fixture() -> (SurvivalMarginalSlopeFamily, Vec<ParameterBlockState>)
    {
        let mut family = make_ghw_flex_family(1);
        let knots = Array1::from(vec![0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0]);
        let degree = 3usize;
        let wiggle_width = time_wiggle_basis_ncols(&knots, degree).expect("timewiggle basis width");
        let time_width = 1 + wiggle_width;
        let mut entry_design = Array2::zeros((1, time_width));
        let mut exit_design = Array2::zeros((1, time_width));
        let mut derivative_design = Array2::zeros((1, time_width));
        entry_design[[0, 0]] = 0.25;
        exit_design[[0, 0]] = 0.45;
        derivative_design[[0, 0]] = 0.15;
        family.design_entry = DesignMatrix::from(entry_design);
        family.design_exit = DesignMatrix::from(exit_design);
        family.design_derivative_exit = DesignMatrix::from(derivative_design);
        family.offset_entry = Arc::new(Array1::from(vec![0.20]));
        family.offset_exit = Arc::new(Array1::from(vec![0.35]));
        family.derivative_offset_exit = Arc::new(Array1::from(vec![0.80]));
        family.marginal_design = DesignMatrix::from(
            Array2::from_shape_vec((1, 1), vec![0.30]).expect("marginal fixture shape"),
        );
        family.logslope_layout = DesignMatrix::from(
            Array2::from_shape_vec((1, 1), vec![0.40]).expect("logslope fixture shape"),
        )
        .into();
        family.influence_absorber = Some(
            Array2::from_shape_vec((1, 2), vec![0.20, -0.15]).expect("influence fixture shape"),
        );
        family.time_wiggle_knots = Some(knots);
        family.time_wiggle_degree = Some(degree);
        family.time_wiggle_ncols = wiggle_width;
        family.event = Arc::new(Array1::from(vec![1.0]));
        family.weights = Arc::new(Array1::from(vec![0.9]));
        family.z =
            Arc::new(Array2::from_shape_vec((1, 1), vec![0.2]).expect("score fixture shape"));
        family.gaussian_frailty_sd = Some(0.6);

        let mut beta_time = Array1::zeros(time_width);
        beta_time[0] = 0.10;
        for local in 0..wiggle_width {
            beta_time[1 + local] = 0.006 + 0.002 * local as f64;
        }
        let beta_marginal = Array1::from(vec![0.12]);
        let beta_logslope = Array1::from(vec![0.20]);
        let score_width = family
            .score_warp
            .as_ref()
            .expect("score runtime")
            .basis_dim();
        let link_width = family.link_dev.as_ref().expect("link runtime").basis_dim();
        let beta_score =
            Array1::from_iter((0..score_width).map(|axis| 0.004 * (1.0 + axis as f64)));
        let beta_link = Array1::from_iter((0..link_width).map(|axis| -0.003 + 0.001 * axis as f64));
        let beta_influence = Array1::from(vec![0.03, -0.02]);
        let time_eta = family.design_exit.dot_row(0, &beta_time) + family.offset_exit[0];
        let marginal_eta = family.marginal_design.dot_row(0, &beta_marginal);
        let logslope_eta = family
            .logslope_layout
            .coefficient_design()
            .dot_row(0, &beta_logslope);
        let states = vec![
            ParameterBlockState {
                beta: beta_time,
                eta: Array1::from(vec![time_eta]),
            },
            ParameterBlockState {
                beta: beta_marginal,
                eta: Array1::from(vec![marginal_eta]),
            },
            ParameterBlockState {
                beta: beta_logslope,
                eta: Array1::from(vec![logslope_eta]),
            },
            ParameterBlockState {
                beta: beta_score,
                eta: Array1::zeros(1),
            },
            ParameterBlockState {
                beta: beta_link,
                eta: Array1::zeros(1),
            },
            ParameterBlockState {
                beta: beta_influence,
                eta: Array1::zeros(1),
            },
        ];
        (family, states)
    }

    #[test]
    fn complete_family_map_owns_every_coefficient_block_and_log_sigma_scale_stack() {
        let (family, states) = make_complete_family_map_fixture();
        let primary = flex_primary_slices(&family);
        let slices = block_slices(&family, &states);
        let sigma = family.gaussian_frailty_sd.expect("fixture sigma");
        let sigma2 = sigma * sigma;
        let alpha = sigma2 / (1.0 + sigma2);
        let scale = family.probit_frailty_scale();
        let first = FlexFamilyRowDirection {
            entry: 0.07,
            exit: -0.04,
            derivative_exit: 0.03,
            probit_scale: -scale * alpha,
        };
        let second = FlexFamilyRowDirection {
            entry: -0.02,
            exit: 0.05,
            derivative_exit: -0.01,
            probit_scale: scale * alpha * (3.0 * alpha - 2.0),
        };
        let jets = family
            .build_flex_family_coefficient_jets::<Jet2>(
                0, &states, &primary, &slices, first, second, None,
            )
            .expect("complete family coefficient map");
        let q = family
            .row_dynamic_q_geometry(0, &states)
            .expect("analytic dynamic q geometry");
        let check = |actual: f64, expected: f64, channel: &str| {
            let tolerance = 1024.0 * f64::EPSILON * (1.0 + actual.abs().max(expected.abs()));
            assert!(
                (actual - expected).abs() <= tolerance,
                "{channel}: actual={actual:.17e}, expected={expected:.17e}, tolerance={tolerance:.3e}"
            );
        };
        for local in 0..slices.time.len() {
            let axis = slices.time.start + local;
            check(jets.q0.v.g[axis], q.dq0_time[local], "q0 time");
            check(jets.q1.v.g[axis], q.dq1_time[local], "q1 time");
            check(jets.qd1.v.g[axis], q.dqd1_time[local], "qd1 time");
        }
        for local in 0..slices.marginal.len() {
            let axis = slices.marginal.start + local;
            check(jets.q0.v.g[axis], q.dq0_marginal[local], "q0 marginal");
            check(jets.q1.v.g[axis], q.dq1_marginal[local], "q1 marginal");
            check(jets.qd1.v.g[axis], q.dqd1_marginal[local], "qd1 marginal");
        }
        assert_eq!(
            jets.g.v.g[slices.logslope.start],
            family.logslope_layout.coefficient_design().to_dense()[[0, 0]],
        );
        let h_primary = primary.h.as_ref().expect("score primary").start;
        let h_coefficient = slices.score_warp.as_ref().expect("score slice").start;
        assert_eq!(jets.du[h_primary].v.g[h_coefficient], 1.0);
        let w_primary = primary.w.as_ref().expect("link primary").start;
        let w_coefficient = slices.link_dev.as_ref().expect("link slice").start;
        assert_eq!(jets.du[w_primary].v.g[w_coefficient], 1.0);
        let influence_primary = primary.infl.expect("influence primary");
        let influence_range = slices.influence.as_ref().expect("influence slice");
        assert_eq!(jets.du[influence_primary].v.g[influence_range.start], 0.20);
        assert_eq!(
            jets.du[influence_primary].v.g[influence_range.start + 1],
            -0.15
        );
        assert_eq!(jets.scale_ratio.v.value(), 1.0);
        check(jets.scale_ratio.g.value(), -alpha, "ds/s");
        check(
            jets.scale_ratio.h.value(),
            alpha * (3.0 * alpha - 2.0),
            "d2s/s",
        );
        assert!(jets.scale_ratio.g.g.iter().all(|value| *value == 0.0));
        assert!(jets.scale_ratio.h.h.iter().all(|value| *value == 0.0));
    }

    #[test]
    fn complete_family_row_dual2_jet2_and_jet3_share_channels_without_fd() {
        let (family, states) = make_complete_family_map_fixture();
        let slices = block_slices(&family, &states);
        let scale = family.probit_frailty_scale();
        let first = FlexFamilyRowDirection {
            entry: 0.04,
            exit: -0.03,
            derivative_exit: 0.02,
            probit_scale: -0.08 * scale,
        };
        let second = FlexFamilyRowDirection {
            entry: -0.01,
            exit: 0.025,
            derivative_exit: 0.015,
            probit_scale: 0.03 * scale,
        };
        let order2 = family
            .flex_family_direction_row_terms(0, &states, first, second, None)
            .expect("Dual2<Jet2> family row");
        let direction =
            Array1::from_iter((0..slices.total).map(|axis| -0.035 + 0.007 * (axis % 9) as f64));
        let order3 = family
            .flex_family_direction_row_terms(0, &states, first, second, Some(&direction))
            .expect("Dual2<Jet3> family row");
        let assert_same = |left: &FlexFamilyCoefficientTerms,
                           right: &FlexFamilyCoefficientTerms,
                           channel: &str| {
            assert_eq!(
                left.objective.to_bits(),
                right.objective.to_bits(),
                "{channel} V"
            );
            for axis in 0..slices.total {
                assert_eq!(
                    left.gradient[axis].to_bits(),
                    right.gradient[axis].to_bits(),
                    "{channel} g[{axis}]"
                );
                for other in 0..slices.total {
                    assert_eq!(
                        left.hessian[[axis, other]].to_bits(),
                        right.hessian[[axis, other]].to_bits(),
                        "{channel} H[{axis},{other}]"
                    );
                }
            }
        };
        assert_same(&order2.first, &order3.first, "first");
        assert_same(&order2.second, &order3.second, "second");
        let drift = order3.directional.expect("nonzero Jet3 beta drift");
        let expected_value = order2.first.gradient.dot(&direction);
        let tolerance =
            |actual: f64, expected: f64| 1.0e-10 * (1.0 + actual.abs().max(expected.abs()));
        assert!(
            (drift.objective - expected_value).abs() <= tolerance(drift.objective, expected_value),
            "family beta drift V {} != g·d {}",
            drift.objective,
            expected_value,
        );
        for axis in 0..slices.total {
            let expected_gradient = order2.first.hessian.row(axis).dot(&direction);
            assert!(
                (drift.gradient[axis] - expected_gradient).abs()
                    <= tolerance(drift.gradient[axis], expected_gradient),
                "family beta drift g[{axis}] {} != H[row]·d {}",
                drift.gradient[axis],
                expected_gradient,
            );
        }
        assert!(drift.hessian.iter().all(|value| value.is_finite()));
        assert!(drift.hessian.iter().any(|value| *value != 0.0));

        // A design direction is not a beta direction: its epsilon seed owns
        // both X_psi beta and X_psi.  With the fixture's scalar marginal
        // design this gives two independent analytic identities, including
        // the pullback-map contribution to the marginal score.
        let x = family.marginal_design.to_dense()[[0, 0]];
        let x_psi = 0.17;
        let beta = states[1].beta[0];
        let design = family
            .flex_family_design_direction_row_terms(
                0,
                &states,
                first,
                second,
                1,
                &Array1::from(vec![x_psi]),
            )
            .expect("Dual2<Jet3> family-by-design row");
        assert_same(&order2.first, &design.first, "design first base");
        assert_same(&order2.second, &design.second, "design second base");
        let design_drift = design.directional.expect("nonzero design drift");
        let marginal_axis = slices.marginal.start;
        let h_psi = x_psi * beta;
        let expected_design_objective = order2.first.gradient[marginal_axis] * h_psi / x;
        assert!(
            (design_drift.objective - expected_design_objective).abs()
                <= tolerance(design_drift.objective, expected_design_objective),
            "family-by-design objective {} != analytic {}",
            design_drift.objective,
            expected_design_objective,
        );
        let expected_design_score = x_psi * order2.first.gradient[marginal_axis] / x
            + h_psi * order2.first.hessian[[marginal_axis, marginal_axis]] / x;
        assert!(
            (design_drift.gradient[marginal_axis] - expected_design_score).abs()
                <= tolerance(design_drift.gradient[marginal_axis], expected_design_score,),
            "family-by-design marginal score {} != analytic pullback {}",
            design_drift.gradient[marginal_axis],
            expected_design_score,
        );
        assert!(design_drift.hessian.iter().all(|value| value.is_finite()));
        assert!(design_drift.hessian.iter().any(|value| *value != 0.0));
    }

    /// `flex_timepoint_inputs_generic` at Jet4 must match a scalar finite difference
    /// of the real intercept solve with active score-warp and link-deviation primaries.
    #[test]
    fn flex_timepoint_inputs_ghw_jet4_matches_scalar_fd_932() {
        let n = 16usize;
        let family = make_ghw_flex_family(n);
        let primary = flex_primary_slices(&family);
        let p = primary.total;
        let row = 6usize;
        let g = 0.2_f64;

        // Non-trivial h/w coefficients (lengths from the primary layout).
        let h_len = primary.h.as_ref().map(|r| r.len()).unwrap_or(0);
        let w_len = primary.w.as_ref().map(|r| r.len()).unwrap_or(0);
        let beta_h = Array1::from_iter(
            (0..h_len).map(|i| 0.1 + 0.05 * (i as f64) - 0.02 * ((i % 2) as f64)),
        );
        let beta_w = Array1::from_iter(
            (0..w_len).map(|i| -0.08 + 0.04 * (i as f64) + 0.01 * ((i % 3) as f64)),
        );
        let bh = Some(&beta_h);
        let bw = Some(&beta_w);

        let m_beta = 0.15_f64;
        let q1 = family.offset_exit[row] + family.marginal_design.to_dense()[[row, 0]] * m_beta;
        let o_infl = 0.0_f64;
        let a1 = family
            .solve_row_survival_intercept_with_slot(
                q1,
                g,
                bh,
                bw,
                Some((row, SurvivalInterceptSlotKind::Exit)),
            )
            .expect("intercept solve")
            .0;
        let cached = family
            .build_cached_partition(&primary, a1, g, bh, bw)
            .expect("cached partition");

        let (obs_coeff, obs_fixed) =
            observed_fixed_for(&family, &primary, row, a1, g, bh, bw).expect("obs fixed");
        let cells = cells_from_cached(&cached);
        let z_obs = family.observed_score_projection(row);
        let d_check = family
            .evaluate_survival_denom_d(a1, g, bh, bw)
            .expect("denom");

        // ── #932 scalar-FD oracle: the authoritative [q1,q1]
        // bidirectional reference.
        //
        // `q1` (= primary.q1) enters the OBSERVED eta/chi/D only through the lifted
        // intercept a (no de-nested-cell coefficient dependence: the eta_aa·a_u² and
        // r_uv terms vanish at the q1 axis), so eta_uv_uv[q1,q1] = D_d1 D_d2(∂²_q1
        // eta_obs) is a pure chain through the intercept solve a(q1, β). Finite-
        // difference the observed scalars eta_obs/chi_obs/D as functions of the q1
        // marginal and the (dir1, dir2)-perturbed primaries. The intercept root is
        // solved at every stencil point, so the oracle includes the complete moving
        // boundary response. The probe also pins the lifted intercept itself.
        let (oracle_eta_uvuv, oracle_chi_uvuv, oracle_d_uvuv) = {
            let dir1 = Array1::from_iter(
                (0..p).map(|c| 0.12 + 0.04 * (c as f64) - 0.01 * ((c % 2) as f64)),
            );
            let dir2 = Array1::from_iter(
                (0..p).map(|c| -0.07 + 0.05 * ((c % 3) as f64) + 0.02 * (c as f64)),
            );
            // Solve the intercept at θ + (an arbitrary per-primary perturbation `pert`)
            // and read back (a, eta_obs, chi_obs, D). `pert[u]` shifts primary u's
            // scalar: q1→the marginal q1 argument, g→the slope, h-range[i]→β_h[i],
            // w-range[i]→β_w[i]; every other primary (q0/qd1/infl) leaves the intercept
            // unchanged (a depends only on q1/g/β_h/β_w). This drives BOTH the directional
            // contractions and the (u,v) Hessian stencils below.
            let scalars_of = |pert: &Array1<f64>| -> (f64, f64, f64, f64) {
                let q1_pert = q1 + pert[primary.q1];
                let g_pert = g + pert[primary.g];
                let bh_pert: Array1<f64> = Array1::from_iter(
                    (0..h_len).map(|i| beta_h[i] + pert[primary.h.as_ref().unwrap().start + i]),
                );
                let bw_pert: Array1<f64> = Array1::from_iter(
                    (0..w_len).map(|i| beta_w[i] + pert[primary.w.as_ref().unwrap().start + i]),
                );
                let a_pert = family
                    .solve_row_survival_intercept_with_slot(
                        q1_pert,
                        g_pert,
                        Some(&bh_pert),
                        Some(&bw_pert),
                        None,
                    )
                    .expect("oracle intercept solve")
                    .0;
                let obs = family
                    .observed_denested_cell_partials(
                        row,
                        a_pert,
                        g_pert,
                        Some(&bh_pert),
                        Some(&bw_pert),
                    )
                    .expect("oracle observed partials");
                let d_pert = family
                    .evaluate_survival_denom_d(a_pert, g_pert, Some(&bh_pert), Some(&bw_pert))
                    .expect("oracle denom");
                (
                    a_pert,
                    eval_coeff4_at(&obs.coeff, z_obs) + o_infl,
                    eval_coeff4_at(&obs.dc_da, z_obs),
                    d_pert,
                )
            };

            let hq = 2.0e-3_f64;
            let ht = 3.0e-3_f64;
            // Build the per-primary perturbation vector for a stencil point:
            // su·e_u + sv·e_v + t1·dir1 + t2·dir2 (u and v may coincide → su,sv add).
            let pert_vec =
                |su: f64, u: usize, sv: f64, v: usize, t1: f64, t2: f64| -> Array1<f64> {
                    let mut pert = &dir1 * t1 + &dir2 * t2;
                    pert[u] += su;
                    pert[v] += sv;
                    pert
                };
            // The mixed bidirectional Hessian entry [u,v] of the observed scalars
            // (a, eta_obs, chi_obs, D) all at once: ∂_u ∂_v (D_dir1 D_dir2 ·). For u==v
            // a ∂²_u 3-point stencil; for u!=v the 2×2 cross stencil. The directional
            // second cross is the outer 2×2 over (t1,t2) — a 4×4 stencil product
            // (Hessian × directional). Returns one tuple so the four scalars share the
            // (expensive) intercept solves.
            let mixed = |u: usize, v: usize| -> (f64, f64, f64, f64) {
                let acc =
                    |w: f64, su: f64, sv: f64, t1: f64, t2: f64, out: &mut (f64, f64, f64, f64)| {
                        let s = scalars_of(&pert_vec(su, u, sv, v, t1, t2));
                        out.0 += w * s.0;
                        out.1 += w * s.1;
                        out.2 += w * s.2;
                        out.3 += w * s.3;
                    };
                let hess_uv = |t1: f64, t2: f64| -> (f64, f64, f64, f64) {
                    let mut o = (0.0, 0.0, 0.0, 0.0);
                    if u == v {
                        acc(1.0, hq, 0.0, t1, t2, &mut o);
                        acc(-2.0, 0.0, 0.0, t1, t2, &mut o);
                        acc(1.0, -hq, 0.0, t1, t2, &mut o);
                        let inv = 1.0 / (hq * hq);
                        (o.0 * inv, o.1 * inv, o.2 * inv, o.3 * inv)
                    } else {
                        acc(1.0, hq, hq, t1, t2, &mut o);
                        acc(-1.0, hq, -hq, t1, t2, &mut o);
                        acc(-1.0, -hq, hq, t1, t2, &mut o);
                        acc(1.0, -hq, -hq, t1, t2, &mut o);
                        let inv = 1.0 / (4.0 * hq * hq);
                        (o.0 * inv, o.1 * inv, o.2 * inv, o.3 * inv)
                    }
                };
                let a = hess_uv(ht, ht);
                let b = hess_uv(ht, -ht);
                let c = hess_uv(-ht, ht);
                let d = hess_uv(-ht, -ht);
                let inv = 1.0 / (4.0 * ht * ht);
                (
                    (a.0 - b.0 - c.0 + d.0) * inv,
                    (a.1 - b.1 - c.1 + d.1) * inv,
                    (a.2 - b.2 - c.2 + d.2) * inv,
                    (a.3 - b.3 - c.3 + d.3) * inv,
                )
            };

            // Cross-check: the jet's lifted intercept a_uv_uv[q1,q1] (eps_del Hessian)
            // == the scalar-FD a-Hessian (the verdict that confirmed the jet correct).
            let template4 = Jet4::primary(0.0, usize::MAX, p, 0.0, 0.0);
            let b_jet4 = Jet4::primary(g, primary.g, p, dir1[primary.g], dir2[primary.g]);
            let du4: Vec<Jet4> = (0..p)
                .map(|u| Jet4::primary(0.0, u, p, dir1[u], dir2[u]))
                .collect();
            let q_jet4 = add_const(&du4[primary.q1], q1);
            let scale_ratio4 = const_jet_like(&template4, 1.0);
            let residual_probe = |a: &Jet4| {
                calibration_residual_jet(
                    a,
                    &b_jet4,
                    primary.g,
                    &du4,
                    &q_jet4,
                    &scale_ratio4,
                    &cells,
                )
            };
            let a_jet_probe = lift_intercept_flex(&template4, a1, 1.0 / d_check, 4, residual_probe);
            let jet_a_uvuv = a_jet_probe.eps_del.h[primary.q1 * p + primary.q1];

            // Oracle matrices: the FULL bidirectional (a, eta, chi, D) Hessian for EVERY
            // (u,v) — the scalar-FD of the real intercept solve is ground truth at every
            // entry, so the gate asserts the whole eta/chi/D_uv_uv matrix against it.
            // The Hessian is symmetric, so compute v>=u and mirror. `a`-channel
            // diagonal [q1,q1] feeds the lifted-intercept cross-check below.
            let mut o_eta = Array2::<f64>::zeros((p, p));
            let mut o_chi = Array2::<f64>::zeros((p, p));
            let mut o_d = Array2::<f64>::zeros((p, p));
            let mut ref_a_uvuv = 0.0_f64;
            for u in 0..p {
                for v in u..p {
                    let (a_uvuv, eta_uvuv, chi_uvuv, d_uvuv) = mixed(u, v);
                    o_eta[[u, v]] = eta_uvuv;
                    o_eta[[v, u]] = eta_uvuv;
                    o_chi[[u, v]] = chi_uvuv;
                    o_chi[[v, u]] = chi_uvuv;
                    o_d[[u, v]] = d_uvuv;
                    o_d[[v, u]] = d_uvuv;
                    if u == primary.q1 && v == primary.q1 {
                        ref_a_uvuv = a_uvuv;
                    }
                }
            }
            assert!(
                (jet_a_uvuv - ref_a_uvuv).abs() <= 1e-3 * (1.0 + ref_a_uvuv.abs()),
                "#932 PROBE a_uv_uv[q1,q1]: jet {jet_a_uvuv} != scalar-FD {ref_a_uvuv} \
                 (diff {})",
                jet_a_uvuv - ref_a_uvuv,
            );
            (o_eta, o_chi, o_d)
        };

        // ── Jet4 bidirectional ──
        let dir1 =
            Array1::from_iter((0..p).map(|c| 0.12 + 0.04 * (c as f64) - 0.01 * ((c % 2) as f64)));
        let dir2 =
            Array1::from_iter((0..p).map(|c| -0.07 + 0.05 * ((c % 3) as f64) + 0.02 * (c as f64)));
        let template4 = Jet4::primary(0.0, usize::MAX, p, 0.0, 0.0);
        let b_jet4 = Jet4::primary(g, primary.g, p, dir1[primary.g], dir2[primary.g]);
        let du4: Vec<Jet4> = (0..p)
            .map(|u| Jet4::primary(0.0, u, p, dir1[u], dir2[u]))
            .collect();
        let q_jet4 = add_const(&du4[primary.q1], q1);
        let (eta4, chi4, d4) = flex_timepoint_inputs_generic(
            &template4,
            &b_jet4,
            &du4,
            a1,
            d_check,
            primary.g,
            primary.infl,
            &q_jet4,
            &const_jet_like(&template4, 1.0),
            z_obs,
            o_infl,
            obs_coeff,
            &obs_fixed,
            &cells,
        )
        .expect("generic jet4");

        // Assert the full bidirectional Hessian against the scalar-FD oracle at every
        // entry. Report every mismatch so a channel regression is immediately local.
        let cmp_mat_oracle = |label: &str, jet: &Vec<f64>, oracle: &Array2<f64>| {
            let mut fails: Vec<String> = Vec::new();
            for u in 0..p {
                for v in 0..p {
                    let o = oracle[[u, v]];
                    let j = jet[u * p + v];
                    if (j - o).abs() > 1e-3 * (1.0 + o.abs()) {
                        let rel = (j - o).abs() / (1.0 + o.abs());
                        fails.push(format!("[{u},{v}] jet {j:.6} oracle {o:.6} rel {rel:.2e}"));
                    }
                }
            }
            assert!(
                fails.is_empty(),
                "{label} jet != scalar-FD oracle at {} entr{}: {}",
                fails.len(),
                if fails.len() == 1 { "y" } else { "ies" },
                fails.join("; "),
            );
        };
        cmp_mat_oracle("eta_uv_uv", &eta4.eps_del.h, &oracle_eta_uvuv);
        cmp_mat_oracle("chi_uv_uv", &chi4.eps_del.h, &oracle_chi_uvuv);
        cmp_mat_oracle("d_uv_uv", &d4.eps_del.h, &oracle_d_uvuv);
    }
}

#[cfg(test)]
mod compiled_order2_oracle_tests {
    //! Gate: the two-output-allocation order-two lowering of [`FlexOuterPlan`]
    //! agrees to `1e-12` with the same plan evaluated through generic [`Jet2`]
    //! — value, gradient, and Hessian, channel-for-channel — over ≥2000 random
    //! inputs at several primary counts `p`.
    use super::*;

    fn xorshift(state: &mut u64) -> f64 {
        let mut x = *state;
        x ^= x << 13;
        x ^= x >> 7;
        x ^= x << 17;
        *state = x;
        let u = (x >> 11) as f64 / ((1u64 << 53) as f64);
        2.0 * u - 1.0
    }

    fn rand_dense(p: usize, st: &mut u64) -> (f64, Vec<f64>, Vec<f64>) {
        let v = xorshift(st);
        let g: Vec<f64> = (0..p).map(|_| xorshift(st)).collect();
        let mut h = vec![0.0; p * p];
        for i in 0..p {
            for j in i..p {
                let x = xorshift(st);
                h[i * p + j] = x;
                h[j * p + i] = x;
            }
        }
        (v, g, h)
    }

    #[test]
    fn compiled_order2_row_nll_matches_generic_plan() {
        for &p in &[3usize, 6, 9, 12, 20] {
            let mut st = 0x5DEE_CE66_D9C7_F123u64 ^ (p as u64).wrapping_mul(0x9E3779B97F4A7C15);
            for _ in 0..2200 {
                let wi = (xorshift(&mut st) + 1.5).abs() + 0.1;
                let di = if xorshift(&mut st) > 0.0 { 1.0 } else { 0.0 };
                let surv0: [f64; 5] = std::array::from_fn(|_| xorshift(&mut st));
                let surv1: [f64; 5] = std::array::from_fn(|_| xorshift(&mut st));
                let (e0v, e0g, e0h) = rand_dense(p, &mut st);
                let (e1v, e1g, e1h) = rand_dense(p, &mut st);
                let (mut cv, cg, ch) = rand_dense(p, &mut st);
                cv = (cv + 2.0).abs() + 0.3;
                let (mut dv, dg, dh) = rand_dense(p, &mut st);
                dv = (dv + 2.0).abs() + 0.3;
                let q1v = (xorshift(&mut st) + 2.0).abs() + 0.2;
                let qd1v = (xorshift(&mut st) + 2.0).abs() + 0.2;
                let qax = p - 2;
                let qdax = p - 1;

                // Generic single source at Jet2.
                let g_out = flex_row_nll(
                    &Jet2::from_parts(e0v, &e0g, &e0h),
                    &Jet2::from_parts(e1v, &e1g, &e1h),
                    &Jet2::from_parts(cv, &cg, &ch),
                    &Jet2::from_parts(dv, &dg, &dh),
                    &Jet2::primary(q1v, qax, p),
                    &Jet2::primary(qd1v, qdax, p),
                    surv0,
                    surv1,
                    wi,
                    di,
                );

                // Production compiled lowering of that exact plan.
                let plan = FlexOuterPlan::new(cv, dv, qd1v, surv0, surv1, wi, di);
                let (f_value, f_gradient, f_hessian) = lower_flex_outer_plan_order2(
                    &plan,
                    FlexOrder2Inputs {
                        eta0: FlexOrder2View {
                            value: e0v,
                            gradient: ndarray::ArrayView1::from(&e0g),
                            hessian: ndarray::ArrayView2::from_shape((p, p), &e0h).unwrap(),
                        },
                        eta1: FlexOrder2View {
                            value: e1v,
                            gradient: ndarray::ArrayView1::from(&e1g),
                            hessian: ndarray::ArrayView2::from_shape((p, p), &e1h).unwrap(),
                        },
                        q1: (q1v, qax),
                        chi1: FlexOrder2View {
                            value: cv,
                            gradient: ndarray::ArrayView1::from(&cg),
                            hessian: ndarray::ArrayView2::from_shape((p, p), &ch).unwrap(),
                        },
                        d1: FlexOrder2View {
                            value: dv,
                            gradient: ndarray::ArrayView1::from(&dg),
                            hessian: ndarray::ArrayView2::from_shape((p, p), &dh).unwrap(),
                        },
                        qd1: (qd1v, qdax),
                    },
                    p,
                );

                let close = |left: f64, right: f64, channel: &str| {
                    let tolerance = 1e-12 * left.abs().max(right.abs()).max(1.0);
                    assert!(
                        (left - right).abs() <= tolerance,
                        "{channel} p={p}: generic={left:+.16e} compiled={right:+.16e}"
                    );
                };
                close(g_out.v, f_value, "value");
                for i in 0..p {
                    close(g_out.g[i], f_gradient[i], &format!("grad[{i}]"));
                }
                for k in 0..p * p {
                    close(g_out.h[k], f_hessian[k], &format!("hess[{k}]"));
                }
            }
        }
    }

    /// #932 release speed gate for the FLEX row order-2 lowering: the
    /// production compiled plan (`lower_flex_outer_plan_order2`, two output
    /// allocations, structure-scheduled) must beat the generic [`Jet2`]
    /// evaluation of the SAME single-source plan (`flex_row_nll`), the
    /// substrate it specializes. The historical hand flex assembly was
    /// deleted by the cutover, so — as in the multinomial / cause-specific /
    /// contracted-tower release cells — the honest fail-closed baseline is
    /// the generic jet plan, and the emitted `hand_over_production` token
    /// carries `generic_plan_ns / production_ns` for the MSI release harness
    /// to fail closed on any cell `<= 1`. One cell per event branch at a
    /// representative flex width.
    #[test]
    fn release_measure_flex_compiled_order2_vs_generic_plan_932() {
        use std::time::Instant;

        let p = 12usize;
        let qax = p - 2;
        let qdax = p - 1;

        // Feedback-coupled timing barrier (no `std::hint::black_box`): the
        // entry-eta value channel is nudged by a negligible multiple of the
        // running checksum, so the pure row evaluation can be neither hoisted
        // nor dropped while the measured regime stays bit-adjacent to the
        // fixture.
        fn best_ns<F: FnMut(f64) -> f64>(iterations: usize, base: f64, mut evaluate: F) -> f64 {
            let mut best = f64::INFINITY;
            for _ in 0..5 {
                let mut checksum = 0.0_f64;
                let started = Instant::now();
                for _ in 0..iterations {
                    checksum += evaluate(base + checksum * 1e-18);
                }
                assert!(
                    checksum.is_finite(),
                    "flex order-2 release-measure checksum must stay finite"
                );
                best = best.min(started.elapsed().as_secs_f64());
            }
            best * 1e9 / iterations as f64
        }

        let iterations = 20_000usize;
        for di in [0.0_f64, 1.0] {
            let mut st = 0xA5F0_3C11_9D2E_7B41u64 ^ di.to_bits();
            let wi = (xorshift(&mut st) + 1.5).abs() + 0.1;
            let surv0: [f64; 5] = std::array::from_fn(|_| xorshift(&mut st));
            let surv1: [f64; 5] = std::array::from_fn(|_| xorshift(&mut st));
            let (e0v, e0g, e0h) = rand_dense(p, &mut st);
            let (e1v, e1g, e1h) = rand_dense(p, &mut st);
            let (mut cv, cg, ch) = rand_dense(p, &mut st);
            cv = (cv + 2.0).abs() + 0.3;
            let (mut dv, dg, dh) = rand_dense(p, &mut st);
            dv = (dv + 2.0).abs() + 0.3;
            let q1v = (xorshift(&mut st) + 2.0).abs() + 0.2;
            let qd1v = (xorshift(&mut st) + 2.0).abs() + 0.2;

            let plan = FlexOuterPlan::new(cv, dv, qd1v, surv0, surv1, wi, di);

            // Parity pin on the exact benchmarked inputs (the 2200-draw sweep
            // is `compiled_order2_row_nll_matches_generic_plan` above).
            let generic = flex_row_nll(
                &Jet2::from_parts(e0v, &e0g, &e0h),
                &Jet2::from_parts(e1v, &e1g, &e1h),
                &Jet2::from_parts(cv, &cg, &ch),
                &Jet2::from_parts(dv, &dg, &dh),
                &Jet2::primary(q1v, qax, p),
                &Jet2::primary(qd1v, qdax, p),
                surv0,
                surv1,
                wi,
                di,
            );
            let (compiled_value, ..) = lower_flex_outer_plan_order2(
                &plan,
                FlexOrder2Inputs {
                    eta0: FlexOrder2View {
                        value: e0v,
                        gradient: ndarray::ArrayView1::from(&e0g),
                        hessian: ndarray::ArrayView2::from_shape((p, p), &e0h).unwrap(),
                    },
                    eta1: FlexOrder2View {
                        value: e1v,
                        gradient: ndarray::ArrayView1::from(&e1g),
                        hessian: ndarray::ArrayView2::from_shape((p, p), &e1h).unwrap(),
                    },
                    q1: (q1v, qax),
                    chi1: FlexOrder2View {
                        value: cv,
                        gradient: ndarray::ArrayView1::from(&cg),
                        hessian: ndarray::ArrayView2::from_shape((p, p), &ch).unwrap(),
                    },
                    d1: FlexOrder2View {
                        value: dv,
                        gradient: ndarray::ArrayView1::from(&dg),
                        hessian: ndarray::ArrayView2::from_shape((p, p), &dh).unwrap(),
                    },
                    qd1: (qd1v, qdax),
                },
                p,
            );
            let tolerance = 1e-12 * generic.v.abs().max(compiled_value.abs()).max(1.0);
            assert!(
                (generic.v - compiled_value).abs() <= tolerance,
                "di={di:.0} value: generic={:+.16e} compiled={compiled_value:+.16e}",
                generic.v,
            );

            let production_ns = best_ns(iterations, e0v, |perturbed_e0v| {
                let (value, gradient, hessian) = lower_flex_outer_plan_order2(
                    &plan,
                    FlexOrder2Inputs {
                        eta0: FlexOrder2View {
                            value: perturbed_e0v,
                            gradient: ndarray::ArrayView1::from(&e0g),
                            hessian: ndarray::ArrayView2::from_shape((p, p), &e0h).unwrap(),
                        },
                        eta1: FlexOrder2View {
                            value: e1v,
                            gradient: ndarray::ArrayView1::from(&e1g),
                            hessian: ndarray::ArrayView2::from_shape((p, p), &e1h).unwrap(),
                        },
                        q1: (q1v, qax),
                        chi1: FlexOrder2View {
                            value: cv,
                            gradient: ndarray::ArrayView1::from(&cg),
                            hessian: ndarray::ArrayView2::from_shape((p, p), &ch).unwrap(),
                        },
                        d1: FlexOrder2View {
                            value: dv,
                            gradient: ndarray::ArrayView1::from(&dg),
                            hessian: ndarray::ArrayView2::from_shape((p, p), &dh).unwrap(),
                        },
                        qd1: (qd1v, qdax),
                    },
                    p,
                );
                value + gradient[0] + hessian[0]
            });
            let generic_ns = best_ns(iterations, e0v, |perturbed_e0v| {
                let out = flex_row_nll(
                    &Jet2::from_parts(perturbed_e0v, &e0g, &e0h),
                    &Jet2::from_parts(e1v, &e1g, &e1h),
                    &Jet2::from_parts(cv, &cg, &ch),
                    &Jet2::from_parts(dv, &dg, &dh),
                    &Jet2::primary(q1v, qax, p),
                    &Jet2::primary(qd1v, qdax, p),
                    surv0,
                    surv1,
                    wi,
                    di,
                );
                out.v + out.g[0] + out.h[0]
            });
            eprintln!(
                "FLEX-ORDER2-932 p={p} event={di:.0} production={production_ns:.2} ns/row \
                 generic_plan={generic_ns:.2} ns/row hand_over_production={:.6}",
                generic_ns / production_ns,
            );
        }
    }
}