pounce-cli 0.12.0

Command-line driver for POUNCE — solves built-in TNLPs and AMPL .nl files.
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
//! `pounce` — command-line driver for the POUNCE solver.
//!
//! Output is structured to mirror upstream `ipopt`'s console layout:
//! a banner, a problem-statistics block, the per-iteration table, and
//! a final residual / eval-count summary. The intent is that anyone
//! used to reading `ipopt` output can drop in `pounce` without
//! relearning where the numbers live.
//!
//! Exit status: 0 on a successful solve — `Solve_Succeeded` or
//! `Solved_To_Acceptable_Level` (the reduced-accuracy convergence Ipopt
//! likewise treats as success) — and non-zero otherwise. In AMPL solver
//! mode (`-AMPL`) the exit code instead follows the AMPL contract — 0 for
//! any solve that ran and produced a `.sol`, since the termination is
//! carried by the file's `solve_result_num`.

use pounce_algorithm::alg_builder::{LinearBackendFactory, LinearSolverChoice};
use pounce_algorithm::application::{IpoptApplication, Ma57Config};
use pounce_cli::builtin;
use pounce_cli::cli::{Args, ProblemSource};
use pounce_cli::counting_tnlp::CountingTnlp;
use pounce_cli::nl_reader;
use pounce_cli::nl_writer;
use pounce_cli::print;
use pounce_cli::sens;
use pounce_cli::solve_report::{
    InputDescriptor, ReportBuilder, ReportDetail, SolutionSuffix, status_to_solve_result_num,
    write_report_file,
};
use pounce_common::diagnostics::{
    DiagCategory, DiagnosticsConfig, DiagnosticsState, DumpFormat, IterSpec,
};
use pounce_linsol::sparse_sym_iface::SparseSymLinearSolverInterface;
use pounce_nlp::return_codes::ApplicationReturnStatus;
use pounce_nlp::solve_statistics::IterRecord;
use pounce_nlp::tnlp::{InfeasibilityProof, TNLP};
use pounce_restoration::resto_alg_builder::RestoAlgorithmBuilder;
use pounce_restoration::resto_inner_solver::{
    InnerBackendFactoryFactory, make_default_restoration_factory_provider,
};
use pounce_restoration::second_opinion_driver::{SecondOpinionOutcome, run_second_opinion_ladder};
use std::cell::RefCell;
use std::path::PathBuf;
use std::process::ExitCode;
use std::rc::Rc;

/// The reported `(message, solve_result_num)` for a finished solve.
///
/// Single source of truth shared by the JSON report and the `.sol` writer — a
/// run reporting `201` in one and `200` in the other is a bug a caller has no
/// way to reconcile.
///
/// A presolve-certified infeasibility reports `201`; everything else uses the
/// standard status mapping. Both sit in AMPL's `200..299` infeasible band, so
/// band-reading consumers (Pyomo included) are unaffected either way.
fn presolve_verdict(
    certified: Option<InfeasibilityProof>,
    status: ApplicationReturnStatus,
) -> (String, i32) {
    // The certificate only *relabels* an infeasibility verdict — it never
    // manufactures one. The application short-circuits on a proof before
    // dispatch, so the two normally agree; but the SQP engine is dispatched
    // ahead of that check and reports its own status, and the CLI computes
    // `certified` from its own presolve handle. Without this guard a
    // disagreement would write "proved infeasible" with `201` on top of a
    // successful solve's `x` — a self-contradictory `.sol` that no caller
    // could reconcile. If they ever disagree, trust the engine that ran.
    match certified.filter(|_| status == ApplicationReturnStatus::InfeasibleProblemDetected) {
        Some(proof) => {
            let detail = match proof {
                InfeasibilityProof::BoundPropagation => "bound propagation".to_string(),
                InfeasibilityProof::IntervalArithmetic { witness } => {
                    format!("interval arithmetic, constraint {witness}")
                }
            };
            (
                format!(
                    "POUNCE {}: InfeasibleProblemDetected (detected by presolve: {detail})",
                    env!("CARGO_PKG_VERSION")
                ),
                201,
            )
        }
        None => (
            format!("POUNCE {}: {status:?}", env!("CARGO_PKG_VERSION")),
            status_to_solve_result_num(status),
        ),
    }
}

/// Whether the resolved options select `nlp_scaling_method=curvature-based`
/// (gh #703). Read off the `OptionsList` rather than the raw argv so the
/// option file, the `pounce_options` environment variable and the
/// command line are all honoured in the order they are applied.
fn curvature_scaling_requested(app: &pounce_algorithm::application::IpoptApplication) -> bool {
    app.options()
        .get_string_value("nlp_scaling_method", "")
        .ok()
        .and_then(|(v, f)| f.then_some(v))
        .is_some_and(|v| v == "curvature-based")
}

pub fn main() -> ExitCode {
    // Install the tracing subscriber first so even argument-parse
    // diagnostics and the iteration collector are active (pounce#71).
    // Honors RUST_LOG, NO_COLOR, and POUNCE_LOG_FORMAT.
    pounce_observability::init_subscriber();

    // `pounce verify <problem.nl> <claim.sol>` — an independent solution
    // checker that re-derives feasibility from the canonical problem. It is
    // a distinct subcommand (not a solve), so dispatch it before the normal
    // argv parser and solve path. See `pounce_cli::verify`.
    let raw_argv: Vec<String> = std::env::args().collect();
    if raw_argv.get(1).map(|s| s == "verify").unwrap_or(false) {
        return pounce_cli::verify::run_from_argv(&raw_argv[2..]);
    }

    // `pounce check-x0 <problem.nl>` — starting-point preflight: evaluate
    // the model once at x0 and report NaN/inf, bound/constraint violations,
    // interior-clamp displacement, and derivative scale spread before any
    // solve. See `pounce_cli::check_x0` and docs/src/initialization.md.
    if raw_argv.get(1).map(|s| s == "check-x0").unwrap_or(false) {
        return pounce_cli::check_x0::run_from_argv(&raw_argv[2..]);
    }

    let mut args = match Args::parse_argv(std::env::args().collect()) {
        Ok(a) => a,
        Err(msg) => {
            eprintln!("pounce: {msg}");
            eprintln!("{}", Args::usage());
            return ExitCode::from(2);
        }
    };

    // AMPL drivers pass solver directives via the `<solver>_options` env
    // var (`pounce_options`): a whitespace-separated list of `key=value`
    // tokens. Merge them ahead of the command-line `key=value` options so
    // an explicit CLI flag overrides the env var (set_options is applied
    // last-wins). Pyomo, which writes options as CLI args, is unaffected.
    if let Ok(env_opts) = std::env::var("pounce_options") {
        let mut merged = pounce_cli::cli::options_from_env(&env_opts);
        if !merged.is_empty() {
            merged.append(&mut args.set_options);
            args.set_options = merged;
        }
    }

    if args.help {
        println!("{}", Args::usage());
        return ExitCode::SUCCESS;
    }
    if args.version {
        println!("pounce {}", env!("CARGO_PKG_VERSION"));
        return ExitCode::SUCCESS;
    }
    if args.about {
        print_about();
        return ExitCode::SUCCESS;
    }
    if args.cite {
        return run_cite(&args);
    }

    let mut app = IpoptApplication::new();

    // This binary is the one entry point that can route a model to the
    // convex LP/QP/SOCP engines (`solver_selection` + the structure
    // extraction that classifies the `.nl`), so the `qp_*` knobs those
    // engines read configure something here. Declaring that is what keeps
    // `IpoptApplication`'s guard from refusing them on the NLP fallback
    // path — a convex attempt that hands off to `optimize_tnlp` used them
    // for real (gh#604).
    app.set_convex_routing_available(true);

    // NOTE: the convex LP/QP knobs (`qp_tau`, `qp_tau_max`, `qp_reg`,
    // `qp_gondzio_corr`,
    // `qp_infeas_tol`, `qp_hsde`, `qp_equilibrate`, `qp_crossover`) and the
    // active-set SQP QP-subproblem knobs (`sqp_qp_feas_tol`, `sqp_qp_opt_tol`,
    // `sqp_qp_max_iter`, `sqp_qp_elastic_gamma`, `sqp_qp_anti_cycling`) used to
    // be registered here. They now live in the core registry
    // (`pounce_algorithm::upstream_options`) so the library and Python paths
    // see them too — registering them here as well would raise
    // OPTION_ALREADY_REGISTERED and abort the binary at startup (gh #360 for
    // the SQP block, gh #604 for the convex one).

    // Opt into iter-history capture when the user asked for a JSON
    // report at Full detail — saves the per-iter alloc when they
    // didn't.
    if args.json_output.is_some() && matches!(args.json_detail, ReportDetail::Full) {
        app.enable_iter_history();
    }

    // Load the options file before the `key=value` overrides below, so a
    // command-line option beats a file option and not the other way round
    // — which is also why `option_file_name` has to be read off argv here
    // rather than out of the option store (upstream reads it from the
    // store at this same point, before the store has the CLI's values).
    //
    // Until gh#518 the only way in was `--options-file`: `option_file_name`
    // was refused, and the implicit `pounce.opt` / `ipopt.opt` lookup did
    // not exist, so a run configured entirely through an option file ran
    // at stock defaults and still reported success.
    let option_file_choice = match args.option_file_choice() {
        Ok(c) => c,
        Err(msg) => {
            eprintln!("pounce: {msg}");
            return ExitCode::from(2);
        }
    };
    let mut option_file_read: Option<PathBuf> = None;
    match &option_file_choice {
        pounce_cli::cli::OptionFileChoice::Suppressed => {
            if let Err(e) = app.initialize() {
                eprintln!("pounce: initialize failed: {e}");
                return ExitCode::from(2);
            }
        }
        choice => {
            let explicit = match choice {
                pounce_cli::cli::OptionFileChoice::Named(p) => Some(p.as_path()),
                _ => None,
            };
            match app.initialize_with_option_file(explicit) {
                Ok(load) => {
                    for warning in &load.warnings {
                        eprintln!("pounce: warning: {warning}");
                    }
                    option_file_read = load.path;
                }
                Err(e) => {
                    // `e.message` rather than the full `Display`: this one
                    // is read by whoever wrote the options file, and the
                    // C++-style "in file … at line …" prefix names a
                    // pounce source location, not theirs.
                    eprintln!("pounce: failed to load options file: {}", e.message);
                    return ExitCode::from(2);
                }
            }
        }
    }

    // Apply CLI `key=value` overrides after initialization, mirroring
    // how upstream's ipopt CLI lets command-line options override the
    // ipopt.opt file. Routed through `read_from_str` so the type
    // coercion (string / number / integer) matches the options-file
    // parser exactly.
    for (k, v) in &args.set_options {
        let line = format!("{k} {v}\n");
        if let Err(e) = app.options_mut().read_from_str(&line, true) {
            eprintln!("pounce: failed to set {k}={v}: {e}");
            return ExitCode::from(2);
        }
    }

    // Interactive solver debugger (`--debug` / `--debug-json`). Installs
    // a hook that pauses at each iteration. In JSON mode stdout becomes a
    // pure protocol channel: the per-iteration table, banner, problem
    // stats, and final summary are all silenced (the debugger and the
    // post-solve `terminated` event carry that information instead).
    let json_dbg = matches!(args.debug, Some(pounce_cli::cli::DebugMode::Json));
    // Shared slot the debugger's `resolve` command writes to; the
    // post-solve loop below reads it to re-run with new options.
    let restart_cell: pounce_cli::debug_repl::RestartCell = Rc::new(RefCell::new(None));
    // Held across `resolve` re-solves so the SAME debugger is reused rather
    // than rebuilt — keeps its single stdin-reader thread (no leak/contention),
    // its already-sent `hello`, and its breakpoints. The `--debug-script` is
    // consumed at the first pause, so reuse won't re-run it.
    let mut debug_hook: Option<Rc<RefCell<pounce_cli::debug_repl::SolverDebugger>>> = None;
    if let Some(mode) = args.debug {
        if json_dbg {
            let _ = app.options_mut().read_from_str("print_level 0\n", true);
        }
        let reg = Some(std::rc::Rc::clone(app.registered_options()));
        let hook = Rc::new(RefCell::new(build_debugger(
            mode,
            args.debug_on_error,
            args.debug_on_interrupt,
            args.debug_script.as_deref(),
            reg,
            restart_cell.clone(),
        )));
        app.set_debug_hook(hook.clone());
        debug_hook = Some(hook);
        // Install the Ctrl-C → break-into-debugger handler. All debug
        // modes are interruptible; this only changes Ctrl-C behavior
        // when a debugger is active.
        pounce_cli::debug_repl::interrupt::install();
        // Branded open banner (human REPL only).
        pounce_cli::debug_repl::print_open_banner(mode);
        let extra = if args.debug_on_error {
            ", on-error"
        } else if args.debug_on_interrupt {
            ", on-interrupt"
        } else {
            ""
        };
        eprintln!(
            "pounce: interactive debugger enabled ({}{}). Type `help` at the prompt; Ctrl-C breaks in.",
            match mode {
                pounce_cli::cli::DebugMode::Repl => "repl",
                pounce_cli::cli::DebugMode::Json => "json",
            },
            extra
        );
    }

    // Wire the restoration phase. Without this, any line-search failure
    // surfaces as `RestorationFailure` instead of falling back into the
    // ℓ1-feasibility sub-IPM. Mirrors what upstream's `IpAlgBuilder`
    // does unconditionally for every solve.
    //
    // Capture the feral config off the now-fully-loaded options so the
    // restoration sub-IPM honors the same `feral_*` overrides (e.g.
    // `feral_cascade_break yes` from an `--options-file`) as the main
    // IPM. Snapshot, not borrow: the BFF outlives the option-mutation
    // window we cleanly own here.
    let feral_cfg = pounce_algorithm::application::feral_config_from_options(app.options());
    // Same snapshot discipline for MA57, except that the restoration sub-IPM reads the `ma57_*` options again
    // under the `"resto."` prefix, which is upstream's
    // `Ma57TSolverInterface::InitializeImpl(options, prefix)` facility and was
    // dead code until gh#825 — nothing called it.
    let ma57_cfg = pounce_algorithm::application::ma57_config_from_options(app.options(), "resto.");
    // Use the multi-pass provider so the ℓ₁ wrapper (`l1_exact_penalty_barrier`)
    // and the auto-fallback (`l1_fallback_on_restoration_failure`) don't
    // panic with "restoration factory invoked more than once" on their
    // second inner solve — see pounce#10 Phase 3 / pounce#24.
    let bff_mint = move || -> InnerBackendFactoryFactory {
        let feral_cfg = feral_cfg.clone();
        let ma57_cfg = ma57_cfg.clone();
        Box::new(move || default_backend_factory(feral_cfg.clone(), ma57_cfg.clone()))
    };
    // Hand the inner IPM a builder mirroring the outer options so its
    // `mu_strategy` (adaptive vs. monotone) inherits the user's choice —
    // matches upstream `IpAlgBuilder::BuildRestoIpoptAlgorithm`.
    let resto_provider = make_default_restoration_factory_provider(
        RestoAlgorithmBuilder::new(),
        app.algorithm_builder_from_options(),
        bff_mint,
    );
    app.set_restoration_factory_provider(resto_provider);

    // gh#483 follow-up: refuse a `linear_solver` pounce does not
    // implement. Checked here — before the banner, and before the routing
    // that would send an LP/QP to `pounce-convex` without ever reaching
    // `optimize_tnlp`'s copy of this guard — so the verdict does not
    // depend on which engine the problem happens to classify into.
    if let Some(value) = app.unimplemented_linear_solver() {
        eprintln!(
            "{}",
            IpoptApplication::unimplemented_linear_solver_message(&value)
        );
        return ExitCode::from(2);
    }
    // Same treatment for every other option naming a feature pounce does
    // not implement, and the same reason for checking here: a model that
    // routes to `pounce-convex` never reaches `optimize_tnlp`, where the
    // library-side copy of this guard lives.
    if let Some(msg) = app
        .unimplemented_option_refusal()
        .or_else(|| app.unimplemented_option_value_refusal())
    {
        eprintln!("{msg}");
        return ExitCode::from(2);
    }
    // Knobs for a linear-solver backend pounce does not ship warn here
    // rather than refusing: an `ipopt.opt` that configures several
    // backends so one file runs everywhere is the compatibility the
    // registry exists to provide, and failing it over knobs this run
    // never touches would cost more than the silence did (gh#551).
    // `take_*`, not the plain getter: `optimize_tnlp` emits the same
    // warnings for every frontend that never passes through here, and a
    // CLI run reaches both sites. Printing the paragraph twice is how a
    // warning teaches its reader to skip warnings.
    let backend_warnings = app.take_unimplemented_backend_warnings();
    for warning in app
        .unexploited_hint_warnings()
        .into_iter()
        .chain(backend_warnings)
    {
        eprintln!("{warning}");
    }

    // gh#551 / gh#677: the sIPOPT keys (`run_sens`, `compute_red_hessian`,
    // `rh_eigendecomp`, `sens_boundcheck`, `sens_bound_eps`,
    // `sens_max_pdpert`) are registered so an sIPOPT `ipopt.opt` parses,
    // and until this read site existed setting one did nothing at all —
    // the same post-optimal work was reachable only through the `--*`
    // flags below. Read once, here, so the option and the flag agree
    // everywhere the request is consulted. Each option only ADDS to what
    // the flags asked for, except `run_sens=no` (upstream's spelling of
    // "do not take the step") — see `SensOptionOverrides` for why the
    // reader reports "explicitly set" rather than resolved defaults.
    let sens_options = pounce_sensitivity::SensOptionOverrides::from_options_list(app.options());

    // Branded logo + copyright banner, printed up-front — before the
    // problem is even read — so they head the output. `sb yes` suppresses
    // both (mirrors upstream `IpoptApplication::Initialize`).
    //
    // The registered default is `feral`, so the option's resolved value is
    // the whole story and the "was it explicitly set?" flag this used to
    // consult is no longer needed: `ma57` here always means someone asked
    // for it. (Under upstream's `ma57` default it did not, and the banner
    // would otherwise have claimed "ma57 requested" on every run.)
    let backend_tag = {
        let (v, _) = app
            .options()
            .get_string_value("linear_solver", "")
            .unwrap_or_else(|_| ("feral".to_string(), false));
        if v.eq_ignore_ascii_case("ma57") {
            #[cfg(feature = "ma57")]
            {
                "MA57 (HSL)"
            }
            #[cfg(not(feature = "ma57"))]
            {
                "FERAL (ma57 requested but not compiled)"
            }
        } else {
            "FERAL"
        }
    };
    let suppress_banner = app
        .options()
        .get_bool_value("sb", "")
        .ok()
        .and_then(|(v, f)| f.then_some(v))
        .unwrap_or(false);
    if !suppress_banner && !json_dbg {
        print::print_logo();
        print::print_banner(backend_tag);
    }
    // Which options file configured this run, on the same `sb` gate as the
    // banner (upstream prints its "Using option file" line here too). A
    // discovered file especially has to announce itself: nothing on the
    // command line hints that a `pounce.opt` sitting in the working
    // directory is steering the solve.
    if let Some(path) = &option_file_read {
        if !suppress_banner && !json_dbg {
            println!("Using option file \"{}\".\n", path.display());
        }
    }

    // Snapshot the problem source as a string — needed downstream by
    // the diagnostics manifest.
    let problem_desc: String = match &args.problem {
        ProblemSource::Builtin(s) => format!("builtin:{s}"),
        ProblemSource::NlFile(p) => format!("nl:{}", p.display()),
    };

    // Resolve where (if anywhere) to write an AMPL `.sol` solution
    // file. AMPL solver convention: a `.nl` input gets a sibling
    // `<stub>.sol` unless suppressed. Builtins have no stub on disk,
    // so they only produce a `.sol` when `--sol-output` is explicit.
    let sol_path: Option<PathBuf> = if args.no_sol {
        None
    } else if let Some(p) = &args.sol_output {
        Some(p.clone())
    } else {
        match &args.problem {
            ProblemSource::NlFile(p) => {
                let mut s = p.clone();
                s.set_extension("sol");
                Some(s)
            }
            ProblemSource::Builtin(_) => None,
        }
    };

    // Load the problem. For `.nl` inputs, keep the parsed suffixes and
    // dimensions around: the sIPOPT-style suffixes (`sens_state_1` …)
    // drive the post-optimal sensitivity step below, and they must be
    // read off `NlProblem` before `NlTnlp` consumes it.
    let mut nl_suffixes: Option<nl_reader::NlSuffixes> = None;
    let mut nl_dims: Option<(usize, usize)> = None;
    // The model's own AMPL option words, echoed back in the `.sol`
    // `Options` block the way an ASL solver does. Empty for problems
    // that did not come from a `.nl` header.
    let mut nl_ampl_options: Vec<i64> = Vec::new();
    // Problem class captured from the *first* `.nl` parse below, so the
    // LP/QP dispatch never has to re-read the file just to classify it
    // (re-parsing doubled parse time / peak memory on large models — code
    // review L24). `None` for builtins (treated as general NLP).
    let mut nl_class: Option<pounce_cli::dispatch::ProblemClass> = None;
    // gh #703: set alongside `nl_class` when curvature-based scaling is
    // switched on below, and only then. Records whether the model handed the
    // scheme any second-order coefficient to work with — see
    // `decline_convex_for_curvature_scaling` for why the answer decides
    // whether the request is worth the convex fast path.
    let mut nl_curvature_read_curvature = false;
    // `nl_expr_provider` shadows `inner_tnlp` for the `.nl`-file path:
    // both point at the same `NlTnlp`, but the second handle is typed
    // as `dyn ExpressionProvider` so the presolve wrapper can use it
    // for FBBT (issue #62). For built-in problems we leave it `None`.
    let mut nl_expr_provider: Option<
        Rc<RefCell<dyn pounce_nlp::expression_provider::ExpressionProvider>>,
    > = None;
    let inner_tnlp: Rc<RefCell<dyn TNLP>> = match &args.problem {
        ProblemSource::Builtin(name) => match builtin::lookup(name) {
            Some(t) => t,
            None => {
                eprintln!("pounce: unknown builtin problem '{name}'");
                eprintln!("available: {}", builtin::list().join(", "));
                return ExitCode::from(2);
            }
        },
        ProblemSource::NlFile(path) => {
            if !json_dbg {
                println!("Reading {}...", path.display());
            }
            let t0 = std::time::Instant::now();
            match nl_reader::read_nl_file(path) {
                Ok(prob) => {
                    nl_suffixes = Some(prob.suffixes.clone());
                    nl_dims = Some((prob.n, prob.m));
                    nl_ampl_options = prob.ampl_options.clone();
                    let elapsed = t0.elapsed().as_secs_f64();
                    // Render the source constraint equations and hand them to
                    // the debugger so `print equation <name|row>` can show a
                    // culprit constraint's algebra — the named-equation
                    // diagnostic of Lee et al. (2024,
                    // https://doi.org/10.69997/sct.147875). Built before
                    // `NlTnlp::new` moves `prob`.
                    if let Some(hook) = debug_hook.as_ref() {
                        let book = pounce_cli::debug_repl::EquationBook::new(
                            prob.con_names.clone(),
                            nl_reader::render_all_constraint_equations(&prob),
                        );
                        // Structural rank analysis of the equality Jacobian
                        // (Dulmage–Mendelsohn) so `diagnose` can name the
                        // dependent equations behind a singular system —
                        // Lee et al. (2024,
                        // https://doi.org/10.69997/sct.147875).
                        let (jac_irow, jac_jcol) = nl_reader::constraint_jacobian_sparsity(&prob);
                        let probe = pounce_presolve::incidence::ProbeView {
                            n_vars: prob.n,
                            m_rows: prob.m,
                            jac_irow: &jac_irow,
                            jac_jcol: &jac_jcol,
                            jac_values: None,
                            g_l: &prob.g_l,
                            g_u: &prob.g_u,
                            linearity: None,
                            one_based: false,
                            eq_tol: 1e-12,
                            excluded_vars: None,
                            excluded_rows: None,
                        };
                        let inc = pounce_presolve::incidence::EqualityIncidence::from_probe(&probe);
                        let structure = pounce_cli::debug_repl::StructureBook::new(
                            inc,
                            prob.con_names.clone(),
                            prob.var_names.clone(),
                        );
                        let mut h = hook.borrow_mut();
                        h.set_equation_book(book);
                        h.set_structure_book(structure);
                    }
                    // Classify now, while we still own `prob` (it's about to
                    // be moved into `NlTnlp`). Saves a second full parse in the
                    // LP/QP dispatch block below.
                    nl_class = Some(pounce_cli::dispatch::classify_problem(&prob));
                    let nl_rc = Rc::new(RefCell::new(nl_reader::NlTnlp::new(prob)));
                    // gh #703: `nlp_scaling_method=curvature-based` derives
                    // its factors from the model's coefficients, so it has
                    // to be switched on here — while the handle is still
                    // the concrete `NlTnlp` that owns them, and before any
                    // wrapper (presolve, penalty, the variable-scaling
                    // substitution itself) sits in front of it. The
                    // wrappers forward `get_scaling_parameters` and project
                    // the indices, so the factors reach the engine through
                    // the channel user factors already use.
                    if curvature_scaling_requested(&app)
                        && !nl_rc.borrow_mut().enable_curvature_scaling()
                    {
                        eprintln!(
                            "pounce: nlp_scaling_method=curvature-based needs \
                             every row and the objective to be degree <= 2 (it \
                             scales a model by its quadratic coefficients, and \
                             a genuine nonlinearity has none). This model has \
                             at least one row it cannot read that way. Use \
                             gradient-based, or user-scaling with your own \
                             scaling_factor suffixes."
                        );
                        return ExitCode::from(2);
                    }
                    nl_curvature_read_curvature = nl_rc.borrow().curvature_scaling_read_curvature();
                    nl_expr_provider = Some(Rc::clone(&nl_rc)
                        as Rc<RefCell<dyn pounce_nlp::expression_provider::ExpressionProvider>>);
                    let t: Rc<RefCell<dyn TNLP>> = nl_rc;
                    if let Some(info) = t.borrow_mut().get_nlp_info() {
                        if !json_dbg {
                            println!(
                                "Parsed {} vars, {} cons, jac_nnz={}, h_nnz={} in {:.2}s",
                                info.n, info.m, info.nnz_jac_g, info.nnz_h_lag, elapsed
                            );
                        }
                    }
                    t
                }
                Err(e) => {
                    eprintln!("pounce: failed to read {}: {e}", path.display());
                    return ExitCode::from(2);
                }
            }
        }
    };

    // issue #196 (and related): does the .nl / CLI request post-optimal work
    // that only the general NLP filter-IPM path provides — the sIPOPT
    // parametric sensitivity step (sens_* suffixes) or a reduced-Hessian
    // computation (--compute-red-hessian)? Neither the --minima multistart
    // driver nor the specialized convex solvers run it, so detect it up front
    // and make sure no path silently drops the request.
    let declares_sens_suffixes = nl_suffixes
        .as_ref()
        .map(sens::is_sensitivity_input)
        .unwrap_or(false);
    // `run_sens=no` is the one option that takes work away: it is how
    // upstream says "solve, but do not take the sensitivity step", and
    // without it a `.nl` carrying the suffixes has no off switch.
    let wants_sens = declares_sens_suffixes && !sens_options.suppresses_sens_step();
    // `compute_red_hessian=yes` reaches the same computation as
    // `--compute-red-hessian`; `rh_eigendecomp=yes` implies it, exactly
    // as `--rh-eigendecomp` does.
    let wants_red_hessian = args.compute_red_hessian || sens_options.wants_reduced_hessian();
    let wants_nlp_postopt = wants_sens || wants_red_hessian;
    // gh#483: does the run ask for user NLP scaling — `nlp_scaling_method=
    // user-scaling` together with at least one `scaling_factor` suffix in the
    // `.nl` for the solver to read? Only the general NLP path implements the
    // scaling callback, so this gates the same "reroute or warn" treatment
    // the post-optimal request gets, rather than the option quietly meaning
    // "no scaling" on a specialized path.
    let wants_user_scaling = app
        .options()
        .get_string_value("nlp_scaling_method", "")
        .ok()
        .and_then(|(v, set)| set.then_some(v))
        .is_some_and(|v| v == "user-scaling")
        && nl_suffixes.as_ref().is_some_and(|s| {
            s.obj_real.contains_key("scaling_factor")
                || s.con_real.contains_key("scaling_factor")
                || s.var_real.contains_key("scaling_factor")
        });
    // gh #703, gh#483 again: `nlp_scaling_method=curvature-based` reaches the
    // engine through exactly the same channel as `user-scaling` — the TNLP's
    // `get_scaling_parameters` callback — and the convex solvers do not call
    // it. They equilibrate internally, so routing a curvature-scaling request
    // there accepts the option and means "not this scaling".
    //
    // That is not a corner case for *this* option: the models it is defined
    // for are the models with quadratic rows, which is precisely the
    // population `classify_problem` sends to the convex path. Both fixtures
    // gh #703 added are convex QCQPs, and of the 47 corpus models the option
    // accepts, 38 classify convex. Without this gate the headline feature is
    // inert by default on the majority of the models it exists for, which is
    // the gh#483 failure verbatim.
    let wants_curvature_scaling = curvature_scaling_requested(&app);
    // gh#483 follow-up: `obj_scaling_factor` is an NLP-path knob — the convex
    // solvers run their own equilibration and never read it. A *negative*
    // factor is upstream's documented spelling for "maximize", so dropping it
    // does not merely leave the conditioning alone: the convex path minimizes
    // an objective the user asked to maximize and reports the wrong optimum
    // with no complaint. (`min (x−3)²` over `x ∈ [0,1]` with
    // `obj_scaling_factor=-1` returned `x = 1`, the minimizer, instead of
    // `x = 0`.) A *positive* factor is genuinely inert on that path — it
    // reports natural units already, so both paths give the same answer — and
    // is deliberately not treated as a conflict.
    //
    // There are *two* channels into the same sign flip, and the guard has to
    // watch both. The option is one. The other is the `.nl`'s objective
    // `scaling_factor` suffix under `nlp_scaling_method=user-scaling`:
    // `scale_user_supplied` installs it as `df` with no sign guard, so a
    // negative entry maximizes exactly as the option does. Watching only the
    // option left `scaling_factor[obj] = -1` plus a forced convex solver
    // returning the minimizer with an "the requested scaling will be skipped"
    // warning — which understates it, since what is skipped is the objective
    // sense, not conditioning. Found by adversarial testing of this guard.
    let negative_obj_scaling_option = app
        .options()
        .get_numeric_value("obj_scaling_factor", "")
        .ok()
        .and_then(|(v, set)| set.then_some(v))
        .is_some_and(|v| v < 0.0);
    let negative_obj_scaling_suffix = wants_user_scaling
        && nl_suffixes.as_ref().is_some_and(|s| {
            s.obj_real
                .get("scaling_factor")
                .and_then(|v| v.first())
                .is_some_and(|&f| f < 0.0)
        });
    let maximize_via_obj_scaling = negative_obj_scaling_option || negative_obj_scaling_suffix;
    // Human-readable description of the requested post-optimal work, reused in
    // the "not available on this path" messages below.
    let postopt_what = match (wants_sens, wants_red_hessian) {
        (true, true) => {
            "a parametric sensitivity step (sIPOPT sens_* suffixes) and a \
             reduced-Hessian computation"
        }
        (true, false) => "a parametric sensitivity step (sIPOPT sens_* suffixes)",
        _ => "a reduced-Hessian computation",
    };

    // Multistart / find-minima: when a `--minima` method is set, drive the
    // local solver in a loop over the *raw* problem TNLP (presolve / counting
    // wrappers are intentionally bypassed so coordinates match the original
    // problem and the clean objective is evaluated directly) and return.
    if let Some(mcfg) = &args.minima {
        // Related to #196: --minima is a multistart search, not a single
        // post-optimal solve, so it does not run the sIPOPT sensitivity /
        // reduced-Hessian step. Warn rather than silently drop the request
        // (sensitivity at a multistart optimum is ill-defined).
        if wants_nlp_postopt {
            eprintln!(
                "pounce: warning: the .nl requests {postopt_what}, but --minima \
                 runs a multistart search that does not compute it; the request \
                 will be skipped. Run without --minima to obtain it."
            );
        }
        app.set_presolve_already_applied(true);
        return pounce_cli::minima::run(&mut app, &inner_tnlp, mcfg, &args, sol_path.as_deref());
    }

    // LP/QP routing (Phase 1). Resolve the `solver_selection` option
    // against the detected problem class. For `.nl` inputs we classify
    // the parsed problem; for builtins we conservatively treat the class
    // as NLP (they are general nonlinear test problems). `auto`/`nlp`
    // both route to the existing solver — the only observable effect in
    // Phase 1 is that an explicit forcing value (e.g. `--solver=lp`)
    // that does not match the detected class is rejected with a clear
    // message, instead of being silently ignored.
    {
        use pounce_cli::dispatch::{ProblemClass, SolverChoice, SolverSelection, resolve_solver};
        let sel_str = app
            .options()
            .get_string_value("solver_selection", "")
            .map(|(v, _)| v)
            .unwrap_or_else(|_| "auto".to_string());
        let selection = match SolverSelection::parse(&sel_str) {
            Some(s) => s,
            None => {
                eprintln!(
                    "pounce: invalid solver_selection '{sel_str}'; valid values: {}",
                    SolverSelection::VALUES.join(", ")
                );
                return ExitCode::from(2);
            }
        };

        // Problem class. The `.nl` path was already classified during the
        // initial parse above (`nl_class`) — we do NOT re-read the file here
        // (re-parsing doubled parse time / peak memory on large models, and
        // its error arm silently fell back to NLP; code review L24). Builtins
        // are treated as general NLP.
        let class = match &args.problem {
            ProblemSource::NlFile(_) => nl_class.unwrap_or(ProblemClass::Nlp),
            ProblemSource::Builtin(_) => ProblemClass::Nlp,
        };

        let choice = match resolve_solver(class, selection) {
            Ok(c) => c,
            Err(msg) => {
                eprintln!("pounce: {msg}");
                return ExitCode::from(2);
            }
        };

        // issue #196: `wants_sens` / `wants_nlp_postopt` / `postopt_what` were
        // computed above (they also gate the --minima warning). Under `auto`,
        // decline the convex fast-path and fall through to the NLP filter-IPM
        // (which honors the request — correctness over the specialized path's
        // speed); under an explicit convex solver_selection, respect the forced
        // choice but warn (below) instead of silently skipping.
        //
        // The convex arm has a parametric step of its own now
        // (`pounce_convex::QpSensitivity`, reached through
        // `pounce_cli::convex_sens`), so this decline is narrowed to the
        // capability it still lacks rather than to "any post-optimal request".
        // What it can serve is a **parametric step on an LP or convex QP whose
        // pins are equality rows** — see `convex_sens::resolve_pins`, which is
        // where the request stops being expressible and the run falls back.
        //
        // What still reroutes, and why each is a capability rather than an
        // oversight:
        //
        // * **A reduced-Hessian request.** `QpSensitivity::reduced_hessian`
        //   exists, but it is a *different computation* behind the same word —
        //   a null-space projection where the CLI's `sens::try_compute_red_hessian`
        //   takes sIPOPT's Schur route. Serving it here would silently change
        //   which number `--compute-red-hessian` returns. CLAUDE.md names this
        //   as a deliberate non-goal; honoring it means routing.
        // * **The conic path** (`SolverChoice::SocpIpm`). `build_conic` can
        //   answer for every cone family, but the CLI's conic route extracts
        //   through `extract_socp_with_map` into a different provenance map,
        //   and mapping pins through *that* is its own index space. Not
        //   started, so not claimed.
        // * **The active-set engine** (`SolverChoice::QpActiveSet`). It returns
        //   a vertex solution the orthant guard accepts, but its degenerate
        //   bases are exactly the case `QpSensitivity` flags as
        //   `lp_without_crossover`, and that interaction is unmeasured here.
        let convex_can_serve_sens = wants_sens
            && !wants_red_hessian
            && matches!(choice, SolverChoice::LpIpm | SolverChoice::QpIpm);
        let decline_convex_for_postopt = wants_nlp_postopt
            && matches!(selection, SolverSelection::Auto)
            && !convex_can_serve_sens;

        // gh#483: same bargain for user NLP scaling. `nlp_scaling_method=
        // user-scaling` plus the `.nl`'s `scaling_factor` suffixes is honored
        // by the general NLP interior-point path only — the convex solvers run
        // their own internal equilibration and never see the TNLP's scaling
        // callback, so routing there would accept the option and mean "none".
        let decline_convex_for_user_scaling =
            wants_user_scaling && matches!(selection, SolverSelection::Auto);

        // gh #703: and again for curvature-based scaling, for the same reason
        // and through the same callback — but only when the model handed the
        // scheme some curvature to read.
        //
        // The `user-scaling` gate above already has this shape: it requires
        // the option *and* a `scaling_factor` suffix in the `.nl` for the
        // solver to read, because rerouting a model that carries no suffixes
        // buys a different engine and nothing else. The same test applies
        // here, and it is not cosmetic. Leaving it out was measured on the
        // corpus: `nlp_scaling_method=curvature-based` on `lp_israel`, a pure
        // LP, went from 29 iterations on the convex path to 296 on the
        // general one — 29 → 135 for the engine and 135 → 296 for a scaling
        // scheme whose defining input, `Qᵢ`, is empty in every row. On an LP
        // §8 degenerates to Ruiz equilibration of `[A b]`, which is what
        // `pounce-convex` already does internally, so the fast path is not
        // "quietly meaning none" here — it is doing the same kind of work by
        // its own route. That is a claim worth making out loud rather than
        // silently, so the no-curvature case still prints (below); what it
        // does not do is pay for an engine switch that cannot help.
        let decline_convex_for_curvature_scaling = wants_curvature_scaling
            && nl_curvature_read_curvature
            && matches!(selection, SolverSelection::Auto);

        // gh#483 follow-up: a negative `obj_scaling_factor` means maximize,
        // which the convex path cannot express. Unlike the two requests above
        // — where the fast path merely skips *extra* work — taking it here
        // returns the wrong optimum, so under an explicit `solver_selection`
        // this is refused outright below rather than warned about.
        let decline_convex_for_obj_scaling =
            maximize_via_obj_scaling && matches!(selection, SolverSelection::Auto);
        // Any of these declines the fast path; the messages below say which.
        let decline_convex = decline_convex_for_postopt
            || decline_convex_for_user_scaling
            || decline_convex_for_curvature_scaling
            || decline_convex_for_obj_scaling;

        // Same bargain for a conic solve that finishes without a verified KKT
        // point: under `auto` the class was our inference, not the user's
        // instruction, so fall through to the NLP filter-IPM (a convex QCQP is
        // also a valid NLP) rather than reporting a failure the general path
        // can solve. Under an explicit `solver_selection` the forced choice is
        // respected and the conic verdict stands — the user asked for that
        // engine and silently answering from a different one would hide it.
        let socp_nlp_fallback = matches!(selection, SolverSelection::Auto);

        // gh #535: and the same bargain again for an LP the convex IPM cannot
        // certify. `auto` for the same reason as above — the LP classification
        // was our inference, so a failure to certify it is ours to fix, while a
        // named engine keeps its verdict. Additionally suppressed when the user
        // set `max_iter` (their budget is the question being answered, and
        // `max_iter=0` must stop without a solve, pounce#186) and when the
        // interactive debugger is attached (the user is stepping *this* engine;
        // silently continuing into a different one would strand the session).
        // See `lp_declines_to_nlp` for the rest of the gating.
        let lp_nlp_fallback = matches!(selection, SolverSelection::Auto)
            && debug_hook.is_none()
            && !max_iter_explicitly_set(&app);

        // Banner-level routing line: report the detected problem class and
        // which of pounce's solvers was selected for it. Gated like the
        // banner (suppressed by `sb yes` and in JSON-debug protocol mode) so
        // stdout stays clean for machine consumers. When we decline the convex
        // fast-path for a post-optimal request (#196), report the NLP path that
        // actually runs, not the convex one `resolve_solver` picked.
        if !suppress_banner && !json_dbg {
            // `algorithm=active-set-sqp` is invisible to `resolve_solver`,
            // which routes on `solver_selection` alone — and that is `auto`
            // on a general NLP no matter how `algorithm` is set. So until
            // this check existed the line read "NLP filter line-search
            // interior-point (pounce-nlp)" on every active-set SQP run: not
            // merely uninformative but the opposite of what happened, on the
            // one line a user reads to confirm which engine they got. The
            // banner above it is worse still (it is a fixed string naming the
            // interior point), so this line is the whole budget.
            //
            // Asked of the application rather than re-derived here, so the
            // announcement and the dispatch cannot disagree; a convex decline
            // still wins, because those routes never reach the SQP driver.
            // Gated on actually reaching the general NLP route, because
            // `is_sqp_algorithm_selected` is also true for
            // `solver_selection=qp-active-set` — and that value routes an LP
            // or convex QP to `pounce_convex::active_set`, a different engine
            // that `choice.describe()` already names correctly. Likewise
            // `algorithm=active-set-sqp` on an LP under `auto` is routed to
            // the convex IPM and never reaches the SQP driver at all, so the
            // `algorithm` option alone does not license this branch.
            let reaches_nlp_route = decline_convex || matches!(choice, SolverChoice::Nlp);
            let described = if reaches_nlp_route {
                if app.is_sqp_algorithm_selected() {
                    "active-set SQP (pounce-qp subproblems)"
                } else {
                    SolverChoice::Nlp.describe()
                }
            } else {
                choice.describe()
            };
            println!(
                "Problem class: {}. Selected solver: {} [solver_selection={}].",
                class.name(),
                described,
                sel_str
            );
            println!();
        }

        // Dispatch to the specialized convex solvers when resolved.
        // `LpIpm`/`QpIpm` use the convex QP IPM (LP is P = 0); `SocpIpm`
        // reformulates a convex QCQP to second-order cones and uses the
        // conic IPM. Both live in `pounce-convex`.
        //
        // `QpActiveSet` joins them here rather than routing through the SQP
        // outer loop as it used to. The engine is different, but everything
        // wrapped around it — QP extraction, presolve, postsolve, `.sol`
        // writing, status vocabulary, timing — is shared with the IPM, and
        // that shared wrapper is the entire point: the active-set engine had
        // been running with no presolve and no scaling, which costs an
        // active-set method far more than it costs an IPM (its pivot count
        // grows with the problem, an IPM's essentially does not). See
        // `pounce_convex::active_set` for the full rationale.
        if matches!(
            choice,
            SolverChoice::LpIpm
                | SolverChoice::QpIpm
                | SolverChoice::SocpIpm
                | SolverChoice::QpActiveSet
        ) {
            // gh#483 follow-up: `derivative_test` is about the *model*,
            // not the engine, so on the convex route it is run here rather
            // than declined — this dispatch never reaches `optimize_tnlp`,
            // where the NLP path's copy lives. Checking the raw
            // `inner_tnlp` keeps the report in the user's own indices, and
            // running it here (not there) means it cannot fire twice.
            app.run_derivative_test(&inner_tnlp);
            // Same reason, same place: `install_constant_derivative_hints`
            // lives behind `optimize_tnlp`, so on this route the four
            // constant-derivative hints are read by nothing. gh #588 Q6
            // emptied the NLP path's unexploited-hint table — correctly,
            // it exploits them now — and that silenced the convex route's
            // warning too. Say it here, where the route is known.
            for warning in app.convex_unexploited_hint_warnings() {
                eprintln!("{warning}");
            }
            // gh#483 follow-up: a forced convex solver plus a negative
            // `obj_scaling_factor` has no honest outcome — the engine cannot
            // maximize, and running it anyway hands back the minimizer of the
            // problem the user asked to maximize. Refuse, the way a
            // class/solver mismatch is refused, instead of warning and
            // returning a wrong answer.
            if maximize_via_obj_scaling && !decline_convex_for_obj_scaling {
                eprintln!(
                    "pounce: the objective scaling is negative (maximize) — via \
                     obj_scaling_factor or the .nl's `scaling_factor` suffix — \
                     but solver_selection={sel_str} forces the convex solver \
                     (pounce-convex), which minimizes and does not read that \
                     option — it would report the minimizer of the objective \
                     you asked to maximize. Use solver_selection=nlp or auto \
                     (which routes here automatically), or negate the \
                     objective in the model and drop obj_scaling_factor."
                );
                return ExitCode::from(2);
            }
            // issue #196: if the .nl requested a sensitivity / reduced-Hessian
            // step, either reroute (auto) or warn (explicit convex force) so
            // the fast path never silently drops it.
            if wants_nlp_postopt {
                if decline_convex_for_postopt {
                    eprintln!(
                        "pounce: note: this problem classifies as {} but the .nl \
                         requests {postopt_what}, which the convex solver \
                         (pounce-convex) does not provide; routing to the general \
                         NLP interior-point path so the request is honored.",
                        class.name()
                    );
                } else if convex_can_serve_sens {
                    // Served where it was solved. Said out loud because it is a
                    // routing change: the same input used to run on a different
                    // engine, and a user comparing two versions deserves to see
                    // which one answered.
                    eprintln!(
                        "pounce: note: the .nl requests {postopt_what}; the convex \
                         solver (pounce-convex) computes it directly on this {}\
                         no reroute to the general NLP path is needed.",
                        class.name()
                    );
                } else {
                    eprintln!(
                        "pounce: warning: the .nl requests {postopt_what}, but \
                         solver_selection={sel_str} forces the convex solver \
                         (pounce-convex), which does not compute it; the request \
                         will be skipped. Use solver_selection=nlp or auto to \
                         obtain it."
                    );
                }
            }
            // gh#483: same treatment for `nlp_scaling_method=user-scaling`.
            if wants_user_scaling {
                if decline_convex_for_user_scaling {
                    eprintln!(
                        "pounce: note: this problem classifies as {} but \
                         nlp_scaling_method=user-scaling asks for the .nl's \
                         `scaling_factor` suffixes to be applied, which the \
                         convex solver (pounce-convex) does not do; routing to \
                         the general NLP interior-point path so the scaling is \
                         honored.",
                        class.name()
                    );
                } else {
                    eprintln!(
                        "pounce: warning: nlp_scaling_method=user-scaling asks \
                         for the .nl's `scaling_factor` suffixes to be applied, \
                         but solver_selection={sel_str} forces the convex solver \
                         (pounce-convex), which equilibrates internally and does \
                         not read them; the requested scaling will be skipped. \
                         Use solver_selection=nlp or auto to apply it."
                    );
                }
            }
            // gh #703: same treatment for `nlp_scaling_method=curvature-based`,
            // with a third case the other requests do not have — a model that
            // is degree <= 2 (so the option was accepted) but carries no
            // second-order coefficient at all.
            if wants_curvature_scaling {
                if decline_convex_for_curvature_scaling {
                    eprintln!(
                        "pounce: note: this problem classifies as {} but \
                         nlp_scaling_method=curvature-based asks for factors \
                         derived from the model's quadratic coefficients, which \
                         the convex solver (pounce-convex) does not read; \
                         routing to the general NLP interior-point path so the \
                         scaling is honored.",
                        class.name()
                    );
                } else if !nl_curvature_read_curvature {
                    eprintln!(
                        "pounce: note: nlp_scaling_method=curvature-based was \
                         accepted, but every quadratic coefficient in this \
                         model is zero, so the scheme reduces to Ruiz \
                         equilibration of the linear rows; the convex solver \
                         (pounce-convex) equilibrates internally and keeps the \
                         fast path. Use solver_selection=nlp to run the scheme \
                         on the general path anyway."
                    );
                } else {
                    eprintln!(
                        "pounce: warning: nlp_scaling_method=curvature-based \
                         asks for factors derived from the model's quadratic \
                         coefficients, but solver_selection={sel_str} forces \
                         the convex solver (pounce-convex), which equilibrates \
                         internally and does not read them; the requested \
                         scaling will be skipped. Use solver_selection=nlp or \
                         auto to apply it."
                    );
                }
            }
            // gh#483 follow-up: the auto-reroute half of the negative
            // `obj_scaling_factor` case (the forced half exited above).
            if decline_convex_for_obj_scaling {
                eprintln!(
                    "pounce: note: this problem classifies as {} but \
                     obj_scaling_factor is negative (maximize), which the \
                     convex solver (pounce-convex) cannot express; routing to \
                     the general NLP interior-point path so the objective \
                     sense is honored.",
                    class.name()
                );
            }
            // The convex solvers need the parsed `NlProblem`, but the initial
            // parse moved it into `NlTnlp`. Re-parse the file here — only on
            // the convex dispatch path (LP / convex-QP / SOCP), never for a
            // general NLP solve. Only `.nl` inputs ever classify as convex, so
            // the builtin arm falls through to NLP. A parse failure surfaces
            // and exits rather than silently mis-routing to NLP (L24).
            if decline_convex {
                // Declined for #196 / gh#483: fall through to the NLP solve
                // below, which runs the sensitivity / reduced-Hessian step in
                // `on_converged` (writing `sens_sol_state_1` to the `.sol`) and
                // reads the `scaling_factor` suffixes through the TNLP scaling
                // callback.
            } else if let ProblemSource::NlFile(path) = &args.problem {
                let prob = match nl_reader::read_nl_file(path) {
                    Ok(p) => p,
                    Err(e) => {
                        eprintln!(
                            "pounce: failed to re-read {} for the convex solver: {e}",
                            path.display()
                        );
                        return ExitCode::from(2);
                    }
                };
                // JSON solve report, when requested — same schema as the NLP
                // path, so the benchmark harness can compare convex and NLP
                // solves.
                let json_cfg = args.json_output.as_deref().map(|p| {
                    let input = InputDescriptor::NlFile {
                        path: path.clone(),
                        size_bytes: std::fs::metadata(path).ok().map(|m| m.len()),
                    };
                    (p, args.json_detail, input)
                });
                // Materialize the convex controls in pounce-convex, which owns
                // their typed representation and precedence rules. In
                // particular, unset shared NLP options must not replace the
                // convex driver's independently tuned defaults.
                let convex_opts =
                    match pounce_convex::QpOptions::try_from_options_list(app.options()) {
                        Ok(options) => options,
                        Err(error) => {
                            eprintln!("pounce: convex option setup failed: {error}");
                            return ExitCode::from(2);
                        }
                    };
                // gh #744/#745: the same `bound_relax_factor` widening the NLP
                // path applies, so both arms solve one model.
                let bound_relax = convex_bound_relax(&app);
                // When the convex attempt declines (gh #535 / `socp_nlp_fallback`)
                // the NLP solve below opens its own `Deadline` from the *option
                // value*, which still names the full budget — so a run that spent
                // most of `max_wall_time` here would be granted it again there,
                // and the user's cap would buy up to twice the wall clock they
                // asked for. Charge the declined attempt against the budget; see
                // the deduction below the block.
                let convex_t0 = std::time::Instant::now();
                // Resolve the convex-path presolve switch (#139) once, above
                // the driver split: both convex drivers honour it.
                let presolve_on = match pounce_convex::ConvexPresolveOptions::try_from_options_list(
                    app.options(),
                ) {
                    Ok(options) => options.enabled,
                    Err(error) => {
                        eprintln!("pounce: convex presolve setup failed: {error}");
                        return ExitCode::from(2);
                    }
                };
                if matches!(choice, SolverChoice::SocpIpm) {
                    // `None` means the conic solve came back without a verified
                    // KKT point and declined the problem (only possible under
                    // `auto` — see `socp_nlp_fallback`). It printed and wrote
                    // nothing, so control falls out of this whole block to the
                    // NLP solve below, which produces the one and only verdict.
                    if let Some(code) = run_convex_socp(
                        &prob,
                        class,
                        sol_path.as_deref(),
                        json_cfg,
                        debug_hook.as_ref(),
                        args.ampl,
                        convex_opts,
                        bound_relax,
                        presolve_on,
                        socp_nlp_fallback,
                        convex_console(&app, json_dbg),
                    ) {
                        return code;
                    }
                } else {
                    // The interactive debugger is a pdb-for-the-IPM: it pauses on
                    // barrier-IPM iterations (mu, search direction, fraction-to-
                    // the-boundary). The active-set engine is a different
                    // algorithm with no such hook, so a `--debug*` request would
                    // otherwise silently no-op. Say so explicitly.
                    // Forward the `sqp_qp_*` family to the inner engine. Only
                    // explicit settings materialize as overrides, leaving the
                    // direct driver's tuned defaults intact otherwise.
                    let engine_overrides =
                        match pounce_convex::ActiveSetOverrides::try_from_options_list(
                            app.options(),
                        ) {
                            Ok(options) => options,
                            Err(error) => {
                                eprintln!("pounce: active-set option setup failed: {error}");
                                return ExitCode::from(2);
                            }
                        };
                    if matches!(choice, SolverChoice::QpActiveSet) && debug_hook.is_some() {
                        eprintln!(
                            "pounce: note: the interactive debugger is IPM-only and does \
                             not engage on the active-set QP engine (solver_selection=\
                             qp-active-set); the solve runs without pausing. Use \
                             solver_selection=qp-ipm to debug a convex QP interactively."
                        );
                    }
                    // `None` means the convex solve finished an LP without a
                    // certificate and declined it (gh #535, `auto` only — see
                    // `lp_nlp_fallback`). It printed no verdict and wrote no
                    // `.sol`/JSON, so control falls out of this whole block to
                    // the NLP solve below, which owns the one verdict.
                    if let Some(code) = run_convex_qp(
                        &prob,
                        class,
                        sol_path.as_deref(),
                        // A run that serves a sensitivity request presolves
                        // nothing, and the reason is narrower than it first
                        // looks — worth writing down, because the obvious
                        // reason is wrong.
                        //
                        // It is NOT that presolve's row space would break the
                        // pins. This driver postsolves back to the
                        // extracted-QP space before anything downstream runs
                        // (the same property `con_map`'s dual recovery needs),
                        // so `QpSensitivity` is built on the unpresolved `qp`
                        // and the pin indices stay valid. Measured, not
                        // reasoned: with presolve left on, the step on
                        // `convex_qp_sens.nl` still lands within `1e-6` of the
                        // NLP path's.
                        //
                        // What it *is*: on that fixture presolve fixes the
                        // parameter the pin parametrizes and drops its row
                        // ("3 → 2 vars, 1 → 0 rows, fixed 1"), so the KKT the
                        // sensitivity reads is a postsolve reconstruction
                        // rather than the one the solve converged. The step
                        // costs four orders of accuracy for it — `5.0e-11`
                        // against `6.2e-15` — and that is on the one fixture
                        // that exercises this at all. Whether a reconstructed
                        // bound multiplier can also move the *active set* the
                        // sensitivity infers is unmeasured, and a wrong active
                        // set is a wrong derivative rather than a less
                        // accurate one.
                        //
                        // The NLP path makes the same trade (see
                        // `presolve_opts.enabled = false` below). Presolving a
                        // sensitivity run is a real option and a separate
                        // change, and it needs a fixture that reaches the
                        // active-set question.
                        presolve_on && !convex_can_serve_sens,
                        json_cfg,
                        debug_hook.as_ref(),
                        args.ampl,
                        convex_opts,
                        bound_relax,
                        matches!(choice, SolverChoice::QpActiveSet),
                        engine_overrides,
                        lp_nlp_fallback,
                        convex_console(&app, json_dbg),
                        convex_can_serve_sens
                            .then(|| nl_suffixes.as_ref())
                            .flatten(),
                        // Under `auto` the class was our inference, so an
                        // inexpressible pin is ours to hand back. Under an
                        // explicit convex `solver_selection` the user named the
                        // engine, and silently answering from a different one
                        // would hide that — so there the step is skipped with a
                        // warning, exactly as it was before this path existed.
                        matches!(selection, SolverSelection::Auto),
                    ) {
                        return code;
                    }
                }
                // Reaching here means the convex attempt declined and the NLP
                // path below owns the verdict; charge it for the time it spent.
                charge_wall_budget(app.options_mut(), convex_t0.elapsed());
                // ...and make that path solve the model the caller DECLARED,
                // which is the whole point of the reroute.
                //
                // Without this the fallback hands the model to the one arm
                // that still applies `bound_relax_factor`, so a route
                // introduced to rescue a declined solve answers a different
                // question than the one asked. Measured on
                // `scaled_feasible_a`: the rerouted point sits **2679.85**
                // outside the declared model — its rows reach `|b| = 2.65e13`
                // and the row width is relative (gh #385) — while reporting
                // `Solve_Succeeded` at `Constraint violation 7.45e-09`. That
                // is the exact failure this branch exists to remove, reached
                // through the mechanism added to repair its one regression.
                //
                // Unset-means-declared is the same rule the convex arm now
                // follows, so `pounce foo.nl` solves one model whichever arm
                // answers. An explicit `bound_relax_factor` is still honoured
                // and still buys Ipopt's model, exactly as
                // `solver_selection=nlp` does — neither is a default.
                if !matches!(
                    app.options().get_numeric_value("bound_relax_factor", ""),
                    Ok((_, true))
                ) {
                    // The discarded `Result<bool, _>` is dead, and provably so
                    // rather than incidentally: `Ok(false)` means "clobber
                    // refused, nothing written", which here would silently
                    // leave the widening on — the very defect this restores.
                    // It cannot happen, because the guard above is exactly
                    // complementary to the refusal. `get_numeric_value`
                    // reports `set == true` iff the tag is in the user's map
                    // (`options_list.rs`, `find_tag`), and `will_allow_clobber`
                    // returns true iff it is ABSENT from that same map. Guard
                    // false ⟹ absent ⟹ clobber allowed ⟹ the write lands.
                    let _ =
                        app.options_mut()
                            .set_numeric_value("bound_relax_factor", 0.0, true, true);
                }
            }
            // Builtins never classify as convex; fall through to NLP.
        }
        // `qp-active-set` no longer lands here: it is dispatched with the
        // other convex engines above, straight into `pounce-qp` via
        // `pounce_convex::active_set`, rather than being rewritten to
        // `algorithm=active-set-sqp` and run through the SQP outer loop.
        // Wrapping a QP in an SQP was never wrong — with an exact Hessian and
        // already-linear constraints the first subproblem *is* the original QP
        // — but it forfeited the convex path's presolve, scaling, timing, and
        // status vocabulary in exchange for machinery a QP has no use for.
        // The SQP route remains for genuine NLPs via `algorithm=active-set-sqp`,
        // where the outer loop is doing real work.
        //
        // `nlp` and any unmatched case fall through to the existing NLP
        // solve below unchanged.
        let _ = choice;
    }

    // Does the `.nl` ask for a parametric sensitivity step? When it
    // does, the post-optimal step runs inside `on_converged` below and
    // its result is written back as the `sens_sol_state_1` suffix.
    // `run_sens=no` turns that off (gh#551); `run_sens=yes` cannot turn
    // it *on* — the perturbation itself is declared by the suffixes and
    // there is nothing to step without them, so say so rather than
    // solve and silently report nothing.
    let sens_active = wants_sens;
    if sens_options.run_sens == Some(true) && !declares_sens_suffixes {
        eprintln!(
            "pounce: warning: `run_sens=yes` asks for a parametric sensitivity \
             step, but the input declares none of the sIPOPT suffixes \
             (sens_state_1, sens_state_value_1, sens_init_constr) that say \
             which parameter to perturb; no step will be computed."
        );
    }
    if sens_options.suppresses_sens_step() && declares_sens_suffixes {
        eprintln!(
            "pounce: `run_sens=no` — solving without the parametric \
             sensitivity step the input's sIPOPT suffixes ask for."
        );
    }

    // Capture the converged primal / dual into `nominal_capture` so the
    // JSON report and `.sol` below can ship `solution.x` /
    // `solution.lambda`. The same callback runs the suffix-driven
    // post-processing: the parametric sensitivity step
    // (`sens_sol_state_1`) and the reduced-Hessian computation.
    let nominal_capture: Rc<
        RefCell<
            Option<(
                Vec<pounce_common::types::Number>,
                Vec<pounce_common::types::Number>,
            )>,
        >,
    > = Rc::new(RefCell::new(None));
    let sens_capture: Rc<RefCell<Option<Vec<pounce_common::types::Number>>>> =
        Rc::new(RefCell::new(None));
    // Converged bound multipliers, lifted to full-x order and the user's
    // unscaled-Lagrangian convention (Ipopt `ipopt_zL_out`/`ipopt_zU_out`).
    // Both are `≥ 0` at an active bound; zero elsewhere. Written as `.sol`
    // suffix blocks so Pyomo's `model.ipopt_zL_out` / AMPL `.rc` are
    // populated for reduced-cost / sensitivity work (gh #296).
    let bound_mult_capture: Rc<
        RefCell<
            Option<(
                Vec<pounce_common::types::Number>,
                Vec<pounce_common::types::Number>,
            )>,
        >,
    > = Rc::new(RefCell::new(None));
    let red_hessian_capture: Rc<RefCell<Option<sens::RedHessianResult>>> =
        Rc::new(RefCell::new(None));
    if args.json_output.is_some() || sol_path.is_some() || sens_active || wants_red_hessian {
        let cap = Rc::clone(&nominal_capture);
        let sens_cap = Rc::clone(&sens_capture);
        let bmult_cap = Rc::clone(&bound_mult_capture);
        let rh_cap = Rc::clone(&red_hessian_capture);
        let suffixes_cb = nl_suffixes.clone();
        let dims_cb = nl_dims;
        let compute_rh = wants_red_hessian;
        let rh_eigen = args.rh_eigendecomp || sens_options.wants_eigendecomp();
        // `--sens-boundcheck` and `sens_boundcheck=yes` both switch the
        // refinement on. The margin: a `--sens-bound-eps` that was
        // actually typed (it carries its own value and implies the
        // flag) wins; otherwise `sens_bound_eps` from the options;
        // otherwise the registered default, which is the same 1e-3 the
        // flag defaults to — so reading the option changes nothing for
        // anyone who does not set it. `sens_bound_eps_explicit`, not a
        // comparison against the default: `--sens-bound-eps 1e-3` is a
        // real request and must still beat the options file.
        let boundcheck_eps = {
            let on = args.sens_boundcheck || sens_options.sens_boundcheck == Some(true);
            let eps = if args.sens_bound_eps_explicit {
                args.sens_bound_eps
            } else {
                sens_options
                    .sens_bound_eps
                    .unwrap_or(pounce_sensitivity::DEFAULT_SENS_BOUND_EPS)
            };
            on.then_some(eps)
        };
        // The refinement releases a bound whose multiplier the step
        // drives negative past the solve's own margin, not past
        // `sens_bound_eps`, which is a primal margin.
        let release_eps = pounce_sensitivity::release_floor_from_options(app.options());
        let sens_opts_cb = sens_options;
        app.set_on_converged(Box::new(move |data, cq, nlp, pd| {
            let curr = match data.borrow().curr.clone() {
                Some(c) => c,
                None => return,
            };
            // Lift to full length so a fixed / eliminated variable
            // still occupies its slot — AMPL's `.sol` reader matches
            // the x block against the originating `.nl`'s var count.
            let x_iterate = nlp.borrow().lift_x_to_full(&*curr.x);
            // The `.sol` / JSON `solution.x` is the point the user is
            // *told* is the solution, so it goes through
            // `finalize_solution_x` — which adds the
            // `honor_original_bounds` projection undoing the
            // `bound_relax_factor` widening. Without it a bound-pinned
            // solution is reported just outside its own declared bounds
            // even with the option on, because this hook reads the raw
            // iterate rather than the `finalize_solution` payload.
            // `x_iterate` stays unprojected for the sensitivity /
            // reduced-Hessian steps below: those expand around the point
            // the KKT factorization was built at, and must not be handed
            // a base shifted out from under it.
            let x = nlp.borrow().finalize_solution_x(&*curr.x);
            // Reassemble the user-facing `lambda` (length `n_full_g`, in
            // original `.nl` g-row order) via `finalize_solution_lambda`, which
            // inverts the c/d split through `c_map`/`d_map`, unwinds the
            // `c_scale`/`d_scale` scaling, AND divides out `obj_scale_factor`
            // so the dual is in the user's unscaled-Lagrangian convention.
            // (`pack_lambda_for_user` omits the obj_scale division — it feeds
            // the scaled `eval_h` — so using it here left the duals scaled
            // whenever gradient-based scaling triggered: pounce#11 F1.)
            // Concatenating the raw `y_c` then `y_d` blocks here instead would
            // permute the duals on any `.nl` with interleaved eq/ineq rows and
            // leave them scaled — AMPL / Pyomo read the dual block positionally.
            let mut lambda = nlp
                .borrow()
                .finalize_solution_lambda(&*curr.y_c, &*curr.y_d);
            if lambda.is_empty() {
                // Fallback for a non-`OrigIpoptNlp` whose `pack_lambda_for_user`
                // is the empty-vec default: emit the raw `y_c`-then-`y_d`
                // concatenation (no map/scale information available).
                let n_c = curr.y_c.dim() as usize;
                let n_d = curr.y_d.dim() as usize;
                lambda = Vec::with_capacity(n_c + n_d);
                if let Some(dv) = curr
                    .y_c
                    .as_any()
                    .downcast_ref::<pounce_linalg::dense_vector::DenseVector>()
                {
                    lambda.extend_from_slice(&dv.expanded_values());
                } else {
                    lambda.extend(std::iter::repeat(0.0).take(n_c));
                }
                if let Some(dv) = curr
                    .y_d
                    .as_any()
                    .downcast_ref::<pounce_linalg::dense_vector::DenseVector>()
                {
                    lambda.extend_from_slice(&dv.expanded_values());
                } else {
                    lambda.extend(std::iter::repeat(0.0).take(n_d));
                }
            }
            *cap.borrow_mut() = Some((x.clone(), lambda));

            // Lift the algorithm-side compressed bound multipliers to
            // full-x order in the user's convention. `finalize_solution_z_l`
            // /`_z_u` unwind the fixed-var/scaling maps and divide out
            // `obj_scale_factor`, yielding Ipopt-convention duals
            // (`z_l ≥ 0` at an active lower bound, `z_u ≥ 0` at an active
            // upper bound) — exactly Ipopt's `ipopt_zL_out`/`ipopt_zU_out`
            // (gh #296). A non-`OrigIpoptNlp` returns empty here and no
            // bound-multiplier suffixes are written.
            let z_l_full = nlp.borrow().finalize_solution_z_l(&*curr.z_l);
            let z_u_full = nlp.borrow().finalize_solution_z_u(&*curr.z_u);
            if !z_l_full.is_empty() || !z_u_full.is_empty() {
                *bmult_cap.borrow_mut() = Some((z_l_full, z_u_full));
            }

            // Suffix-driven post-processing on the converged KKT
            // system: the parametric sensitivity step and (on request)
            // the reduced Hessian.
            if let Some(suffixes) = &suffixes_cb {
                let (n_full, m_full) = dims_cb.unwrap_or((x.len(), 0));
                if sens_active {
                    if let Some(xp) = sens::compute_sens_perturbed_x(
                        data,
                        cq,
                        nlp,
                        Rc::clone(&pd),
                        suffixes,
                        n_full,
                        m_full,
                        &x_iterate,
                        boundcheck_eps,
                        release_eps,
                        &sens_opts_cb,
                    ) {
                        *sens_cap.borrow_mut() = Some(xp);
                    }
                }
                if compute_rh {
                    match sens::try_compute_red_hessian(
                        data,
                        cq,
                        nlp,
                        Rc::clone(&pd),
                        suffixes,
                        rh_eigen,
                        &sens_opts_cb,
                    ) {
                        Some(r) => *rh_cap.borrow_mut() = Some(r),
                        None => eprintln!(
                            "pounce: --compute-red-hessian requested but the `red_hessian` \
                             suffix is missing or empty in the input .nl"
                        ),
                    }
                }
            }
        }));
    }

    // Optionally wrap with presolve before counting so eval-call
    // counts reflect what the solver actually issues.
    let mut presolve_opts = match pounce_presolve::PresolveOptions::from_options_list(app.options())
    {
        Ok(o) => o,
        Err(e) => {
            eprintln!("pounce: presolve setup failed: {e}");
            return ExitCode::from(2);
        }
    };
    // Sensitivity / reduced-Hessian post-processing reads the converged
    // KKT system and indexes it with suffixes defined against the
    // original `.nl`. Presolve tightens bounds and drops rows, which
    // would shift that indexing — so disable it when either is active.
    if (sens_active || wants_red_hessian) && presolve_opts.enabled {
        eprintln!(
            "pounce: disabling presolve — sensitivity / reduced-Hessian post-processing \
             operates on the original (un-presolved) KKT system"
        );
        presolve_opts.enabled = false;
    }
    let presolve_handle = if presolve_opts.enabled {
        let p = Rc::new(RefCell::new(match &nl_expr_provider {
            Some(ep) => pounce_presolve::PresolveTnlp::with_expression_provider(
                Rc::clone(&inner_tnlp),
                Rc::clone(ep),
                presolve_opts,
            ),
            None => pounce_presolve::PresolveTnlp::new(Rc::clone(&inner_tnlp), presolve_opts),
        }));
        // Force the lazy init now so we can print a one-line summary.
        let _ = p.borrow_mut().get_nlp_info();
        {
            let h = p.borrow();
            let tr = h.tighten_report();
            let dropped = h.n_dropped_rows();
            let licq = h
                .licq_verdict()
                .map(|v| format!("{v:?}"))
                .unwrap_or_else(|| "off".into());
            if !json_dbg {
                println!(
                    "Presolve: tightened {} bounds ({} newly-finite), dropped {} redundant rows, LICQ={}",
                    tr.n_tightened, tr.n_new_finite, dropped, licq
                );
            }
            if let Some(fr) = h.fbbt_report() {
                if !json_dbg {
                    println!(
                        "Presolve FBBT: {} sweeps, {} variable tightenings (Σ|Δ|={:.3e})",
                        fr.iterations, fr.bound_updates, fr.total_tightening
                    );
                }
                if let Some(witness) = fr.infeasibility_witness {
                    eprintln!("pounce: FBBT detected infeasibility (witness constraint {witness})");
                }
            }
        }
        Some(p)
    } else {
        None
    };
    // Phase 6 (#487) stacks on top: it is the one pass that removes
    // *columns*, so it must be the outermost layer, and it is the layer the
    // `.sol` / JSON writers below read the full-space solution back out of.
    let elim_handle = match (&presolve_handle, presolve_opts.linear_eq_reduction) {
        (Some(p), true) => {
            let e = Rc::new(RefCell::new(pounce_presolve::LinearEqElimTnlp::new(
                Rc::clone(p) as Rc<RefCell<dyn TNLP>>,
                presolve_opts,
            )));
            // Force the lazy init so the summary below reports real numbers.
            let _ = e.borrow_mut().get_nlp_info();
            if !json_dbg {
                let h = e.borrow();
                let r = h.report();
                println!(
                    "Presolve linear-equality reduction: eliminated {} columns \
                     ({} pinned, {} aggregated), dropped {} rows ({} redundant)",
                    h.n_eliminated_vars(),
                    r.n_constant_vars,
                    r.n_aggregated_vars,
                    h.n_eliminated_rows(),
                    r.n_redundant_rows,
                );
            }
            Some(e)
        }
        _ => None,
    };
    let post_presolve: Rc<RefCell<dyn TNLP>> = match (&elim_handle, &presolve_handle) {
        (Some(e), _) => Rc::clone(e) as Rc<RefCell<dyn TNLP>>,
        (None, Some(p)) => Rc::clone(p) as Rc<RefCell<dyn TNLP>>,
        (None, None) => Rc::clone(&inner_tnlp),
    };

    // The CLI owns its explicit wrapper so `.nl` input can supply an
    // ExpressionProvider for FBBT and so it can report presolve diagnostics
    // before solving. This also keeps the sensitivity branch above un-presolved
    // when it disabled the local wrapper, without mutating the user's `presolve`
    // option.
    app.set_presolve_already_applied(true);

    // `POUNCE_DROP_HESSIAN=1` hides the model's second derivatives, so a
    // `.nl` — which always carries an exact Hessian through AMPL's AD —
    // can be benchmarked as the Hessian-less model the quasi-Newton and
    // finite-difference paths actually target. See `no_hessian_tnlp`.
    let post_presolve: Rc<RefCell<dyn TNLP>> =
        if pounce_cli::no_hessian_tnlp::NoHessianTnlp::requested() {
            Rc::new(RefCell::new(
                pounce_cli::no_hessian_tnlp::NoHessianTnlp::new(Rc::clone(&post_presolve)),
            ))
        } else {
            Rc::clone(&post_presolve)
        };

    // Wrap so we can pull eval-call counts out for the final summary.
    let counting = Rc::new(RefCell::new(CountingTnlp::new(Rc::clone(&post_presolve))));
    let tnlp: Rc<RefCell<dyn TNLP>> = Rc::clone(&counting) as Rc<RefCell<dyn TNLP>>;

    // Problem statistics are emitted by the engine now (application.rs),
    // gated on print_level, so every frontend gets them identically (#206).
    // The branded logo + copyright banner still print up-front, before the
    // problem is read — see near the top of `run`.

    // Build diagnostics state from `--dump …` flags. None of these
    // flags is required, but `--dump-dir` / `--dump-format` on their
    // own (no `--dump <cat>`) yields an empty config and we skip
    // installation entirely — there's nothing to write.
    let diagnostics_handle = match build_diagnostics(
        &args.dump_specs,
        args.dump_dir.as_ref(),
        args.dump_format.as_deref(),
    ) {
        Ok(d) => d,
        Err(msg) => {
            eprintln!("pounce: {msg}");
            return ExitCode::from(2);
        }
    };
    if let Some(diag) = diagnostics_handle.as_ref() {
        if !json_dbg {
            println!(
                "Diagnostics: dumping to {} ({} categor{} configured)",
                diag.dump_dir().display(),
                diag.config.categories.len(),
                if diag.config.categories.len() == 1 {
                    "y"
                } else {
                    "ies"
                },
            );
        }
        app.set_diagnostics(Rc::clone(diag));
    }

    // Snapshot NLP dimensions before the solve so we can use them in
    // both the console summary and the JSON report. Borrowing here is
    // safe because we hold no outstanding borrow on the counting
    // wrapper yet.
    let nlp_info_snapshot = tnlp.borrow_mut().get_nlp_info();

    // Solve, with a re-solve loop: the debugger's `resolve` command stops
    // the current solve and leaves a `RestartRequest` in `restart_cell`.
    // We then apply the staged option overrides, seed the next solve from
    // the captured `x` (via `SeededTnlp`), re-install a fresh debugger,
    // and run again. Without `resolve`, this runs exactly once.
    let mut solve_tnlp: Rc<RefCell<dyn TNLP>> = Rc::clone(&tnlp);
    // The run-ending `EXIT:` / `POUNCE <version>:` verdict belongs to the
    // whole run, not to each attempt. Deferred from here through the
    // second-opinion ladder below, which releases it and prints it once
    // with the status that actually ships. Without this, every retry
    // driver's attempt printed its own verdict and a run that recovered
    // reported a mid-run one that read as the final answer.
    //
    // Once, OUTSIDE the loop: a debugger `resolve` goes round it again, and
    // there is exactly one release below. Deferring per pass left the
    // counter at 1 after a resolve, so the run printed no verdict at all.
    app.defer_end_verdict();
    let mut status = loop {
        let st = app.optimize_tnlp(Rc::clone(&solve_tnlp));
        let req = restart_cell.borrow_mut().take();
        let Some(req) = req else { break st };
        for (k, v) in &req.options {
            if let Err(e) = app.options_mut().read_from_str(&format!("{k} {v}\n"), true) {
                eprintln!("pounce: re-solve could not set {k}={v}: {e}");
            }
        }
        // Full primal-dual warm restart (`resolve`): install the captured
        // 8-vector iterate and turn on the warm-start initializer so the
        // duals carry over and the barrier resumes at the captured μ
        // instead of cold-restarting at `mu_init`. The primal-only path
        // (sweep / multistart, `warm == None`) leaves these off and just
        // seeds `x` through `SeededTnlp` below.
        if let Some(snap) = req.warm {
            let mu = snap.mu();
            app.set_warm_start_iterate(snap);
            let _ = app
                .options_mut()
                .read_from_str("warm_start_init_point yes\n", true);
            if mu.is_finite() && mu > 0.0 {
                let _ = app
                    .options_mut()
                    .read_from_str(&format!("warm_start_target_mu {mu}\n"), true);
            }
        }
        solve_tnlp = Rc::new(RefCell::new(pounce_cli::seeded_tnlp::SeededTnlp::new(
            Rc::clone(&tnlp),
            req.seed_x,
        )));
        if let Some(hook) = debug_hook.as_ref() {
            // Re-arm the SAME debugger for the next solve (the hook is consumed
            // per `optimize_tnlp`). Reusing it — rather than building a fresh
            // one — preserves the stdin pump, the `hello` handshake, and any
            // breakpoints, and avoids leaking a second stdin-reader thread.
            app.set_debug_hook(hook.clone());
        }
        eprintln!(
            "pounce: re-solving from saved point with {} option override(s)…",
            req.options.len()
        );
    };

    // Snapshot the statistics from the solve whose verdict `status` currently
    // reflects. The MC64 scaling retry below runs a *second* solve into the
    // same `app`, which overwrites `app.statistics()`. On a non-promoting
    // retry we keep the original local-infeasibility verdict, so we must keep
    // the original stats too — otherwise the summary/JSON report would pair the
    // original verdict with the failed retry's iteration count / objective. We
    // adopt the retry's stats only when the retry is actually promoted (below).
    let mut solve_stats = app.statistics();

    // Second-opinion ladder: a failing verdict gets re-solved along up to
    // three deliberately different trajectories before it ships. Policy in
    // `pounce_algorithm::second_opinion`, driver in
    // `pounce_restoration::second_opinion_driver` — the CLI is one of four
    // surfaces that run it, and the rationale for every rung lives with the
    // policy rather than here.
    //
    // Two CLI-only exemptions gate it:
    //
    //  * A presolve-*certified* infeasibility. The ladder exists to
    //    second-guess a *numerical* local-infeasibility verdict that a bad
    //    scaling or an unlucky barrier trajectory may have manufactured;
    //    re-solving to double-check an exact proof would burn whole solves to
    //    re-derive something no knob can affect.
    //  * An attached debugger. Each rung is a fresh `optimize_tnlp`, and the
    //    debug hook is consumed per solve — an interactive session would find
    //    its breakpoints gone and the iterate replaced under it.
    let presolve_certified = presolve_handle
        .as_ref()
        .and_then(|p| p.borrow().certified_infeasible());
    let second_opinion = if debug_hook.is_none() && presolve_certified.is_none() {
        // Gated like every other banner the CLI prints: `print_level 0` is a
        // request for silence, and the ladder's narration is no more exempt
        // than the `EXIT:` block or the degeneracy diagnosis. The ladder still
        // *runs* -- silence is about the console, not about the answer. The
        // gate itself is shared with the C interface so the two cannot drift.
        let narrate = pounce_algorithm::second_opinion::narration_is_wanted(app.options());
        let outcome = run_second_opinion_ladder(
            &mut app,
            Rc::clone(&tnlp),
            status,
            solve_stats.clone(),
            &mut |line| {
                if narrate {
                    eprintln!("{line}");
                }
            },
        );
        status = outcome.status;
        solve_stats = outcome.statistics.clone();
        outcome
    } else {
        // The ladder is exempted here, so it cannot be the one to release the
        // deferred verdict — release it on this path too, or a debugger
        // session and a presolve-certified infeasibility each lose their
        // `EXIT:` line entirely.
        if app.release_end_verdict() {
            app.print_end_verdict(status);
        }
        SecondOpinionOutcome::unchanged(status, solve_stats.clone())
    };
    // gh #508's arbiter used to live here: every rung printed its own
    // `EXIT:` banner, so when nothing was promoted the terminal's last word
    // was the last REJECTED rung's, while the `.sol`, the summary and the JSON
    // report all carried the original verdict. `validation/p3_control.py`
    // keeps the last `EXIT:` line it sees and pairs it with the `.sol`, so it
    // recorded a status the `.sol` never held. Measured on
    // `min (x-5)² s.t. x²+δ = 0` at `tol=1e-4`: the console ended
    // `Error in step computation.` (δ=1e-9) and `Maximum Number of Iterations
    // Exceeded.` (δ=1e-1) over a `.sol` that said locally infeasible in both.
    //
    // There is nothing left to arbitrate. The verdict is deferred across the
    // whole run and printed exactly once, by whoever releases the last
    // deferral, with the status that ships — so the terminal's final word is
    // the true one by construction rather than by a correcting re-emission
    // after the fact. Re-emitting here now would print it twice.

    // Failure diagnosis, printed once, after the ladder has finished moving
    // `status` and before the machine-readable verdict below.
    //
    // Two statuses get a diagnosis because two statuses are routinely correct
    // and useless. `Invalid_Number_Detected` says a non-finite value reached
    // the algorithm and says nothing about which one: on the KRONOS corpus all
    // four such losses had the culprit sitting in the starting vector the model
    // itself supplied — `hong`'s x0 is literally `[NaN, NaN, NaN, NaN, 0, …]` —
    // and the user was told none of that. `Infeasible_Problem_Detected` is a
    // *local* statement about a nonconvex problem, and when the constraint
    // Jacobian is rank-deficient at the point the solve started from, LICQ
    // fails there and the verdict is a statement about the point at least as
    // much as about the problem: ten of the fifteen corpus losses carry that
    // verdict on models an independent solver proves feasible to 2.4e-7.
    //
    // The audit runs on `inner_tnlp` — the user's own TNLP, before presolve,
    // elimination, scaling or the counting wrapper — for the same reason
    // `run_derivative_test` does: a wrapper renumbers variables, so naming
    // `x[3]` of a presolved model points at a *neighbouring* variable's
    // answer. That is the gh#450 failure mode, and a diagnosis that names the
    // wrong variable is worse than none. Going around `counting` also keeps
    // the reported eval counts honest — this costs one call of each callback,
    // and they are the diagnosis's, not the solver's.
    //
    // It is spent only on a run that has already failed, and it changes
    // nothing — not the status, not the trajectory, not an option.
    if matches!(
        status,
        ApplicationReturnStatus::InvalidNumberDetected
            | ApplicationReturnStatus::InfeasibleProblemDetected
    ) && app
        .options()
        .get_integer_value("print_level", "")
        .map(|(v, _found)| v >= 1)
        .unwrap_or(true)
        && let Some(diagnosis) = pounce_nlp::degeneracy::diagnose_start_point(&inner_tnlp, 6)
    {
        if let Some(what) = diagnosis.audit.describe() {
            eprintln!("pounce: the model is not finite at its own starting point: {what}.");
        }
        // Not when presolve *proved* the infeasibility. The ladder is exempt
        // there for the reason given at its own guard — re-solving to
        // second-guess a proof is a waste — and the advice below is the same
        // mistake in words: on a certified-infeasible model with any
        // structurally-zero Jacobian row, this told the user to doubt a
        // verdict the `.sol` had just stamped `solve_result_num` 201,
        // "proved". Rank-deficiency is a statement about the starting point,
        // and a bound-propagation refutation is not.
        //
        // The non-finite audit above keeps running: "your model is NaN at its
        // own start" is true and worth saying whoever proved what.
        if presolve_certified.is_none()
            && status == ApplicationReturnStatus::InfeasibleProblemDetected
            && let Some(jac) = diagnosis.jacobian.as_ref()
            && let Some(what) = jac.describe(6)
        {
            eprintln!("pounce: the constraint Jacobian is rank-deficient there: {what}.");
            eprintln!(
                "pounce: LICQ fails at a point like that, so a local-infeasibility verdict \
                 reached from it is as much a statement about the starting point as about the \
                 problem. Try a different starting point, or `start_point_perturbation 1e-2`."
            );
        }
    }

    // The machine-readable verdict, printed exactly once per run, after every
    // path above has finished moving `status`.
    //
    // Free-form banners are not a usable status channel and the ladder is what
    // proved it. `Application::emit_end_summary` prints one `EXIT:` banner per
    // *solve*, so a laddered run prints one per rung — and a consumer that
    // scans the whole log for known phrases picks up whichever phrase it ranks
    // first, not whichever solve shipped. `benchmarks/scripts/run_nl_bench.sh`
    // ranks "Maximum Number of Iterations Exceeded" above "Converged to a point
    // of local infeasibility", so on `cresc100` — where the barrier rung hits
    // `max_iter` and the original infeasibility verdict then stands — it
    // recorded `Maximum_Iterations_Exceeded` for a run that shipped
    // `Infeasible_Problem_Detected`. Wrong status, no error, straight into
    // `BENCHMARK_REPORT.md`.
    //
    // That driver already prefers a `Status:` line and only falls back to
    // phrase-ranking because nothing ever emitted one. This is that line. It
    // carries the upstream enumerator spelling (`Infeasible_Problem_Detected`),
    // which is what CUTEst tables and the reference JSONs use, and being last
    // and unique it cannot be confused with a rung's banner.
    //
    // Gated like the banners it disambiguates: `print_level >= 1` (at 0 the
    // console is silent by request), and never under `--json-debug`, whose
    // stdout is a pure protocol channel.
    if !json_dbg
        && app
            .options()
            .get_integer_value("print_level", "")
            .map(|(v, _found)| v >= 1)
            .unwrap_or(true)
    {
        println!("Status: {}", status.upstream_name());
    }

    // `solve_stats` was snapshotted right after the solve loop and updated
    // above iff the MC64 retry was promoted, so it always matches `status`.
    let counters = counting.borrow();
    if json_dbg {
        // Pure protocol channel: emit a `terminated` lifecycle event in
        // place of the human summary, so a visual debugger gets a clean
        // end-of-session signal with the final status and stats.
        let ev = serde_json::json!({
            "event": "terminated",
            "status": format!("{status:?}"),
            "status_message": print::status_message(status),
            "iterations": solve_stats.iteration_count,
            "objective": solve_stats.final_objective,
            "evals": {
                "obj": counters.n_obj.get(),
                "obj_grad": counters.n_grad_f.get(),
                "constr": counters.n_g.get(),
                "constr_jac": counters.n_jac_g.get(),
                "hess": counters.n_h.get(),
            },
        });
        println!("{ev}");
    }
    // The console end-of-run summary is emitted by the engine now
    // (application.rs), gated on print_level; the CLI only prints the JSON
    // event variant above (#206).
    drop(counters); // release before JSON block (which re-borrows the wrapped TNLP).

    // Active-set SQP fallback: that solve path bypasses the IPM-only
    // `on_converged` hook the `.sol` / JSON writers read, so
    // `nominal_capture` is still empty even on a clean solve. Backfill it
    // from the solution `CountingTnlp` captured at `finalize_solution`
    // (original-problem space, the same `x` / `lambda` the IPM hook would
    // have recorded). Only fills when empty, so the IPM path is untouched.
    if nominal_capture.borrow().is_none() {
        if let Some(xl) = counting.borrow().captured_solution() {
            *nominal_capture.borrow_mut() = Some(xl);
        }
    }

    // ...and OVERWRITE it, not merely backfill it, when a losing retry's
    // answer was thrown away and an earlier attempt's replayed.
    //
    // `on_converged` fires once per *attempt*. A retry that converged and
    // was then refused on the answer (gh#884's promotion gate, or the μ
    // fallback's, pounce#870) has already run it, so `nominal_capture`
    // holds the **discarded** point while `status`, `objective` and every
    // statistic beside them were floored back to the attempt that won.
    // The `.sol` `x`, the JSON's `solution.x` and the dual block all come
    // from this cell, so without the overwrite one run reports two
    // different answers: measured on a declined retry, the `.sol` held
    // `f = -6.3274` and the JSON report beside it said `-6.1768`, with
    // `pounce verify` on the `.sol` confirming the file carried the loser.
    //
    // `captured_solution()` is refreshed by `FinalizeSnapshot::replay`,
    // which restores the winning attempt by *calling* `finalize_solution`
    // — so the last capture is always the answer being reported, on this
    // path and on the ordinary one. Gated on the flag rather than taken
    // unconditionally because the two agree everywhere else, and
    // `on_converged`'s capture is the one that has had the gh#486
    // variable-scaling substitution undone against the algorithm's own
    // iterate; this swap is for the case where that capture describes a
    // point nobody is reporting.
    //
    // **Frame**: `CountingTnlp` sits INSIDE the gh#486 scaling wrapper
    // (`main.rs` hands `counting` to `optimize_tnlp`, which wraps what it is
    // handed) and OUTSIDE the presolve one (`counting.inner` is
    // `post_presolve`, and it captures before forwarding). So this payload
    // has ALREADY had `x /= d`, `z *= d` applied by
    // `scaling_tnlp::finalize_solution`, and has NOT been lifted out of the
    // reduced presolve space. The lift below must therefore still run on it;
    // the gh#486 correction must not, or it lands twice. Measured before
    // this flag existed, on `mpcc_scholtes4_biactive` under
    // `nlp_scaling_method=curvature-based`: a declined retry reported
    // `x = [7.28e-14, 7.28e-14, -3.63e-09]` against the correct
    // `[1.46e-13, 1.46e-13, -1.82e-09]` — every component off by exactly the
    // factor, with the objective beside it unchanged and right. Silent,
    // plausible, wrong: the shape this whole block exists to remove, one
    // wrapper over.
    let capture_is_already_in_model_units = app.answer_restored_from_floor();
    if capture_is_already_in_model_units {
        if let Some(xl) = counting.borrow().captured_solution() {
            *nominal_capture.borrow_mut() = Some(xl);
        }
        // The bound multipliers are the same story one field over: they
        // also come from `on_converged`, they are also the loser's, and
        // they are what `ipopt_zL_out` / `ipopt_zU_out` ship to Pyomo and
        // AMPL for reduced-cost work (gh #296). Both sources apply the
        // same `finalize_solution_z_l` / `_z_u` lift, so this is the same
        // number rather than a compatible one. Empty blocks are left
        // alone: a non-`OrigIpoptNlp` model writes no such suffixes, and
        // overwriting a populated capture with an empty pair would drop
        // them rather than correct them.
        if let Some((z_l, z_u)) = counting.borrow().captured_bound_mults() {
            if !z_l.is_empty() || !z_u.is_empty() {
                *bound_mult_capture.borrow_mut() = Some((z_l, z_u));
            }
        }
    }

    // Presolve row-dropping: both lambda sources above (`on_converged`
    // and the `CountingTnlp` fallback) sit *outside* presolve, so their
    // `lambda` is in the reduced kept-row space — length `m_out`, not the
    // original `.nl`'s `m`. AMPL / Pyomo read the `.sol` dual block
    // positionally against the originating `.nl`, so a short block
    // mis-aligns or is rejected. `PresolveTnlp::finalize_solution` already
    // lifted the duals back to the original row order *and* recovered
    // multipliers for the dropped rows; swap that full-length vector in.
    // Phase 6 (#487) removes columns too, so with it active every capture
    // taken outside the wrappers — `on_converged`, the `CountingTnlp`
    // fallback, the bound-multiplier suffixes — is in the reduced variable
    // space as well, and short in both directions.
    let elim_reduced = elim_handle
        .as_ref()
        .map(|e| {
            let h = e.borrow();
            h.n_eliminated_vars() > 0 || h.n_eliminated_rows() > 0
        })
        .unwrap_or(false);
    if let Some(p) = &presolve_handle {
        let lifted = if p.borrow().n_dropped_rows() > 0 || elim_reduced {
            p.borrow().finalized_full_solution()
        } else {
            None
        };
        if let Some((x_full, lam_full)) = lifted {
            if let Some((x, lambda)) = nominal_capture.borrow_mut().as_mut() {
                *lambda = lam_full;
                if elim_reduced {
                    *x = x_full;
                }
            }
        }
    }
    // Variable scaling (gh#486) is the same shape of problem as the
    // reductions above, one level further out: the `on_converged` hook
    // reads the algorithm's own iterate, and under a change of
    // variables that iterate is in scaled coordinates. `.sol` and the
    // JSON report must carry the model's own units, so undo the
    // substitution here. `finalize_solution` already did it for every
    // consumer that reads THAT payload; this fixes the ones that do not.
    //
    // The lengths are asserted rather than zipped: a `zip` against a
    // shorter factor vector would leave the tail in scaled coordinates
    // and report it as though it were in the model's units, which no
    // reader could detect. Both captures come from the same iterate the
    // factors were built against, so a mismatch is a wiring bug.
    // Skipped when the captures came from the `finalize_solution` payload
    // (see `capture_is_already_in_model_units` above): that payload is the
    // output of this very substitution, so correcting it again squares the
    // factor.
    if let Some(d) = app
        .variable_scaling()
        .filter(|_| !capture_is_already_in_model_units)
    {
        if let Some((x, _lambda)) = nominal_capture.borrow_mut().as_mut() {
            assert_eq!(
                x.len(),
                d.len(),
                "scaling: captured {} variables but {} factors",
                x.len(),
                d.len()
            );
            for (xi, s) in x.iter_mut().zip(d.iter()) {
                *xi /= s;
            }
        }
        if let Some((z_l, z_u)) = bound_mult_capture.borrow_mut().as_mut() {
            assert_eq!(
                z_l.len(),
                d.len(),
                "scaling: captured {} bound multipliers but {} factors",
                z_l.len(),
                d.len()
            );
            assert_eq!(z_l.len(), z_u.len(), "z_L and z_U must be the same length");
            for ((l, u), s) in z_l.iter_mut().zip(z_u.iter_mut()).zip(d.iter()) {
                *l *= s;
                *u *= s;
            }
        }
    }

    // Bound multipliers are per *variable*, so only the column reduction can
    // shorten them. Swap in the wrapper's full-space pair when — and only
    // when — the captured one is the wrong length; leaving a correctly-sized
    // capture alone keeps the scaling path that produced it untouched.
    if elim_reduced {
        if let Some(full) = elim_handle
            .as_ref()
            .and_then(|e| e.borrow().finalized_full_solution().cloned())
        {
            if let Some((z_l, z_u)) = bound_mult_capture.borrow_mut().as_mut() {
                if z_l.len() != full.z_l.len() {
                    *z_l = full.z_l;
                    *z_u = full.z_u;
                }
            }
        }
    }

    // Reduced Hessian: print to stderr (informational), mirroring
    // upstream sIPOPT's RedHessian / Eigenvalues prints in
    // `SensReducedHessianCalculator.cpp`.
    if let Some(rh) = red_hessian_capture.borrow().as_ref() {
        sens::print_red_hessian_to_stderr(rh);
    } else if wants_red_hessian {
        eprintln!(
            "pounce: --compute-red-hessian requested but the reduced Hessian \
             was not produced (see warnings above)."
        );
    }

    // Assemble the AMPL `.sol` suffix blocks. The parametric
    // sensitivity step contributes `sens_sol_state_1` (the perturbed
    // primal) when the `.nl` declared the sIPOPT suffixes.
    let mut sol_suffixes: Vec<nl_writer::SolSuffix> = Vec::new();
    if let Some(xp) = sens_capture.borrow().clone() {
        sol_suffixes.push(nl_writer::SolSuffix {
            name: "sens_sol_state_1".to_string(),
            target: nl_writer::SolSuffixTarget::Var,
            values: nl_writer::SolSuffixValues::Real(xp),
        });
    }
    // Bound-multiplier suffixes (`ipopt_zL_out` / `ipopt_zU_out`): the
    // reduced costs / bound sensitivities. Pyomo maps these `.sol` suffix
    // blocks straight onto `model.ipopt_zL_out` / `model.ipopt_zU_out` and
    // AMPL onto variable `.rc` (gh #296).
    //
    // Sign convention — verified numerically against Ipopt 3.14 on
    // bound-active models (gh #296): Ipopt's AMPL `.sol` writes
    //   `ipopt_zL_out = +z_l`  (≥ 0 at an active lower bound), and
    //   `ipopt_zU_out = −z_u`  (≤ 0 at an active upper bound),
    // i.e. both equal the objective-gradient component at the bound
    // (`∂f/∂x_i`). `finalize_solution_z_l`/`_z_u` return the internal
    // multipliers with `z_l, z_u ≥ 0` (Ipopt's internal convention), so
    // the lower block is emitted as-is and the upper block is negated to
    // match Ipopt's output. (`min (x−3)² s.t. x≤1`: x*=1, ∂f/∂x=−4, so
    // Ipopt writes `ipopt_zU_out = −4`; pounce now matches.)
    if let Some((z_l_full, z_u_full)) = bound_mult_capture.borrow().clone() {
        let z_u_neg: Vec<pounce_common::types::Number> = z_u_full.iter().map(|&z| -z).collect();
        sol_suffixes.push(nl_writer::SolSuffix {
            name: "ipopt_zL_out".to_string(),
            target: nl_writer::SolSuffixTarget::Var,
            values: nl_writer::SolSuffixValues::Real(z_l_full),
        });
        sol_suffixes.push(nl_writer::SolSuffix {
            name: "ipopt_zU_out".to_string(),
            target: nl_writer::SolSuffixTarget::Var,
            values: nl_writer::SolSuffixValues::Real(z_u_neg),
        });
    }

    // Emit the JSON solve report, when requested. Written AFTER the
    // console summary so a piped `pounce ... --json-output -` reader
    // could be wired up later without disturbing stdout (today we
    // write to a path; stdout-mode is a follow-up).
    if let Some(json_path) = &args.json_output {
        let input = match &args.problem {
            ProblemSource::Builtin(name) => InputDescriptor::Builtin { name: name.clone() },
            ProblemSource::NlFile(p) => InputDescriptor::NlFile {
                path: p.clone(),
                size_bytes: std::fs::metadata(p).ok().map(|m| m.len()),
            },
        };
        let mut builder = ReportBuilder::new(args.json_detail, input);
        if let Some(info) = nlp_info_snapshot {
            builder.problem.n_variables = info.n;
            // `info.m` is the reduced kept-row count under presolve, but
            // the lifted `lambda` (and the `.sol`) carry the original
            // `.nl` constraint count — and `SolutionInfo::lambda` is
            // documented to have length `problem.n_constraints`. Report
            // the original `m` so that invariant holds.
            let n_dropped = presolve_handle
                .as_ref()
                .map(|p| p.borrow().n_dropped_rows())
                .unwrap_or(0);
            builder.problem.n_constraints = info.m + n_dropped;
            builder.problem.n_objectives = 1; // pounce IPM uses obj 0; multi-obj is read but ignored
            builder.problem.nnz_jac_g = Some(info.nnz_jac_g);
            builder.problem.nnz_h_lag = Some(info.nnz_h_lag);
        }
        // The arm that produced this verdict, not the one routing
        // picked: a convex solve that declines its own result lands
        // here (gh #535) after the `Selected solver:` banner has
        // already said `pounce-convex`.
        //
        // "the arm" is two arms, and this used to be a constant. Everything
        // that reaches this block went through `IpoptApplication::optimize_*`,
        // which dispatches on `is_sqp_algorithm_selected` — so a general NLP
        // under `algorithm=active-set-sqp` was reported as `nlp` by exactly
        // the field whose doc comment says it exists so that a reroute leaves
        // a trace. `scripts/sweep-fixtures.sh` reads this field for its engine
        // column, so the blind spot CLAUDE.md describes there covered the SQP
        // arm too: a change that moved a model between the interior-point and
        // active-set arms could not show up in a sweep diff.
        //
        // Read after the solve, so it is also right for the late convex
        // declines above: those call back into `optimize_tnlp` and get
        // whichever arm the option selects, long after the banner printed.
        builder.solution.engine = if app.is_sqp_algorithm_selected() {
            "sqp-active-set"
        } else {
            "nlp"
        }
        .to_string();
        builder.solution.status = status;
        // Same source of truth as the `.sol` writer below — a run must not
        // report 201 in one output and 200 in the other.
        builder.solution.solve_result_num = presolve_verdict(presolve_certified, status).1;
        builder.solution.objective = solve_stats.final_objective;
        if let Some((x, lambda)) = nominal_capture.borrow().clone() {
            builder.solution.x = x;
            builder.solution.lambda = lambda;
        }
        builder.ingest_stats(&solve_stats);
        if let Some(linsol) = app.linear_solver_summary() {
            builder.set_linear_solver_summary(linsol);
        }
        // gh #850: what the ladder did, and in particular what the *base*
        // solve did before it. `ingest_stats` above has just written the
        // promoted rung's iteration count as though it were the solve's, and
        // without this nothing in the report says the base solver failed --
        // which turns a lost solve into a recorded speed-up.
        if second_opinion.ran() {
            builder.set_second_opinion(pounce_solve_report::SecondOpinionInfo {
                tried: second_opinion.tried.iter().map(|s| s.to_string()).collect(),
                promoted_by: second_opinion.promoted_by.map(|s| s.to_string()),
                base_status: second_opinion.base_status.upstream_name().to_string(),
                base_iteration_count: second_opinion.base_iteration_count,
                rung_iteration_counts: second_opinion.rung_iteration_counts.clone(),
                total_iteration_count: second_opinion.total_iteration_count(),
            });
        }

        // `Full` detail carries the suffix blocks: the sensitivity
        // result and, when computed, the reduced Hessian (packed as
        // problem-level suffixes — see `pounce-cli`'s sens module).
        if matches!(args.json_detail, ReportDetail::Full) {
            for s in &sol_suffixes {
                builder
                    .solution
                    .suffixes
                    .push(sens::sol_suffix_to_report(s));
            }
            if let Some(rh) = red_hessian_capture.borrow().as_ref() {
                builder.solution.suffixes.push(SolutionSuffix {
                    name: "_red_hessian".to_string(),
                    target: "problem".to_string(),
                    kind: "real".to_string(),
                    values: rh.hr.clone(),
                    int_values: Vec::new(),
                });
                builder.solution.suffixes.push(SolutionSuffix {
                    name: "_red_hessian_vars".to_string(),
                    target: "problem".to_string(),
                    kind: "int".to_string(),
                    values: Vec::new(),
                    int_values: rh.var_indices.iter().map(|&v| v as i32).collect(),
                });
                if let Some(w) = &rh.eigenvalues {
                    builder.solution.suffixes.push(SolutionSuffix {
                        name: "_red_hessian_eigenvalues".to_string(),
                        target: "problem".to_string(),
                        kind: "real".to_string(),
                        values: w.clone(),
                        int_values: Vec::new(),
                    });
                }
                if let Some(v) = &rh.eigenvectors {
                    builder.solution.suffixes.push(SolutionSuffix {
                        name: "_red_hessian_eigenvectors".to_string(),
                        target: "problem".to_string(),
                        kind: "real".to_string(),
                        values: v.clone(),
                        int_values: Vec::new(),
                    });
                }
            }
        }

        let report = builder.finish();
        if let Err(e) = write_report_file(json_path, &report) {
            eprintln!(
                "pounce: failed to write JSON report to {}: {e}",
                json_path.display()
            );
        } else {
            eprintln!("pounce: wrote {}", json_path.display());
        }
    }

    // Emit the AMPL `.sol` file. Written unconditionally once a target
    // path is resolved — even on a failed solve — so AMPL's reader
    // always sees a `solve_result_num`, matching `pounce_sens` and
    // upstream AMPL solver behaviour. When the solve never converged
    // the capture is empty; fall back to zero blocks sized from the
    // pre-solve NLP dimensions so the file still round-trips.
    if let Some(sol_path) = &sol_path {
        let (n, m_out) = nlp_info_snapshot
            .as_ref()
            .map(|i| (i.n as usize, i.m as usize))
            .unwrap_or((0, 0));
        // `nlp_info_snapshot.m` is the reduced kept-row count when
        // presolve dropped rows; the zero-fallback block must be sized to
        // the original `.nl`'s `m` so a failed-solve `.sol` still aligns.
        let m = m_out
            + presolve_handle
                .as_ref()
                .map(|p| p.borrow().n_dropped_rows() as usize)
                .unwrap_or(0);
        let (x, lambda) = nominal_capture
            .borrow()
            .clone()
            .unwrap_or_else(|| (vec![0.0; n], vec![0.0; m]));
        // A presolve-certified infeasibility is reported as `201` rather than
        // the generic `200`. Both sit in AMPL's 200..299 "infeasible" band, so
        // every consumer that reads the band — Pyomo maps the whole range to
        // `TerminationCondition.infeasible` in both its readers — is unaffected,
        // while a caller reading `solve_result_num` directly can tell a *proof*
        // (bound propagation / interval arithmetic established the feasible
        // region is empty) from the numerical verdict `200` (converged to a
        // stationary point of the constraint violation, which on a nonconvex
        // problem does not preclude a feasible point elsewhere). Sub-coding
        // inside a band is the AMPL-native idiom — it is what Ipopt itself does
        // with 500/501/502 in the failure band.
        let (message, srn) = presolve_verdict(presolve_certified, status);
        let payload = nl_writer::SolutionFile {
            message: &message,
            x: &x,
            mult_g: &lambda,
            solve_result_num: srn,
            suffixes: &sol_suffixes,
        };
        match nl_writer::write_sol_file_with_options(sol_path, &payload, &nl_ampl_options) {
            Ok(_) => eprintln!("pounce: wrote {}", sol_path.display()),
            Err(e) => eprintln!("pounce: failed to write {}: {e}", sol_path.display()),
        }
    }

    // After the solve, drop a manifest + timing summary at the dump
    // root so consumers (and humans) can tell which run produced
    // which artifacts without reading the iter_NNN/ tree.
    if let Some(diag) = diagnostics_handle.as_ref() {
        write_diagnostics_manifest(diag, &problem_desc, status);
        write_diagnostics_timing(diag, &app);
    }

    nlp_exit_code(status, args.ampl)
}

/// Process exit code for the general NLP solve path.
///
/// A *successful* solve — `SolveSucceeded` **or** `SolvedToAcceptableLevel`
/// (the reduced-accuracy convergence Ipopt also treats as a success; see
/// `minimize()` parity, #119) — exits 0. Everything else exits 1, **except**
/// in AMPL solver mode.
///
/// In `-AMPL` mode the process exit code is not the status channel: AMPL and
/// Pyomo's ASL interface read the termination from the `.sol` file's
/// `solve_result_num`, and conventionally an AMPL solver exits 0 whenever it
/// ran and produced a `.sol` — limit reached, infeasible, even a failed solve.
/// A non-zero exit makes Pyomo raise `ApplicationError` and never parse the
/// `.sol`. Genuine startup failures (bad `.nl`, bad option) already returned
/// non-zero earlier, before the solve, so reaching here in `-AMPL` mode means a
/// `.sol` was written and carries the verdict. Mirrors [`convex_exit_code`].
fn nlp_exit_code(status: ApplicationReturnStatus, ampl: bool) -> ExitCode {
    if nlp_solve_succeeded(status) || ampl {
        ExitCode::SUCCESS
    } else {
        ExitCode::from(1)
    }
}

/// Whether an NLP solve outcome counts as a "success" for the (non-AMPL) exit
/// code: `SolveSucceeded`, the reduced-accuracy `SolvedToAcceptableLevel`
/// (#119), or `FeasiblePointFound`.
///
/// The third member is not a widening of what counts as solved — it is the
/// same solve this process just wrote a solved-band `.sol` for.
/// `FeasiblePointFound` is emitted only for square problems
/// (`pounce_restoration`'s `square_feasible_point_found`, gated on
/// `is_square_problem`), where the objective is constant and a feasible
/// point is the solution, and `status_to_solve_result_num` writes Ipopt's
/// own AMPL code `2` for it. Leaving this set at two members would have
/// this binary exit 1 while the `.sol` beside it reads solved — a
/// disagreement between two channels of the same process, which is the
/// shape of the defect gh #815 was.
///
/// Three Python surfaces still exclude the status from their success sets:
/// `_minimize._NLP_SUCCESS_STATUS` (shared by `_curve_fit`),
/// `jax._path._OK_STATUS` and `torch._path._OK_STATUS`. They are a separate
/// contract — a scipy-style `success` flag on a library call that never
/// produces a `.sol` — and are tracked on their own rather than changed
/// here.
fn nlp_solve_succeeded(status: ApplicationReturnStatus) -> bool {
    matches!(
        status,
        ApplicationReturnStatus::SolveSucceeded
            | ApplicationReturnStatus::SolvedToAcceptableLevel
            | ApplicationReturnStatus::FeasiblePointFound
    )
}

/// Build a `SolverDebugger` for the requested mode/flags, wired to the
/// shared restart cell. Used for the first install and each re-solve.
fn build_debugger(
    mode: pounce_cli::cli::DebugMode,
    on_error: bool,
    on_interrupt: bool,
    script: Option<&std::path::Path>,
    reg: Option<Rc<pounce_common::reg_options::RegisteredOptions>>,
    cell: pounce_cli::debug_repl::RestartCell,
) -> pounce_cli::debug_repl::SolverDebugger {
    use pounce_cli::debug_repl::SolverDebugger;
    let dbg = if on_error {
        SolverDebugger::on_error(mode, reg)
    } else if on_interrupt {
        SolverDebugger::on_interrupt(mode, reg)
    } else {
        SolverDebugger::new(mode, reg)
    }
    .with_restart(cell);
    match script {
        Some(p) => dbg.with_script(p.to_string_lossy().into_owned()),
        None => dbg,
    }
}

/// Should an LP whose convex solve came back without a certificate be handed
/// to the general NLP interior-point path instead (gh #535)?
///
/// The NETLIB `gen`/`gen1` models are the case this exists for: `auto` routes
/// them to the convex IPM, which exhausts its 200-iteration budget in 191 s and
/// exits `OptimalInaccurate` with a primal residual of 1.4e-7 against
/// `tol = 1e-8`, while the general NLP filter-IPM — the same binary, the
/// default for every other class — solves the same model in 19 iterations and
/// 1.0 s to a strict certificate. The models are highly degenerate and
/// rank-deficient, strict complementarity fails, and a pure IPM cannot certify
/// the vertex (gh #133); crossover was built to close that gap and does not.
/// So the routing is the cheap lever: an LP is also a valid NLP, and the NLP
/// path is already in the binary.
///
/// The three gates, all necessary:
///
/// * **`allow_nlp_fallback`** — set by the caller only under `auto` (the class
///   was our inference, not the user's instruction), with no interactive
///   debugger attached, and only when the user did **not** set `max_iter`. A
///   user-set budget is a budget: `IterationLimit` is then the answer to the
///   question that was asked, and `max_iter=0` in particular must stop without
///   a solve (pounce#186), not launch a second one. An explicitly tightened
///   `tol` is deliberately *not* a suppressor — that is an accuracy request,
///   and trying the engine that can meet it is exactly the right response.
/// * **`ProblemClass::Lp`** — `P = 0`, per the issue. A convex QP that stalls
///   is a different (and unmeasured) population; leave it to the engine that
///   was chosen for it.
/// * **the status** — the three that mean "no certificate": a reduced-accuracy
///   exit, an exhausted budget, and a numerical failure. `Optimal` needs no
///   help, and `PrimalInfeasible` / `DualInfeasible` are verdicts the convex
///   solver *verified*, which a second solve must not be allowed to overwrite.
///   `NumericalFailure` was excluded until gh #724 on the grounds that it is
///   the post-solve verification refusing a point and no LP in the corpus
///   reached it. Both halves of that are the wrong test. It is the *strongest*
///   of the three "did not certify" signals — the point on offer missed even
///   the acceptable band — and it is the one status `run_convex_socp` reroutes
///   on for the conic path, so omitting it here made the LP and SOCP paths
///   disagree about what an unverified convex result means. An LP that reached
///   it was reported `InternalError` on a model the NLP path in the same
///   binary solves (gh #724 reproduces this on `lp_afiro` with `qp_tau=0.99`).
///   `TimeLimit` still does not reroute: it is a spent budget rather than a
///   stall, and rerouting it would answer "stop after `max_wall_time`" with a
///   second solve.
///
/// Note what this deliberately is **not**: the issue's "never-regress" variant,
/// which would keep whichever of the two results certifies at the lower KKT
/// error. That needs both verdicts in hand at reporting time, and the CLI's
/// standing rule — the one `run_convex_socp` follows and gh #508 re-litigated
/// for the NLP retry ladder — is that one solve prints one verdict. So the
/// decision is taken *before* any status line, `.sol` or JSON report is
/// emitted, and the NLP solve owns the whole report. The gates above are what
/// bound the downside: this only ever runs on an LP that already failed to
/// certify under a default budget.
fn lp_declines_to_nlp(
    class: pounce_cli::dispatch::ProblemClass,
    status: pounce_convex::QpStatus,
    allow_nlp_fallback: bool,
) -> bool {
    use pounce_convex::QpStatus;
    allow_nlp_fallback
        // gh #535 gated this on `Lp`. A convex QP that fails to certify is
        // the same situation and has the same answer -- it is also a valid
        // NLP, and the general path routinely certifies the badly-scaled and
        // degenerate models the interior path stalls on. `scaled_feasible_a`
        // is the case: 20 orders of Jacobian spread, and the convex arm needs
        // 3596 iterations where the NLP arm takes 22. The convex arm already
        // says so itself -- it emits the gh #293 scaling warning on that model
        // before returning IterationLimit -- so declining is a verdict it has
        // already reasoned its way to.
        && matches!(
            class,
            pounce_cli::dispatch::ProblemClass::Lp
                | pounce_cli::dispatch::ProblemClass::ConvexQp
        )
        && matches!(
            status,
            QpStatus::OptimalInaccurate | QpStatus::IterationLimit | QpStatus::NumericalFailure
        )
}

/// Did the user set `max_iter` explicitly? A user-set iteration budget
/// suppresses the gh #535 LP→NLP fallback — see [`lp_declines_to_nlp`].
fn max_iter_explicitly_set(app: &IpoptApplication) -> bool {
    matches!(
        app.options().get_integer_value("max_iter", ""),
        Ok((_, true))
    )
}

/// Solve a classified LP / convex-QP `.nl` problem through the
/// specialized `pounce-convex` interior-point method, write a `.sol`,
/// and return the process exit code. This is the LP/QP dispatch target
/// (see `dev-notes/lp-qp-routing.md`).
///
/// Writes the primal solution `x` and the constraint duals recovered
/// from the QP multipliers (`pounce_cli::qp_extract::recover_duals`).
/// The objective is reported in the user's original sense, including the
/// `.nl`'s constant term, which the standard-form QP drops.
/// Map the convex solver's status onto the NLP-side `ApplicationReturnStatus`
/// used by the JSON solve report, so QP and NLP reports share one status
/// vocabulary.
fn qp_status_to_ars(s: pounce_convex::QpStatus) -> ApplicationReturnStatus {
    use pounce_convex::QpStatus;
    match s {
        QpStatus::Optimal => ApplicationReturnStatus::SolveSucceeded,
        // Reduced-accuracy solve (residual above `tol` but usable) — Ipopt's
        // "Solved To Acceptable Level" is the matching NLP-side status.
        QpStatus::OptimalInaccurate => ApplicationReturnStatus::SolvedToAcceptableLevel,
        QpStatus::PrimalInfeasible => ApplicationReturnStatus::InfeasibleProblemDetected,
        QpStatus::DualInfeasible => ApplicationReturnStatus::DivergingIterates, // unbounded
        QpStatus::IterationLimit => ApplicationReturnStatus::MaximumIterationsExceeded,
        QpStatus::TimeLimit => ApplicationReturnStatus::MaximumWallTimeExceeded,
        QpStatus::NumericalFailure => ApplicationReturnStatus::InternalError,
    }
}

/// Map a convex-solver status onto the AMPL `.sol` terminal line: the message,
/// whether the solve is treated as a success (drives the exit code), and the
/// `solve_result_num`. AMPL convention: 0 solved, 100–199 solved with a
/// warning, 200–299 infeasible, 300–399 unbounded, 400–499 limit, 500–599
/// failure. Shared by the QP/LP and SOCP report paths so the two cannot drift.
///
/// `OptimalInaccurate` reports `1` — Ipopt's code for the same
/// reduced-accuracy convergence, and the same code the NLP path's
/// `SolvedToAcceptableLevel` reports (`status_to_solve_result_num`), which
/// this status maps onto in `qp_status_to_ars`. One status, one code: a model
/// must not change its `.sol` verdict band depending on which engine took it.
fn convex_status_report(s: pounce_convex::QpStatus) -> (&'static str, bool, i32) {
    use pounce_convex::QpStatus;
    match s {
        QpStatus::Optimal => ("Optimal Solution Found.", true, 0),
        QpStatus::OptimalInaccurate => ("Solved to acceptable level (reduced accuracy).", true, 1),
        QpStatus::PrimalInfeasible => ("Problem is primal infeasible.", false, 200),
        QpStatus::DualInfeasible => ("Problem is unbounded (dual infeasible).", false, 300),
        QpStatus::IterationLimit => ("Maximum iterations exceeded.", false, 400),
        QpStatus::TimeLimit => ("Maximum wallclock time exceeded.", false, 400),
        // Deliberately not "failure in KKT factorization": both convex engines
        // reach this status by failing the *post-solve* verification — the
        // returned point's true KKT error exceeded the acceptable band — which
        // a factorization breakdown is only one cause of. On the active-set
        // engine it is also where an uncertified infeasibility claim lands.
        QpStatus::NumericalFailure => ("Numerical failure (no verified KKT point).", false, 500),
    }
}

/// The `bound_relax_factor` widening the convex path applies — **none by
/// default**. Setting the option explicitly still buys Ipopt's behaviour.
///
/// gh #744/#745 made this arm widen bounds like the NLP arm, so one binary
/// would not solve two models depending on `solver_selection`. The goal was
/// right and the direction was backwards: it converged the arms on the NLP
/// arm's *internal perturbation* rather than on the model the user declared.
///
/// A widening of `δ` moves the optimum by `δ` times the bound's multiplier,
/// and nothing bounds that product. On `LISWET1` — every one of 10 000
/// monotonicity rows active, multipliers summing to `1.6e9` — a `1e-8`
/// widening buys `9.0` of objective:
///
/// | | objective |
/// |---|---|
/// | widened (gh #744 default) | `27.1220506` |
/// | as declared (this default) | **`36.1224021`** |
/// | HiGHS, independently | **`36.1224020850`** |
/// | Maros–Mészáros DOC 97/6 ground truth | **`36.1224`** |
///
/// The error is also **one-signed** — widening only ever enlarges the
/// feasible set — so it is a systematic optimistic bias, not noise, and it
/// does not close as `tol` tightens because it is a change to the model
/// rather than a convergence slop.
///
/// `benchmarks/qp_four_way.md`, generated before gh #744, is the record: it
/// scores every engine against DOC 97/6 and put the unrelaxed convex arm at
/// **137/138 correct, 0 solved-but-wrong**, listing `LISWET1(re=2.5e-01)`
/// among Ipopt-MA57's wrong objectives. gh #744 moved this arm into that
/// column. Measured against HiGHS over the 91-instance netlib LP corpus,
/// going back to the declared model takes the median objective error from
/// `1.2e-08` to `3.8e-11` and instances within `1e-8` from 37 to 84.
///
/// The NLP arm keeps its widening and must: it is a feasible-iterate
/// log-barrier that needs `x` strictly inside its bounds, and matching Ipopt
/// is that arm's contract. Disabling it there is not a near miss but a
/// failure — the fixture sweep at `bound_relax_factor=0` turns
/// `square_flowsheet_resto` into `InfeasibleProblemDetected` and takes
/// `cresc4` from 105 iterations to 3000. This arm needs none of it: the IPM
/// is infeasible-start, strict interiority lives in the `(s, z)` slack/dual
/// pair that `init_iterate`/`recenter_warm` place, not in the geometry of the
/// declared box — which is why fixed variables (`lb == ub`, zero width) have
/// always shipped through here un-widened without incident.
///
/// So the arms now differ on constraint-degenerate models, by construction
/// and on purpose. That difference is reported rather than hidden:
/// `final_declared_constr_viol` measures the returned point against the model
/// as declared on either arm.
fn convex_bound_relax(app: &IpoptApplication) -> pounce_cli::qp_extract::BoundRelax {
    let opt = app.options();
    let set_value = |name: &str| {
        opt.get_numeric_value(name, "")
            .ok()
            .and_then(|(v, set)| set.then_some(v))
    };
    match set_value("bound_relax_factor") {
        // Unset: solve the model as declared.
        None => pounce_cli::qp_extract::BoundRelax::NONE,
        // Set: the caller asked for the widening by name, so give them
        // exactly the NLP arm's model -- `constr_viol_tol` caps it there too.
        Some(factor) => pounce_cli::qp_extract::BoundRelax {
            factor,
            cap: set_value("constr_viol_tol").unwrap_or(1e-4),
        },
    }
}

/// The console-contract knobs the convex drivers need from the options list.
///
/// Resolved once at the dispatch site because neither driver carries the
/// [`IpoptApplication`] the options live on, and both must answer the same
/// questions: may they print the end-of-run verdict, and were they asked for
/// timing statistics (gh #767).
#[derive(Debug, Clone, Copy, Default)]
struct ConvexConsole {
    /// `print_level >= 1` — gates the `EXIT:` / `POUNCE:` / `Status:` block,
    /// exactly as `Application::emit_end_summary` gates the NLP path's. At
    /// print_level 0 the console is silent by request.
    verdict: bool,
    /// `--json-debug`: stdout is a pure protocol channel there, so the
    /// machine-readable `Status:` line stays off it — the same carve-out the
    /// NLP path makes.
    json_debug: bool,
    /// `timing_statistics` or `print_timing_statistics` (which implies it) —
    /// run the detailed per-phase timers.
    collect_timing: bool,
    /// `print_timing_statistics` — emit the timing block after the verdict.
    print_timing: bool,
}

/// Read [`ConvexConsole`] off the application's options list.
///
/// gh #767: `print_timing_statistics` was registered, accepted, and reported
/// `(used)` by `print_user_options` on this path while emitting nothing —
/// so a tool attributing solve cost by phase read 0% for every phase of a
/// convex-routed instance, which is indistinguishable from "already fast".
fn convex_console(app: &IpoptApplication, json_dbg: bool) -> ConvexConsole {
    let opt = app.options();
    let yes = |name: &str| {
        opt.get_bool_value(name, "")
            .ok()
            .and_then(|(v, found)| found.then_some(v))
            .unwrap_or(false)
    };
    let print_timing = yes("print_timing_statistics");
    ConvexConsole {
        verdict: opt
            .get_integer_value("print_level", "")
            .map(|(v, _found)| v >= 1)
            .unwrap_or(true),
        json_debug: json_dbg,
        // `print_timing_statistics=yes` implies `timing_statistics=yes` per
        // its own option help, so either one arms the detailed timers.
        collect_timing: print_timing || yes("timing_statistics"),
        print_timing,
    }
}

/// Emit the convex path's end-of-run verdict: the `EXIT:` banner block and
/// the machine-readable `Status:` line, under the same gates the NLP path
/// applies to its own (see [`ConvexConsole`]). Shared by both convex drivers
/// so the two cannot drift.
fn print_convex_verdict(
    console: ConvexConsole,
    status: pounce_convex::QpStatus,
    timing: &pounce_common::timing::ConvexTimingStatistics,
) {
    if !console.verdict {
        return;
    }
    if console.print_timing {
        print!("{}", timing.report());
    }
    // One status vocabulary across both engines: the convex verdict mapped
    // onto the NLP-side enumerator, which is what `status_message` phrases
    // and what `upstream_name` spells the way CUTEst tables and the
    // reference JSONs do.
    let ars = qp_status_to_ars(status);
    // The same quantity the NLP path prints on this line: the driver's own
    // `OverallAlgorithm` total, not the solve-only figure the one-line result
    // above already carries.
    print::print_convex_end(ars, timing.overall_alg.total_wallclock_time());
    if !console.json_debug {
        println!("Status: {}", ars.upstream_name());
    }
}

fn convex_opts_with_remaining(
    mut opts: pounce_convex::QpOptions,
    started: std::time::Instant,
) -> pounce_convex::QpOptions {
    if let Some(limit) = opts.time_limit {
        opts.time_limit = Some(limit.saturating_sub(started.elapsed()));
    }
    opts
}

/// Charge `spent` against `max_wall_time`, so a solve that gets handed from one
/// engine to another spends **one** budget rather than one per engine.
///
/// The convex driver already deducts its own extraction and presolve from the
/// budget it passes down (`convex_opts_with_remaining`). The gap this closes is
/// one level up: when a convex attempt declines the problem (gh #535's LP→NLP
/// reroute, or the conic path's `socp_nlp_fallback`) the NLP solve that takes
/// over builds its `Deadline` from the *option value*, which still names the
/// whole budget. A run that spent 55 of its 60 seconds convex-side would then be
/// granted 60 more, and `max_wall_time` would buy nearly twice the wall clock it
/// promises.
///
/// Applies only when the user actually set the option. Unset it is `1e6` — the
/// effectively-unbounded default — and rewriting that as `1e6 - 3.2` states
/// nothing the default did not, while making the option read as explicitly
/// chosen to everything downstream that tests the `explicitly_set` flag.
///
/// A budget that is entirely gone floors at [`WALL_BUDGET_FLOOR`] rather than
/// zero: the option is registered with a *strict* lower bound of 0, so `0.0` is
/// rejected as invalid and the write would silently do nothing — leaving the
/// full budget in place, which is the failure this exists to prevent. The floor
/// is small enough that the NLP path's first deadline check trips on it.
fn charge_wall_budget(
    opts: &mut pounce_common::options_list::OptionsList,
    spent: std::time::Duration,
) {
    /// Smallest budget that can be *stored* — see [`charge_wall_budget`].
    const WALL_BUDGET_FLOOR: f64 = 1e-9;

    if let Ok((limit, true)) = opts.get_numeric_value("max_wall_time", "") {
        let left = (limit - spent.as_secs_f64()).max(WALL_BUDGET_FLOOR);
        let _ = opts.set_numeric_value("max_wall_time", left, true, false);
    }
}

/// Returns `None` when the LP→NLP fallback fires (gh #535): the problem is an
/// LP, the caller allowed the fallback, and the convex solve finished without a
/// certificate, so the caller falls through to the general NLP interior-point
/// path. No status line, `.sol` or JSON report has been emitted in that case —
/// the decision is taken above all three, so a rerouted solve produces exactly
/// one verdict. (A `Presolve:` reduction line may already have been printed;
/// it reports what presolve did, not what the solve concluded.) See
/// [`lp_declines_to_nlp`] for the gating.
fn run_convex_qp(
    prob: &nl_reader::NlProblem,
    class: pounce_cli::dispatch::ProblemClass,
    sol_path: Option<&std::path::Path>,
    presolve_on: bool,
    json_cfg: Option<(&std::path::Path, ReportDetail, InputDescriptor)>,
    debug_hook: Option<&Rc<RefCell<pounce_cli::debug_repl::SolverDebugger>>>,
    ampl: bool,
    convex_opts: pounce_convex::QpOptions,
    // gh #744/#745: the `bound_relax_factor` widening applied to the extracted
    // model, so this path solves what the NLP path solves.
    bound_relax: pounce_cli::qp_extract::BoundRelax,
    // Use the `pounce-qp` parametric active-set engine instead of the IPM
    // (`solver_selection=qp-active-set`). Everything else about this driver —
    // extraction, presolve, postsolve, reporting, `.sol` writing — is shared.
    use_active_set: bool,
    // Inner-engine overrides from the `sqp_qp_*` family; empty for the IPM.
    engine_overrides: pounce_convex::ActiveSetOverrides,
    // gh #535: may an uncertified LP solve be handed back to the NLP path?
    allow_nlp_fallback: bool,
    // Verdict / timing-statistics switches read off the options list.
    console: ConvexConsole,
    // The `.nl`'s suffixes, when this run is to serve a parametric sensitivity
    // step here rather than reroute it. `None` for every other run.
    sens_suffixes: Option<&nl_reader::NlSuffixes>,
    // May an inexpressible pin hand the whole model back to the NLP path?
    // True under `auto`, false under an explicit convex `solver_selection`.
    sens_may_decline: bool,
) -> Option<ExitCode> {
    let t0 = std::time::Instant::now();
    use pounce_convex::HessianInertia;
    use pounce_convex::active_set::solve_qp_active_set_inertia;
    use pounce_convex::presolve::{FixpointExit, PresolveOutcome, presolve};
    use pounce_convex::{QpOptions, QpStatus, solve_qp_ipm, solve_qp_ipm_debug};

    // What the classifier found out about `P`, handed to the engine rather than
    // assumed by it. `NonconvexQp` reaches this driver only through an explicit
    // `solver_selection=qp-active-set` (gh #786); every other class here was
    // certified convex by `hessian_is_psd`, and claiming PSD for them is what
    // keeps their solve bit-identical to what it was.
    let inertia = if class == pounce_cli::dispatch::ProblemClass::NonconvexQp {
        HessianInertia::Indefinite
    } else {
        HessianInertia::Psd
    };

    // gh #767: per-phase wall clock for the convex path. The struct is always
    // built (it costs nothing when the detailed timers are off) and the sink
    // is always installed, so `pounce-linsol` can charge the factorization and
    // back-solve rows from several crates below this driver.
    let timing = Rc::new(pounce_common::timing::ConvexTimingStatistics::new());
    timing.set_detailed_enabled(console.collect_timing);
    timing.overall_alg.start();
    let _timing_scope = pounce_common::timing::ConvexTimingScope::open(&timing);

    let (qp, con_map, obj_nl_const) = {
        let _t = timing.extraction.guard();
        match pounce_cli::qp_extract::extract_qp_with_map(prob, bound_relax) {
            Some(q) => q,
            None => {
                eprintln!(
                    "pounce: internal error: {} not extractable as QP",
                    class.name()
                );
                return Some(ExitCode::from(2));
            }
        }
    };

    // Resolve the sensitivity pins from the `.nl`'s constraint indices into
    // the extracted QP's equality rows, BEFORE any solve. A refusal here has to
    // cost nothing: under `auto` it hands the whole model to the NLP path, and
    // that path owns the one verdict — so nothing may have been printed and no
    // `.sol` written by the time we find out.
    let sens_pins = match sens_suffixes {
        Some(suffixes) => {
            match pounce_cli::convex_sens::resolve_pins(suffixes, &con_map, &qp, prob.n) {
                Ok(pins) => Some(pins),
                Err(why) if sens_may_decline => {
                    eprintln!(
                        "pounce: note: the .nl requests a parametric sensitivity step, but \
                         {} on the extracted convex model; routing to the general NLP \
                         interior-point path, which expresses it.",
                        why.describe()
                    );
                    return None;
                }
                Err(why) => {
                    eprintln!(
                        "pounce: warning: the .nl requests a parametric sensitivity step, \
                         but {} on the extracted convex model, and solver_selection forces \
                         the convex solver; the request will be skipped. Use \
                         solver_selection=nlp or auto to obtain it.",
                        why.describe()
                    );
                    None
                }
            }
        }
        None => None,
    };

    // The reported objective must include *both* constant sources: the
    // `.nl` linear-section constant (`obj_constant`) and any degree-0 term
    // AMPL/Pyomo folded into the nonlinear objective tree (`obj_nl_const`,
    // recovered by `extract_qp_with_map`). Dropping the latter makes the
    // convex solve report an objective off by that constant versus the NLP
    // path (e.g. HS21 by −100, HS35 by +9). Both are in user sense.
    let obj_const = prob.obj_constant + obj_nl_const;
    let sign = if prob.minimize { 1.0 } else { -1.0 };

    let backend = || -> Box<dyn SparseSymLinearSolverInterface> {
        Box::new(pounce_feral::FeralSolverInterface::new())
    };
    // With presolve on, reduce the problem (logging what was removed),
    // solve the reduced problem, then postsolve back to the extracted-QP
    // space — so the `con_map`-based dual recovery below still applies.
    // Trivial infeasibility / unboundedness is reported without solving.
    let trivial = |status| pounce_convex::QpSolution {
        status,
        x: vec![0.0; qp.n],
        y: vec![0.0; qp.m_eq()],
        z: vec![0.0; qp.m_ineq()],
        z_lb: vec![0.0; qp.n],
        z_ub: vec![0.0; qp.n],
        obj: 0.0,
        iters: 0,
        iterates: Vec::new(),
    };
    // Collect the per-iteration convergence trace only when a Full-detail
    // JSON report was requested (it carries the `iterations` array); the
    // default solve stays trace-free.
    let want_trace = matches!(&json_cfg, Some((_, ReportDetail::Full, _)));
    let qp_opts = QpOptions {
        collect_iterates: want_trace,
        // Tell the solver the objective constant it is *not* carrying (gh
        // #689). `QpProblem` holds the quadratic form only, so on a
        // least-squares-shaped objective the solver's `obj` is the reported one
        // displaced by `obj_const` — unbounded displacement, `5e11` on the
        // `scaled_feasible` pair — and the scale-relative stopping test then
        // normalizes the duality gap by a magnitude that belongs to the
        // constant rather than to the solution. In the solver's own (minimize)
        // sense the constant is `sign · obj_const`, the inverse of the
        // `reported_obj` line below. Convergence-test normalizer only: it
        // changes no residual, no dual, and not `sol.obj`.
        obj_constant: sign * obj_const,
        ..convex_opts
    };
    // The reduced problem presolve hands the solver differs from `qp` by
    // `ps.obj_offset()`, so the constant that makes *it* commensurate with the
    // user's objective carries that offset too.
    let solve_opts_offset = |offset: f64| {
        convex_opts_with_remaining(
            QpOptions {
                obj_constant: qp_opts.obj_constant + offset,
                ..qp_opts
            },
            t0,
        )
    };
    let solve_opts = || solve_opts_offset(0.0);
    // The interior-point solve, with the interactive debugger attached when
    // there is one (gh #892).
    //
    // Routing the hook through here rather than through an arm of its own is
    // what keeps presolve on under the debugger. It used to be skipped, so
    // that the inspected `x`/`s`/`y`/`z` blocks were the user's rows rather
    // than a reduced set — but the price was that the debugged run solved a
    // *different, smaller* problem than the plain one, which is the same
    // "attaching the debugger changes the solve" defect gh #892 is about, one
    // level up from the driver substitution. A user who wants the unreduced
    // blocks asks for them with `qp_presolve=no`, and then both runs agree
    // again because both skip it.
    //
    // Guarded on `!use_active_set`: the debugger hooks barrier-IPM iterations
    // and has no active-set analogue, so under that engine it must not engage
    // — the caller has already printed the note saying so.
    let ipm_solve = |p: &pounce_convex::QpProblem, o: &QpOptions| -> pounce_convex::QpSolution {
        match debug_hook.filter(|_| !use_active_set) {
            Some(hook) => {
                let mut h = hook.borrow_mut();
                solve_qp_ipm_debug(p, o, &mut *h, backend)
            }
            None => solve_qp_ipm(p, o, backend),
        }
    };
    // What presolve did, held back until we know this solve is the one that
    // reports (gh #535). These lines describe the reduction, not the verdict,
    // but they are the *only* stdout a declined convex attempt would otherwise
    // leave behind — and "the rerouted run prints nothing from the attempt it
    // discarded" is a cleaner contract than "nothing except one line". Flushed
    // below, immediately after the fallback check.
    let mut presolve_log: Vec<String> = Vec::new();
    let sol = if qp_opts.max_iter == 0 {
        // AMPL/Ipopt semantics: `max_iter=0` takes no iterations and so
        // cannot reach optimality. Presolve can otherwise solve a trivial
        // problem (e.g. an unconstrained quadratic) directly — or the IPM's
        // reduced/empty solve can report Optimal — regardless of the cap, so
        // enforce the zero-iteration stop here before any solve runs
        // (pounce#186). Mirrors the NLP path's MaximumIterationsExceeded.
        trivial(QpStatus::IterationLimit)
    } else if presolve_on {
        let outcome = {
            let _t = timing.presolve.guard();
            presolve(&qp)
        };
        match outcome {
            PresolveOutcome::Reduced(ps) => {
                // A screen claimed infeasibility and the re-derivation without
                // the speculative fixings would not reproduce it, so presolve
                // solved on instead (gh #523). Say so: the guard turns a false
                // `Infeasible_Problem_Detected` into a normal solve, and this
                // line is the only trace of the reduction that misfired.
                if let Some(trigger) = ps.discarded_infeasibility() {
                    presolve_log.push(format!(
                        "Presolve: discarded an unconfirmed infeasibility claim — \
                         {trigger}; solving normally"
                    ));
                }
                let st = ps.stats();
                if st.reduced_anything() {
                    // Whether the fixpoint converged or the layer cap stopped
                    // it (gh #527), as a suffix rather than a line of its own.
                    // The corpus sweep on #530 measured the cap binding on 46%
                    // of LP and 25% of QP models — it is the common case, not
                    // an alarm, and it never changed the structural reduction
                    // on any of the 394 models that presolve at all. A second
                    // stdout line on half of all solves would read as a
                    // warning about something that is working as designed;
                    // what the reduction needs to carry is which of the two it
                    // came out of, and that fits here.
                    let exit = match st.exit {
                        FixpointExit::Fixpoint => String::new(),
                        FixpointExit::RoundCap => {
                            format!(", cap-truncated after {} layers", st.rounds)
                        }
                    };
                    presolve_log.push(format!(
                        "Presolve: {}{} vars, {}{} rows (fixed {}, \
                         free-fixed {}, substituted {}, aggregated {}, \
                         forcing {}, dominated {}, tightened {}{})",
                        st.orig_vars,
                        st.reduced_vars,
                        st.orig_rows,
                        st.reduced_rows,
                        st.fixed_vars,
                        st.free_cols_fixed,
                        st.free_col_singletons,
                        st.aggregated_vars,
                        st.forcing_rows,
                        st.dominated_cols,
                        st.tightened_bounds,
                        exit,
                    ));
                }
                let red = {
                    let _t = timing.solve.guard();
                    if use_active_set {
                        let mut mk = backend;
                        solve_qp_active_set_inertia(
                            &ps.reduced,
                            &solve_opts_offset(ps.obj_offset()),
                            &engine_overrides,
                            inertia,
                            &mut mk,
                        )
                    } else {
                        ipm_solve(&ps.reduced, &solve_opts_offset(ps.obj_offset()))
                    }
                };
                // The postsolve lift is presolve's other half, so it is
                // charged to the same row.
                let _t = timing.presolve.guard();
                ps.postsolve(&red)
            }
            PresolveOutcome::Infeasible(trigger) => {
                // Name the screen and what it tripped on. A presolve
                // infeasibility arrives with no iteration behind it, so this
                // line is the whole record of *why* (gh #523).
                presolve_log.push(format!("Presolve: proved primal infeasible — {trigger}"));
                trivial(QpStatus::PrimalInfeasible)
            }
            PresolveOutcome::Unbounded => {
                // The sibling of the line above, and it exists for the same
                // reason (gh #523, gh #892 re-review): a presolve verdict
                // arrives with no iteration behind it, so this line is the
                // whole record of *why*. `Unbounded` carries no trigger
                // payload because it has exactly one cause — a free column
                // with a nonzero objective coefficient — so the cause is
                // named here instead.
                presolve_log.push(
                    "Presolve: proved unbounded below — a free column with a \
                     nonzero objective coefficient"
                        .to_string(),
                );
                trivial(QpStatus::DualInfeasible)
            }
        }
    } else if use_active_set {
        let mut mk = backend;
        let _t = timing.solve.guard();
        solve_qp_active_set_inertia(&qp, &solve_opts(), &engine_overrides, inertia, &mut mk)
    } else {
        let _t = timing.solve.guard();
        ipm_solve(&qp, &solve_opts())
    };
    let elapsed = t0.elapsed().as_secs_f64();

    // gh #535: the convex path finished an LP without a certificate. An LP is
    // also a valid NLP, and the general filter-IPM in this same binary solves
    // the degenerate rank-deficient ones the interior path cannot certify
    // (NETLIB `gen`/`gen1`: 199 iters / 191 s at reduced accuracy here, 19
    // iters / 1.0 s and a strict certificate there). Hand it over rather than
    // reporting the uncertified iterate as the last word.
    //
    // This sits above the status line, the `.sol` write and the JSON report on
    // purpose — everything below is the verdict, and the rerouted solve owns
    // it. See `lp_declines_to_nlp` for why each gate is there.
    if lp_declines_to_nlp(class, sol.status, allow_nlp_fallback) {
        let res = sol.kkt_residuals(&qp);
        eprintln!(
            "pounce: note: the convex ({}) solve did not certify a KKT point \
             after {} iterations in {elapsed:.3}s (KKT error {:.2e} against \
             tol {:.1e}); an LP or convex QP is also a valid NLP, so it is \
             being re-solved on the general NLP interior-point path, which \
             certifies the degenerate, rank-deficient and badly-scaled models \
             the interior path stalls on (gh #133, gh #535). Use \
             solver_selection=qp-ipm to see the convex result instead.",
            class.name(),
            sol.iters,
            res.kkt_error(),
            qp_opts.tol,
        );
        return None;
    }

    // This solve is the one that reports, so what presolve did belongs on the
    // record after all.
    for line in &presolve_log {
        println!("{line}");
    }

    // Report the objective in the user's original sense, including the
    // dropped constant term: f_user = sign * (½xᵀPx + cᵀx) + const.
    let reported_obj = sign * sol.obj + obj_const;

    let (msg, ok, srn) = convex_status_report(sol.status);
    // Name the engine that actually ran — the two report different iteration
    // counts (barrier iterations vs active-set changes), so labelling an
    // active-set solve "IPM" would misread both the solver and the number.
    let engine = if use_active_set {
        "active-set, pounce-qp"
    } else {
        "IPM, pounce-convex"
    };
    println!(
        "POUNCE ({} {engine}): {msg}  obj={reported_obj:.8}  iters={}  ({elapsed:.3}s)",
        class.name(),
        sol.iters,
    );
    // gh #848: an indefinite QP whose claimed optimum the second-order screen
    // refuted lands here as `NumericalFailure`, which the shared console
    // vocabulary renders "INTERNAL ERROR: Unknown SolverReturn value." — a
    // message that reads like a crash for what is actually a correct and
    // deliberate refusal. Say what happened and where the answer is.
    //
    // This is a *refusal*, which is what `v0.10.0` did with the whole class
    // before gh #786 admitted it; the intervening behaviour was to return the
    // saddle under `Optimal`. `nonconvex_qp_ineq` is the corpus's own instance:
    // `min x₀x₁ s.t. x₀ + x₁ ≥ 2` over `[0, 4]²`, where the engine settles on
    // `(1, 1)` at `f = 1` — a *maximum* along the active constraint, since
    // `f(1+t, 1−t) = 1 − t²` — while `(0, 2)` is feasible at `f = 0`.
    if use_active_set && !ok && inertia == HessianInertia::Indefinite {
        eprintln!(
            "pounce: note: the active-set engine reached a point that is not a \
             local minimum of this indefinite QP — a feasible direction of \
             negative curvature leads to a strictly better point — so its \
             first-order verdict was refused rather than reported as optimal \
             (gh #848). Its `optimal` on an indefinite Hessian means first-order \
             KKT plus no counterexample found, which is weaker than a local \
             guarantee. Use solver_selection=nlp for one: the NLP filter \
             line-search interior-point path is where `auto` sends this class, \
             and it does give a local optimum."
        );
    }
    // gh #293 naive-caller guardrail: if the solve did not cleanly converge and
    // the objective curvature is tiny relative to the data, say so — the status
    // is honest but a naive caller might otherwise treat a truncated objective
    // as the optimum.
    if let Some(warn) = sol.scaling_diagnostic(&qp) {
        eprintln!("pounce: {warn}");
    }

    // Final KKT residuals from pounce-convex; reused for both the Ipopt-style
    // summary block and the JSON report below.
    let res = sol.kkt_residuals(&qp);
    // ... but `qp` is the model the SOLVER was handed, whose inequality rows
    // and variable box carry the `bound_relax_factor` widening
    // (`qp_extract::BoundRelax`). That is the right model for the convergence
    // test — pounce-convex's acceptance tests call `kkt_residuals` on it by
    // design, and gh #744/#745 made the widening deliberate so this arm
    // solves what the NLP arm solves — and the wrong one to REPORT as the
    // caller's feasibility. On `afiro` the returned point sits 4.99e-06
    // outside the declared row `b = 500` (exactly `1e-8·500`) while this
    // reads 8.68e-13. Report the declared model's numbers instead; every
    // solver decision still reads `res`, so no trajectory moves.
    let reported_res = pounce_cli::qp_extract::declared_residuals_qp(prob, &sol, bound_relax);
    // Ipopt-style summary so the objective/iteration count are scrapable by
    // consumers that parse Ipopt's end-of-run block (see print_convex_summary).
    print::print_convex_summary(
        sol.iters,
        reported_obj,
        res.primal_infeasibility,
        res.dual_infeasibility,
        res.complementarity,
        res.kkt_error(),
        // Ipopt's `Variable bound violation`, measured against the box the
        // caller declared when a widening was applied and against the solved
        // box otherwise — where the two are the same object, so it is one
        // measurement either way and never a stand-in for one. This arm
        // printed a hardcoded `0.0` here until gh#900, which is the right
        // number on an unwidened solve and a false reassurance on the class
        // the line exists for.
        reported_res
            .map(|d| d.bound_violation)
            .unwrap_or(res.bound_violation),
        reported_res.map(|d| d.primal_infeasibility),
    );

    // Recover per-constraint duals once (mapped from the QP multipliers back
    // to per-`.nl`-constraint order); used by both the `.sol` and the JSON
    // report.
    let recovery = timing.solution_recovery.guard();
    let lambda = pounce_cli::qp_extract::recover_duals(prob, &con_map, &sol.y, &sol.z);

    // Bound multipliers (`ipopt_zL_out`/`ipopt_zU_out`). The QP extractor puts
    // the `.nl` variable bounds in the solver's explicit box, so these come
    // back directly in `sol.z_lb`/`z_ub`. They are for the *internal* minimize
    // form (`½xᵀPx + cᵀx`, a maximize objective negated), so `sign` restores
    // the user's objective sense — the same conversion `recover_duals` applies
    // to the constraint duals. The Ipopt output convention (verified
    // numerically, gh #296) is `ipopt_zL_out = +z_l`, `ipopt_zU_out = −z_u`,
    // both equal to the objective-gradient component at the bound. QP
    // variables are 1:1 with the `.nl` variables, so no remap is needed.
    let (z_lb_raw, z_ub_raw) = pounce_cli::qp_extract::recover_bound_mults(prob, &sol);
    let z_l_suffix: Vec<f64> = z_lb_raw.iter().map(|&z| sign * z).collect();
    let z_u_suffix: Vec<f64> = z_ub_raw.iter().map(|&z| -sign * z).collect();
    let mut qp_bound_suffixes = vec![
        nl_writer::SolSuffix {
            name: "ipopt_zL_out".to_string(),
            target: nl_writer::SolSuffixTarget::Var,
            values: nl_writer::SolSuffixValues::Real(z_l_suffix),
        },
        nl_writer::SolSuffix {
            name: "ipopt_zU_out".to_string(),
            target: nl_writer::SolSuffixTarget::Var,
            values: nl_writer::SolSuffixValues::Real(z_u_suffix),
        },
    ];

    // The parametric step, on the same factored KKT the solve just produced.
    // Its `.sol` block is `sens_sol_state_1`, the same name and shape the NLP
    // path writes, so a consumer cannot tell which engine answered.
    //
    // A failure here is reported, never swallowed: by this point the verdict is
    // committed to the convex path, so the honest outcome is "solved, and here
    // is why the step is missing" rather than a silently absent suffix — which
    // is the issue #196 failure mode in a new place.
    if let Some(pins) = &sens_pins {
        match pounce_cli::convex_sens::perturbed_x(&qp, &sol, &solve_opts(), pins, backend) {
            Ok(x_pert) => {
                qp_bound_suffixes.push(pounce_cli::convex_sens::sens_suffix(x_pert));
            }
            Err(why) => eprintln!(
                "pounce: warning: the parametric sensitivity step was requested but not \
                 produced on the convex path: {why}. Use solver_selection=nlp for the \
                 general path's step."
            ),
        }
    }
    recovery.stop();

    // The end-of-run verdict, in the shape the NLP path emits it (gh #767).
    // After the residual block and the dual recovery so the timing rows cover
    // the whole driver, and before the `.sol` / JSON writes, which report
    // nothing to stdout.
    timing.overall_alg.end();
    print_convex_verdict(console, sol.status, &timing);

    // Write a `.sol` if requested: primal x and recovered constraint duals in
    // the AMPL `.sol` convention.
    if let Some(path) = sol_path {
        let payload = nl_writer::SolutionFile {
            message: &format!("POUNCE {} IPM (pounce-convex): {msg}", class.name()),
            x: &sol.x,
            mult_g: &lambda,
            solve_result_num: srn,
            suffixes: &qp_bound_suffixes,
        };
        // Log a `.sol` write failure but do not early-return a distinct exit
        // code: the NLP path (main.rs:1091-1093) only logs, and under `-AMPL`
        // the final exit must still follow the solve-outcome contract.
        if let Err(e) = nl_writer::write_sol_file_with_options(path, &payload, &prob.ampl_options) {
            eprintln!("pounce: failed to write {}: {e}", path.display());
        }
    }

    // Emit the JSON solve report, when requested — same `pounce.solve-report/v1`
    // schema as the NLP path, so the benchmark harness can compare QP and NLP
    // solves uniformly. (Per-iteration history is NLP-only for now; the convex
    // driver does not yet feed the iterate trace, so `iterations` stays empty
    // even at Full detail.)
    if let Some((json_path, detail, input)) = json_cfg {
        let mut builder = ReportBuilder::new(detail, input);
        builder.problem.n_variables = qp.n as _;
        builder.problem.n_constraints = lambda.len() as _;
        builder.problem.n_objectives = 1;
        builder.problem.minimize = prob.minimize;
        builder.solution.engine = if use_active_set {
            "qp-active-set"
        } else {
            "cvx-qp"
        }
        .to_string();
        builder.solution.status = qp_status_to_ars(sol.status);
        builder.solution.solve_result_num = srn;
        builder.solution.objective = reported_obj;
        builder.solution.x = sol.x.clone();
        builder.solution.lambda = lambda.clone();
        builder.stats.iteration_count = sol.iters as _;
        builder.stats.final_objective = reported_obj;
        builder.stats.total_wallclock_time_secs = elapsed;
        // Real final KKT residuals (from pounce-convex, computed above), so the
        // harness sees genuine convergence numbers rather than zeros.
        builder.stats.final_constr_viol = res.primal_infeasibility;
        builder.stats.final_dual_inf = res.dual_infeasibility;
        builder.stats.final_compl = res.complementarity;
        builder.stats.final_kkt_error = res.kkt_error();
        // How far outside the model AS DECLARED the returned point sits —
        // `final_constr_viol` measures the `bound_relax_factor`-widened model
        // the solver was handed, which understates it by the widening.
        builder.stats.final_declared_constr_viol = reported_res
            .map(|d| d.primal_infeasibility)
            .unwrap_or(f64::NAN);
        // Unconditional, unlike the line above: this is a summary *row*, not a
        // warning that only fires when a widening moved the answer, so it
        // carries a real number on every solve.
        builder.stats.final_declared_box_viol = reported_res
            .map(|d| d.bound_violation)
            .unwrap_or(res.bound_violation);
        // Per-iteration convergence trace at Full detail (the convex IPM's
        // iterate records map onto the report's IterRecord schema, shared with
        // the NLP path so the harness reads one format).
        if matches!(detail, ReportDetail::Full) {
            builder.iterations = sol
                .iterates
                .iter()
                .map(|it| IterRecord {
                    iter: it.iter as _,
                    objective: it.objective,
                    inf_pr: it.primal_infeasibility,
                    inf_du: it.dual_infeasibility,
                    mu: it.mu,
                    alpha_primal: it.alpha_primal,
                    alpha_dual: it.alpha_dual,
                    ..IterRecord::default()
                })
                .collect();
        }
        let report = builder.finish();
        if let Err(e) = write_report_file(json_path, &report) {
            eprintln!(
                "pounce: failed to write JSON report to {}: {e}",
                json_path.display()
            );
        } else {
            eprintln!("pounce: wrote {}", json_path.display());
        }
    }

    Some(convex_exit_code(ok, ampl))
}

/// Solve a classified **convex QCQP** by reformulating it to a second-order
/// cone program and running the conic IPM (`pounce-convex`). Mirrors
/// [`run_convex_qp`]: same objective-constant fold-back, `.sol`/JSON output,
/// and per-constraint dual recovery, but the constraints carry quadratic rows
/// that become SOC blocks (see `qp_extract::extract_socp_with_map`). Presolve
/// is skipped — it is the QP-path's nonnegative-orthant reducer and is not
/// cone-aware.
///
/// Returns `None` when `allow_nlp_fallback` is set and the conic solve came
/// back without a verified KKT point: the caller then falls through to the
/// general NLP interior-point path. Nothing has been printed or written to
/// the `.sol`/JSON in that case — the decision is taken before any output, so
/// the fallback solve owns the whole report and a user never sees two verdicts
/// for one solve. See the call site for why this exists.
fn run_convex_socp(
    prob: &nl_reader::NlProblem,
    class: pounce_cli::dispatch::ProblemClass,
    sol_path: Option<&std::path::Path>,
    json_cfg: Option<(&std::path::Path, ReportDetail, InputDescriptor)>,
    debug_hook: Option<&Rc<RefCell<pounce_cli::debug_repl::SolverDebugger>>>,
    ampl: bool,
    convex_opts: pounce_convex::QpOptions,
    // gh #744/#745: see the same parameter on `run_convex_qp`.
    bound_relax: pounce_cli::qp_extract::BoundRelax,
    // #139 / gh #588 (Q9b): the shared convex-path presolve switch. Q1 left
    // this driver with no presolve at all, so `qp_presolve` was silently
    // ignored on every convex QCQP; it is honoured here through the
    // *cone-aware* entry point, never the orthant one — see the call below.
    presolve_on: bool,
    // gh #535: may an unverified conic solve be handed back to the NLP path?
    allow_nlp_fallback: bool,
    // Verdict / timing-statistics switches read off the options list.
    console: ConvexConsole,
) -> Option<ExitCode> {
    let t0 = std::time::Instant::now();
    use pounce_convex::presolve::{PresolveOutcome, presolve_conic};
    use pounce_convex::{QpOptions, solve_socp_ipm, solve_socp_ipm_debug};

    // Per-phase wall clock; see the same block in `run_convex_qp` (gh #767).
    let timing = Rc::new(pounce_common::timing::ConvexTimingStatistics::new());
    timing.set_detailed_enabled(console.collect_timing);
    timing.overall_alg.start();
    let _timing_scope = pounce_common::timing::ConvexTimingScope::open(&timing);

    let (qp, con_map, obj_nl_const, cones) = {
        let _t = timing.extraction.guard();
        match pounce_cli::qp_extract::extract_socp_with_map(prob, bound_relax) {
            Some(q) => q,
            None => {
                eprintln!(
                    "pounce: internal error: {} not extractable as SOCP",
                    class.name()
                );
                return Some(ExitCode::from(2));
            }
        }
    };

    // Reported objective includes both constant sources (the `.nl` linear
    // section and the degree-0 term folded into the nonlinear objective tree),
    // in the user's sense — identical to the QP path.
    let obj_const = prob.obj_constant + obj_nl_const;
    let sign = if prob.minimize { 1.0 } else { -1.0 };

    let backend = || -> Box<dyn SparseSymLinearSolverInterface> {
        Box::new(pounce_feral::FeralSolverInterface::new())
    };
    let want_trace = matches!(&json_cfg, Some((_, ReportDetail::Full, _)));
    let qp_opts = QpOptions {
        collect_iterates: want_trace,
        // The objective constant the solver is not carrying, in its own
        // (minimize) sense — see the QP path for what it is for (gh #689).
        // This path does not presolve, so there is no reduction offset to add.
        obj_constant: sign * obj_const,
        ..convex_opts
    };
    let solve_opts = || convex_opts_with_remaining(qp_opts, t0);
    let trivial = |status| pounce_convex::QpSolution {
        status,
        x: vec![0.0; qp.n],
        y: vec![0.0; qp.m_eq()],
        z: vec![0.0; qp.m_ineq()],
        z_lb: vec![0.0; qp.n],
        z_ub: vec![0.0; qp.n],
        obj: 0.0,
        iters: 0,
        iterates: Vec::new(),
    };
    // Held back until we know this solve is the one that reports (gh #535),
    // exactly as `run_convex_qp` does: these lines describe the reduction,
    // not the verdict, and a declined conic attempt must leave no stdout.
    let mut presolve_log: Vec<String> = Vec::new();
    // The conic solve, with the interactive debugger attached when there is
    // one (gh #892). See the twin in `run_convex_qp` for why the hook goes
    // through here instead of an arm of its own: it is what keeps presolve on
    // under the debugger, so the debugged run is the same problem the plain
    // run solves. `qp_presolve=no` is how you ask for the unreduced blocks.
    let conic_solve = |p: &pounce_convex::QpProblem,
                       k: &[pounce_convex::ConeSpec],
                       o: &QpOptions|
     -> pounce_convex::QpSolution {
        match debug_hook {
            Some(hook) => {
                let mut h = hook.borrow_mut();
                solve_socp_ipm_debug(p, k, o, &mut *h, backend)
            }
            None => solve_socp_ipm(p, k, o, backend),
        }
    };
    let sol = if qp_opts.max_iter == 0 {
        // `max_iter=0` cannot reach optimality — stop before any solve, the
        // same zero-iteration contract the QP path enforces (pounce#186).
        // Above the presolve arm for the same reason it is on the QP path:
        // presolve can otherwise settle a trivial problem without iterating.
        trivial(pounce_convex::QpStatus::IterationLimit)
    } else if presolve_on {
        // **`presolve_conic`, never `presolve`.** The orthant entry point
        // would hand `dedup_rows` an unprotected row list, and this driver's
        // rows are exactly the shape that breaks it: `extract_socp_with_map`
        // emits each quadratic row's linear part `aᵢ` *verbatim* as SOC rows
        // 0 and 1 of its block, so two quadratic constraints sharing a linear
        // part produce byte-identical rows in different cones.
        // `parallel_signature` hashes on the linear triplets alone, sees a
        // duplicate, and drops one — silently deleting half of one cone. See
        // `crates/pounce-convex/tests/presolve_conic_quadratic_rows.rs`.
        // `presolve_conic` protects every non-orthant row, which is what
        // makes this call safe; §7 of `dev-notes/quadratic-structure-
        // exploitation.md` is the validity table.
        let outcome = {
            let _t = timing.presolve.guard();
            presolve_conic(&qp, &cones)
        };
        match outcome {
            PresolveOutcome::Reduced(ps) => {
                if let Some(trigger) = ps.discarded_infeasibility() {
                    presolve_log.push(format!(
                        "Presolve: discarded an unconfirmed infeasibility claim — \
                         {trigger}; solving normally"
                    ));
                }
                let st = ps.stats();
                if st.reduced_anything() {
                    // No `cap-truncated` suffix here: `presolve_conic` is a
                    // single pass by construction (gh #527's round cap is a
                    // fixpoint notion), so `rounds` is always 1.
                    presolve_log.push(format!(
                        "Presolve: {}{} vars, {}{} rows (fixed {}, \
                         free-fixed {}, substituted {}, forcing {}, \
                         dominated {}, tightened {})",
                        st.orig_vars,
                        st.reduced_vars,
                        st.orig_rows,
                        st.reduced_rows,
                        st.fixed_vars,
                        st.free_cols_fixed,
                        st.free_col_singletons,
                        st.forcing_rows,
                        st.dominated_cols,
                        st.tightened_bounds,
                    ));
                }
                // The reduced cone partition: orthant blocks may shrink or
                // vanish, cone blocks pass through whole (that is what the
                // protection buys). `postsolve` restores `z` at the original
                // row indices, so `con_map`'s `z_row0`/`z_row1` — and hence
                // `recover_socp_duals` below — need no remapping.
                let red_cones = ps.reduced_cones(&cones);
                let red = {
                    let _t = timing.solve.guard();
                    conic_solve(&ps.reduced, &red_cones, &solve_opts())
                };
                // The postsolve lift is presolve's other half.
                let _t = timing.presolve.guard();
                ps.postsolve(&red)
            }
            PresolveOutcome::Infeasible(trigger) => {
                presolve_log.push(format!("Presolve: proved primal infeasible — {trigger}"));
                trivial(pounce_convex::QpStatus::PrimalInfeasible)
            }
            PresolveOutcome::Unbounded => {
                // See the twin in `run_convex_qp`.
                presolve_log.push(
                    "Presolve: proved unbounded below — a free column with a \
                     nonzero objective coefficient"
                        .to_string(),
                );
                trivial(pounce_convex::QpStatus::DualInfeasible)
            }
        }
    } else {
        let _t = timing.solve.guard();
        conic_solve(&qp, &cones, &solve_opts())
    };
    let elapsed = t0.elapsed().as_secs_f64();

    // The conic path returned no verified KKT point. A convex QCQP is still a
    // valid NLP — the same reasoning `SOCP_REFORM_FLOP_BUDGET` already uses to
    // route expensive-to-reformulate ones to the filter-IPM before solving — so
    // hand it to the NLP path
    // rather than reporting a failure with a working solver one branch away.
    //
    // `NumericalFailure` only. The other non-optimal statuses must NOT reroute:
    // `PrimalInfeasible`/`DualInfeasible` are verdicts the conic solver *did*
    // verify, and `IterationLimit` is the budget the caller asked for — it is
    // also what `max_iter=0` returns, whose zero-iteration contract (pounce#186)
    // requires stopping without a solve.
    //
    // Nothing has been printed yet: this sits above the status line, the `.sol`
    // write and the JSON report, so a rerouted solve emits exactly one verdict.
    if allow_nlp_fallback && matches!(sol.status, pounce_convex::QpStatus::NumericalFailure) {
        let res = sol.kkt_residuals_conic(&qp, &cones);
        eprintln!(
            "pounce: note: the conic ({}) solve returned no verified KKT point \
             after {} iterations (KKT error {:.2e}); a convex QCQP is also a \
             valid NLP, so it is being re-solved on the general NLP \
             interior-point path. Use solver_selection=socp to see the conic \
             result instead.",
            class.name(),
            sol.iters,
            res.kkt_error(),
        );
        return None;
    }

    // This solve is the one that reports, so what presolve did belongs on the
    // record after all.
    for line in &presolve_log {
        println!("{line}");
    }

    let reported_obj = sign * sol.obj + obj_const;

    let (msg, ok, srn) = convex_status_report(sol.status);
    println!(
        "POUNCE ({} conic IPM, pounce-convex): {msg}  obj={reported_obj:.8}  iters={}  ({elapsed:.3}s)",
        class.name(),
        sol.iters,
    );

    // Final KKT residuals from pounce-convex; reused for both the Ipopt-style
    // summary block and the JSON report below.
    // Cone-aware: the quadratic rows became SOC blocks, whose individual rows
    // legitimately violate `Gx ≤ h` at a perfectly feasible point, so the
    // orthant-only `kkt_residuals` reported a large bogus constraint violation
    // and NLP error for a solved problem (pounce#209).
    let res = sol.kkt_residuals_conic(&qp, &cones);
    // Declared-model numbers for reporting, as on the QP path above: `qp`
    // carries the `bound_relax_factor` widening, so measuring against it
    // understates how far the returned point sits outside the model the
    // caller wrote. `res` still drives every solver decision.
    let reported_res = pounce_cli::qp_extract::declared_residuals_socp(prob, &sol, bound_relax);
    // Ipopt-style summary so the objective/iteration count are scrapable by
    // consumers that parse Ipopt's end-of-run block (see print_convex_summary).
    print::print_convex_summary(
        sol.iters,
        reported_obj,
        res.primal_infeasibility,
        res.dual_infeasibility,
        res.complementarity,
        res.kkt_error(),
        // Ipopt's `Variable bound violation`, measured against the box the
        // caller declared when a widening was applied and against the solved
        // box otherwise — where the two are the same object, so it is one
        // measurement either way and never a stand-in for one. This arm
        // printed a hardcoded `0.0` here until gh#900, which is the right
        // number on an unwidened solve and a false reassurance on the class
        // the line exists for.
        reported_res
            .map(|d| d.bound_violation)
            .unwrap_or(res.bound_violation),
        reported_res.map(|d| d.primal_infeasibility),
    );

    // Per-constraint duals, mapped from the cone multipliers back to `.nl`
    // constraint order (best-effort for the quadratic rows; see
    // `recover_socp_duals`).
    let recovery = timing.solution_recovery.guard();
    let lambda = pounce_cli::qp_extract::recover_socp_duals(prob, &con_map, &sol.y, &sol.z);

    // Bound multipliers (`ipopt_zL_out`/`ipopt_zU_out`). As on the QP path the
    // variable bounds live in the solver's explicit box — outside the cone
    // partition, which covers only the linear-inequality rows and the SOC
    // blocks — so they come back in `sol.z_lb`/`z_ub`. `sign` restores the
    // user objective sense and the Ipopt output convention is
    // `ipopt_zL_out = +z_l`, `ipopt_zU_out = −z_u` (gh #296).
    let (z_lb_raw, z_ub_raw) = pounce_cli::qp_extract::recover_bound_mults(prob, &sol);
    let z_l_suffix: Vec<f64> = z_lb_raw.iter().map(|&z| sign * z).collect();
    let z_u_suffix: Vec<f64> = z_ub_raw.iter().map(|&z| -sign * z).collect();
    let socp_bound_suffixes = [
        nl_writer::SolSuffix {
            name: "ipopt_zL_out".to_string(),
            target: nl_writer::SolSuffixTarget::Var,
            values: nl_writer::SolSuffixValues::Real(z_l_suffix),
        },
        nl_writer::SolSuffix {
            name: "ipopt_zU_out".to_string(),
            target: nl_writer::SolSuffixTarget::Var,
            values: nl_writer::SolSuffixValues::Real(z_u_suffix),
        },
    ];
    recovery.stop();

    // The end-of-run verdict, in the shape the NLP path emits it (gh #767);
    // see the same call in `run_convex_qp` for the placement.
    timing.overall_alg.end();
    print_convex_verdict(console, sol.status, &timing);

    if let Some(path) = sol_path {
        let payload = nl_writer::SolutionFile {
            message: &format!("POUNCE {} conic IPM (pounce-convex): {msg}", class.name()),
            x: &sol.x,
            mult_g: &lambda,
            solve_result_num: srn,
            suffixes: &socp_bound_suffixes,
        };
        // Log a `.sol` write failure but do not early-return a distinct exit
        // code: the NLP path (main.rs:1091-1093) only logs, and under `-AMPL`
        // the final exit must still follow the solve-outcome contract.
        if let Err(e) = nl_writer::write_sol_file(path, &payload) {
            eprintln!("pounce: failed to write {}: {e}", path.display());
        }
    }

    if let Some((json_path, detail, input)) = json_cfg {
        let mut builder = ReportBuilder::new(detail, input);
        builder.problem.n_variables = qp.n as _;
        builder.problem.n_constraints = lambda.len() as _;
        builder.problem.n_objectives = 1;
        builder.problem.minimize = prob.minimize;
        builder.solution.engine = "cvx-qcqp".to_string();
        builder.solution.status = qp_status_to_ars(sol.status);
        builder.solution.solve_result_num = srn;
        builder.solution.objective = reported_obj;
        builder.solution.x = sol.x.clone();
        builder.solution.lambda = lambda.clone();
        builder.stats.iteration_count = sol.iters as _;
        builder.stats.final_objective = reported_obj;
        builder.stats.total_wallclock_time_secs = elapsed;
        builder.stats.final_constr_viol = res.primal_infeasibility;
        builder.stats.final_dual_inf = res.dual_infeasibility;
        builder.stats.final_compl = res.complementarity;
        builder.stats.final_kkt_error = res.kkt_error();
        // How far outside the model AS DECLARED the returned point sits —
        // `final_constr_viol` measures the `bound_relax_factor`-widened model
        // the solver was handed, which understates it by the widening.
        builder.stats.final_declared_constr_viol = reported_res
            .map(|d| d.primal_infeasibility)
            .unwrap_or(f64::NAN);
        // Unconditional, unlike the line above: this is a summary *row*, not a
        // warning that only fires when a widening moved the answer, so it
        // carries a real number on every solve.
        builder.stats.final_declared_box_viol = reported_res
            .map(|d| d.bound_violation)
            .unwrap_or(res.bound_violation);
        if matches!(detail, ReportDetail::Full) {
            builder.iterations = sol
                .iterates
                .iter()
                .map(|it| IterRecord {
                    iter: it.iter as _,
                    objective: it.objective,
                    inf_pr: it.primal_infeasibility,
                    inf_du: it.dual_infeasibility,
                    mu: it.mu,
                    alpha_primal: it.alpha_primal,
                    alpha_dual: it.alpha_dual,
                    ..IterRecord::default()
                })
                .collect();
        }
        let report = builder.finish();
        if let Err(e) = write_report_file(json_path, &report) {
            eprintln!(
                "pounce: failed to write JSON report to {}: {e}",
                json_path.display()
            );
        } else {
            eprintln!("pounce: wrote {}", json_path.display());
        }
    }

    Some(convex_exit_code(ok, ampl))
}

/// Process exit code for the convex (LP/QP/SOCP) solver paths, honoring the
/// AMPL solver-protocol contract. In `-AMPL` mode the termination is conveyed
/// through the `.sol` file's `solve_result_num`, so the process exits 0 for
/// any non-fatal solve outcome (infeasible, unbounded, iteration limit) just
/// as the NLP path does (main.rs:1103-1118) — a non-zero exit makes Pyomo /
/// the ASL interface raise `ApplicationError` and never read the `.sol`.
/// Genuine startup failures (bad `.nl`/option, unextractable problem) returned
/// non-zero earlier, before any solve, so reaching here in `-AMPL` mode means a
/// verdict was produced. Outside AMPL mode, an unsuccessful solve exits 1.
fn convex_exit_code(ok: bool, ampl: bool) -> ExitCode {
    if ok || ampl {
        ExitCode::SUCCESS
    } else {
        ExitCode::from(1)
    }
}

/// Translate the CLI's `--dump …` flags into a live `DiagnosticsState`.
/// Returns `Ok(None)` when no `--dump <cat>` was given (the `--dump-dir`
/// / `--dump-format` flags alone don't activate dumping).
fn build_diagnostics(
    dump_specs: &[(String, String)],
    dump_dir: Option<&std::path::PathBuf>,
    dump_format: Option<&str>,
) -> Result<Option<Rc<DiagnosticsState>>, String> {
    if dump_specs.is_empty() {
        if dump_dir.is_some() || dump_format.is_some() {
            return Err(
                "--dump-dir / --dump-format require at least one --dump <cat>[:spec]".to_string(),
            );
        }
        return Ok(None);
    }

    let dump_dir = dump_dir.cloned().unwrap_or_else(|| {
        let secs = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0);
        std::path::PathBuf::from(format!("pounce-dump-{secs}"))
    });

    let format = match dump_format {
        Some(f) => DumpFormat::parse(f)?,
        None => DumpFormat::Jsonl,
    };

    let mut config = DiagnosticsConfig::new(dump_dir);
    config.format = format;
    for (cat_str, spec_str) in dump_specs {
        let cat = DiagCategory::parse(cat_str)?;
        if cat == DiagCategory::Iterate {
            // `iterate:` accepts an extra `:summary` / `:full` variant
            // suffix after the iter filter. See parse_iterate_spec.
            let (filter, variant) = pounce_common::diagnostics::parse_iterate_spec(spec_str)?;
            config = config
                .with_category(cat, filter)
                .with_iterate_variant(variant);
        } else if cat == DiagCategory::Kkt {
            // `kkt:` accepts `+L` / `+L+Lvals` suffixes that pick up
            // the LDLᵀ factor's pattern (and optionally values). See
            // parse_kkt_spec.
            let (filter, variant) = pounce_common::diagnostics::parse_kkt_spec(spec_str)?;
            config = config.with_category(cat, filter).with_kkt_variant(variant);
        } else {
            let spec = IterSpec::parse(spec_str)?;
            config = config.with_category(cat, spec);
        }
    }

    let state = DiagnosticsState::new(config)
        .map_err(|e| format!("could not create dump directory: {e}"))?;
    Ok(Some(Rc::new(state)))
}

/// Drop a minimal JSON manifest summarising the run. Lets downstream
/// tools (and humans) join a dump directory back to its CLI args
/// without re-reading the per-iter files.
fn write_diagnostics_manifest(
    diag: &DiagnosticsState,
    problem_desc: &str,
    status: ApplicationReturnStatus,
) {
    let mut cats: Vec<String> = diag
        .config
        .categories
        .iter()
        .map(|(c, s)| format!("\"{}\":\"{:?}\"", c.as_str(), s))
        .collect();
    cats.sort();
    let manifest = format!(
        "{{\n  \"pounce_version\": \"{ver}\",\n  \"git\": \"{git}\",\n  \"problem\": \"{problem}\",\n  \"status\": \"{status:?}\",\n  \"format\": \"{fmt:?}\",\n  \"categories\": {{ {cats} }}\n}}\n",
        ver = env!("CARGO_PKG_VERSION"),
        git = env!("POUNCE_BUILD_GIT"),
        problem = problem_desc,
        fmt = diag.config.format,
        cats = cats.join(", "),
    );
    let _ = diag.write_top_level("manifest.json", &manifest);
}

/// Emit a sibling `timing.json` so dump consumers can correlate
/// per-iter files with the solve's wall-clock budget.
///
/// `overall_alg_secs` is always populated. The
/// `linear_system_*` splits are detailed timers gated on
/// `timing_statistics` (default "no", issue #190), so they read `0.0`
/// unless the run set `timing_statistics yes` (or
/// `print_timing_statistics yes`, which implies it).
fn write_diagnostics_timing(diag: &DiagnosticsState, app: &IpoptApplication) {
    let t = app.timing_stats();
    let body = format!(
        "{{\n  \"overall_alg_secs\": {a:.6},\n  \"linear_system_factorization_secs\": {f:.6},\n  \"linear_system_back_solve_secs\": {b:.6}\n}}\n",
        a = t.overall_alg.total_wallclock_time(),
        f = t.linear_system_factorization.total_wallclock_time(),
        b = t.linear_system_back_solve.total_wallclock_time(),
    );
    let _ = diag.write_top_level("timing.json", &body);
}

/// `--cite` output: the papers/software a user should cite when
/// publishing pounce results. Always lists the static core (pounce +
/// Wächter-Biegler); when `--cite <report.json>` supplies a solve
/// report, adds solve-aware extras for features the run used. `--bibtex`
/// switches the rendering to BibTeX. See [`pounce_cli::citations`].
fn run_cite(args: &Args) -> ExitCode {
    let report = match &args.cite_report {
        Some(path) => {
            let text = match std::fs::read_to_string(path) {
                Ok(t) => t,
                Err(e) => {
                    eprintln!("pounce: failed to read {}: {e}", path.display());
                    return ExitCode::from(2);
                }
            };
            match serde_json::from_str::<pounce_cli::solve_report::SolveReport>(&text) {
                Ok(r) => Some(r),
                Err(e) => {
                    eprintln!(
                        "pounce: {} is not a valid solve report: {e}",
                        path.display()
                    );
                    // Common mistake: passing the model (`.nl`) instead of a
                    // solve-report JSON. `--cite` takes the report produced by
                    // a prior solve (`--json-output out.json`), not the model;
                    // bare `pounce --cite` prints the static core with no run.
                    if path.extension().and_then(|e| e.to_str()) == Some("nl") {
                        eprintln!(
                            "pounce: --cite expects a solve-report JSON, not a model file. \
                             Run `pounce {} --json-output report.json` first, then \
                             `pounce --cite report.json` — or use bare `pounce --cite` for the core citations.",
                            path.display()
                        );
                    }
                    return ExitCode::from(2);
                }
            }
        }
        None => None,
    };

    let selected = pounce_cli::citations::select(report.as_ref());
    if args.cite_bibtex {
        print!("{}", pounce_cli::citations::render_bibtex(&selected));
    } else {
        print!("{}", pounce_cli::citations::render_human(&selected));
    }
    ExitCode::SUCCESS
}

/// `--about` output: version, build provenance, compiled-in features,
/// available linear-solver backends, and runtime paths. Intended for
/// bug reports — every field that distinguishes one build from another
/// should appear here.
fn print_about() {
    let pkg_ver = env!("CARGO_PKG_VERSION");
    let git = env!("POUNCE_BUILD_GIT");
    let when = env!("POUNCE_BUILD_TIME");
    let profile = env!("POUNCE_BUILD_PROFILE");
    let target = env!("POUNCE_BUILD_TARGET");
    let host = env!("POUNCE_BUILD_HOST");
    let rustc = env!("POUNCE_BUILD_RUSTC");

    println!("pounce {pkg_ver} (commit {git}, built {when})");
    println!();
    println!("Build:");
    println!("  profile:        {profile}");
    println!("  target:         {target}");
    if host != target {
        println!("  host:           {host}");
    }
    println!("  rustc:          {rustc}");
    println!();

    println!("Features:");
    #[cfg(feature = "ma57")]
    println!("  ma57:           enabled");
    #[cfg(not(feature = "ma57"))]
    println!("  ma57:           disabled (rebuild with --features ma57 to enable HSL MA57)");
    println!();

    println!("Linear solvers:");
    println!("  feral           FERAL pure-Rust sparse LDL^T  (always built-in)");
    #[cfg(feature = "ma57")]
    println!("  ma57            HSL MA57 via libcoinhsl       (compiled in)");
    #[cfg(not(feature = "ma57"))]
    println!(
        "  ma57            HSL MA57 via libcoinhsl       (not compiled; resolves to FERAL at runtime)"
    );
    println!();

    println!("Runtime paths:");
    match std::env::current_exe() {
        Ok(p) => println!("  executable:     {}", p.display()),
        Err(e) => println!("  executable:     <unknown: {e}>"),
    }
    match std::env::current_dir() {
        Ok(p) => println!("  cwd:            {}", p.display()),
        Err(e) => println!("  cwd:            <unknown: {e}>"),
    }
    println!();

    println!("Report bugs at {}/issues", env!("CARGO_PKG_REPOSITORY"));
}

/// Default backend factory used by the restoration sub-IPM. Mirrors
/// the `default_backend_factory` in `pounce-algorithm`: FERAL is the
/// shipping default, with MA57 available behind the `ma57` cargo
/// feature. The `feral_cfg` argument carries the `feral_*` extension
/// options (cascade-break / FMA / iterative-refinement) captured from
/// the application's options list, so per-problem `.opt` overrides
/// flow into the resto sub-IPM as well; `ma57_cfg` does the same for the
/// `ma57_*` options, read under the `"resto."` prefix by the caller.
///
/// Both arguments are snapshots. `ma57_cfg` used to be absent, which is
/// gh#825: this arm called `Ma57SolverInterface::new()` and every
/// `ma57_*` option a user set was accepted and then discarded, with no
/// warning and no observable effect on the solve.
fn default_backend_factory(
    feral_cfg: pounce_feral::FeralConfig,
    ma57_cfg: Ma57Config,
) -> LinearBackendFactory {
    Box::new(
        move |choice: LinearSolverChoice| -> Box<dyn SparseSymLinearSolverInterface> {
            match choice {
                LinearSolverChoice::Feral => Box::new(
                    pounce_feral::FeralSolverInterface::with_config(feral_cfg.clone()),
                ),
                LinearSolverChoice::Ma57 => {
                    #[cfg(feature = "ma57")]
                    {
                        Box::new(pounce_hsl::Ma57SolverInterface::with_options(
                            *ma57_cfg.options(),
                        ))
                    }
                    #[cfg(not(feature = "ma57"))]
                    {
                        let _ = &ma57_cfg;
                        Box::new(pounce_feral::FeralSolverInterface::with_config(
                            feral_cfg.clone(),
                        ))
                    }
                }
            }
        },
    )
}

#[cfg(test)]
mod convex_status_tests {
    use super::{convex_status_report, qp_status_to_ars};
    use pounce_convex::QpStatus;
    use pounce_nlp::return_codes::ApplicationReturnStatus;

    /// Code review 2026-06 item M20: the reduced-accuracy convex status
    /// (`OptimalInaccurate`) must surface to the user as a *distinct* outcome —
    /// not silently folded into a clean `Optimal`. It maps to AMPL
    /// `solve_result_num` 1 (Ipopt's own code for an accepted reduced-accuracy
    /// solve) with a distinct message, and onto the NLP-side
    /// `SolvedToAcceptableLevel` status, so callers reading either the `.sol`
    /// terminal line or the JSON report can tell it apart from a full-accuracy
    /// solve.
    ///
    /// The code moved out of the 100 band in gh #591 — see
    /// `pounce_solve_report::status_to_solve_result_num` — and must agree with
    /// the NLP path, which reports the same status.
    #[test]
    fn optimal_inaccurate_is_distinct_from_optimal() {
        let (msg, ok, srn) = convex_status_report(QpStatus::OptimalInaccurate);
        assert_eq!(
            srn,
            pounce_cli::solve_report::status_to_solve_result_num(
                ApplicationReturnStatus::SolvedToAcceptableLevel
            ),
            "the convex and NLP paths must report one code for one status",
        );
        assert_eq!(
            srn, 1,
            "Ipopt's code for an accepted reduced-accuracy solve"
        );
        assert!(ok, "a reduced-accuracy solve is still a usable success");
        assert!(
            msg.contains("acceptable"),
            "message should signal reduced accuracy, got {msg:?}"
        );

        let (opt_msg, _, opt_srn) = convex_status_report(QpStatus::Optimal);
        assert_eq!(opt_srn, 0);
        assert_ne!(
            srn, opt_srn,
            "OptimalInaccurate must not share Optimal's solve_result_num"
        );
        assert_ne!(msg, opt_msg, "the two must read differently to the user");

        // And on the NLP-side status vocabulary used by the JSON report.
        assert_eq!(
            qp_status_to_ars(QpStatus::OptimalInaccurate),
            ApplicationReturnStatus::SolvedToAcceptableLevel
        );
        assert_eq!(
            qp_status_to_ars(QpStatus::Optimal),
            ApplicationReturnStatus::SolveSucceeded
        );
    }

    /// A declined convex attempt is charged against the wall-clock budget, so
    /// the NLP solve that takes over cannot start a second full one.
    ///
    /// Built on a real `IpoptApplication` rather than a bare `OptionsList`
    /// because the two ways this write can silently do nothing — the option's
    /// *strict* lower bound of zero, and the clobber flag on the stored value —
    /// both live in the registration that only the real one carries.
    #[test]
    fn a_declined_convex_attempt_is_charged_against_the_wall_budget() {
        use std::time::Duration;

        let mut app = super::IpoptApplication::new();
        app.options_mut()
            .set_numeric_value("max_wall_time", 60.0, true, false)
            .unwrap();

        super::charge_wall_budget(app.options_mut(), Duration::from_secs_f64(55.0));
        let (left, set) = app
            .options()
            .get_numeric_value("max_wall_time", "")
            .unwrap();
        assert!(set, "the option must still read as explicitly set");
        assert!(
            (left - 5.0).abs() < 1e-9,
            "60s budget minus a 55s attempt must leave 5s, got {left}"
        );

        // A budget spent outright must not silently write back as the full
        // budget: `max_wall_time` is registered with a strict lower bound, so a
        // literal 0.0 would be rejected and leave 5s standing.
        super::charge_wall_budget(app.options_mut(), Duration::from_secs_f64(600.0));
        let (gone, _) = app
            .options()
            .get_numeric_value("max_wall_time", "")
            .unwrap();
        assert!(
            gone > 0.0 && gone < 1e-6,
            "an exhausted budget must store as positive-but-spent, got {gone}"
        );
    }

    /// The other half: an *unset* budget is left alone. `1e6` is the
    /// effectively-unbounded default, and rewriting it would both say nothing
    /// new and make the option read as user-chosen downstream.
    #[test]
    fn an_unset_wall_budget_is_not_rewritten() {
        use std::time::Duration;

        let mut app = super::IpoptApplication::new();
        let (before, set_before) = app
            .options()
            .get_numeric_value("max_wall_time", "")
            .unwrap();
        assert!(!set_before, "precondition: the option starts unset");

        super::charge_wall_budget(app.options_mut(), Duration::from_secs_f64(3.2));
        let (after, set_after) = app
            .options()
            .get_numeric_value("max_wall_time", "")
            .unwrap();
        assert_eq!(after, before);
        assert!(
            !set_after,
            "an untouched budget must not read as explicitly set"
        );
    }

    #[test]
    fn time_limit_maps_to_wall_clock_status() {
        let (msg, ok, srn) = convex_status_report(QpStatus::TimeLimit);
        assert_eq!(msg, "Maximum wallclock time exceeded.");
        assert!(!ok);
        assert_eq!(srn, 400);
        assert_eq!(
            qp_status_to_ars(QpStatus::TimeLimit),
            ApplicationReturnStatus::MaximumWallTimeExceeded
        );
    }
}

#[cfg(test)]
mod lp_nlp_fallback_tests {
    use super::lp_declines_to_nlp;
    use pounce_cli::dispatch::ProblemClass;
    use pounce_convex::QpStatus;

    const ALL_STATUSES: [QpStatus; 7] = [
        QpStatus::Optimal,
        QpStatus::OptimalInaccurate,
        QpStatus::PrimalInfeasible,
        QpStatus::DualInfeasible,
        QpStatus::IterationLimit,
        QpStatus::TimeLimit,
        QpStatus::NumericalFailure,
    ];

    /// gh #535: the statuses that mean "the convex solve produced no
    /// certificate" are what hands an LP to the NLP path. `OptimalInaccurate`
    /// is the NETLIB `gen`/`gen1` exit (199 of 200 iterations, primal residual
    /// 1.4e-7 against `tol = 1e-8`); `IterationLimit` is the same stall when
    /// the reduced-accuracy band is missed too; `NumericalFailure` (gh #724)
    /// is the post-solve verification refusing the point outright, which is a
    /// stronger statement of the same thing and not a weaker one.
    #[test]
    fn an_uncertified_lp_is_handed_to_the_nlp_path() {
        for status in [
            QpStatus::OptimalInaccurate,
            QpStatus::IterationLimit,
            QpStatus::NumericalFailure,
        ] {
            assert!(
                lp_declines_to_nlp(ProblemClass::Lp, status, true),
                "{status:?} on an LP must reroute"
            );
        }
    }

    /// A certified result is the answer — there is nothing for a second solve
    /// to improve, and running one would double the cost of every LP.
    #[test]
    fn a_certified_lp_is_never_rerouted() {
        assert!(!lp_declines_to_nlp(
            ProblemClass::Lp,
            QpStatus::Optimal,
            true
        ));
    }

    /// `PrimalInfeasible` / `DualInfeasible` are verdicts the convex solver
    /// *verified*. Rerouting them would let a second solve overwrite a proof
    /// with a numerical opinion — the same reason `run_convex_socp` reroutes
    /// only `NumericalFailure` and not these.
    #[test]
    fn verified_verdicts_stand() {
        for status in [QpStatus::PrimalInfeasible, QpStatus::DualInfeasible] {
            assert!(
                !lp_declines_to_nlp(ProblemClass::Lp, status, true),
                "{status:?} must not reroute"
            );
        }
    }

    /// gh #724: the LP gate and the SOCP gate must agree about what an
    /// uncertified convex result means. `run_convex_socp` reroutes exactly
    /// `NumericalFailure`; if the LP gate excludes it, the same failure to
    /// verify is a fallback on one path and a final `InternalError` on the
    /// other. This is the assertion that was inverted before gh #724, so it is
    /// stated as the invariant rather than as one more status in a list.
    #[test]
    fn an_unverified_convex_result_reroutes_on_the_lp_path_as_it_does_on_the_conic_one() {
        assert!(
            lp_declines_to_nlp(ProblemClass::Lp, QpStatus::NumericalFailure, true),
            "NumericalFailure is what the conic path reroutes on; the LP path \
             must not report it as the last word"
        );
    }

    /// A wall-clock budget is a budget, exactly as `max_iter` is: `TimeLimit`
    /// is the answer to the question the user asked. Rerouting it would launch
    /// a *second*, unbudgeted solve on a problem whose whole point was to stop
    /// — the fallback would double the time limit it was told to respect.
    #[test]
    fn a_spent_time_budget_is_not_a_reason_to_solve_again() {
        assert!(!lp_declines_to_nlp(
            ProblemClass::Lp,
            QpStatus::TimeLimit,
            true
        ));
    }

    /// gh #535 scoped the fallback to `P = 0` because a convex QP that stalls
    /// was "a different and unmeasured population". It has been measured
    /// since: `scaled_feasible_a` is a convex QP with 20 orders of Jacobian
    /// spread on which the convex arm needs 3596 iterations and the NLP arm
    /// 22, and the convex arm emits the gh #293 scaling warning on it before
    /// returning `IterationLimit`. So `ConvexQp` reroutes too.
    ///
    /// `ConvexQcqp` deliberately does NOT: the conic arm has its own failure
    /// modes and no measurement behind it, which is the same reason `Lp` was
    /// alone to begin with. Widen it when there is a fixture that says so.
    #[test]
    fn only_the_convex_qp_classes_reroute() {
        assert!(lp_declines_to_nlp(
            ProblemClass::ConvexQp,
            QpStatus::IterationLimit,
            true
        ));
        for class in [
            ProblemClass::ConvexQcqp,
            ProblemClass::NonconvexQp,
            ProblemClass::Nlp,
        ] {
            for status in ALL_STATUSES {
                assert!(
                    !lp_declines_to_nlp(class, status, true),
                    "{class:?}/{status:?} must not reroute"
                );
            }
        }
    }

    /// The caller's gate wins outright: an explicitly named engine, a user-set
    /// `max_iter` (including the `max_iter=0` zero-iteration contract,
    /// pounce#186) or an attached debugger clears it, and then nothing
    /// reroutes.
    #[test]
    fn the_callers_gate_suppresses_every_case() {
        for class in [ProblemClass::Lp, ProblemClass::ConvexQp] {
            for status in ALL_STATUSES {
                assert!(
                    !lp_declines_to_nlp(class, status, false),
                    "{class:?}/{status:?} must not reroute when the caller declines"
                );
            }
        }
    }
}

#[cfg(test)]
mod nlp_exit_code_tests {
    //! Code review L27: the module doc claimed exit 0 only on `Solve_Succeeded`,
    //! but the NLP path also (correctly) exits 0 on `SolvedToAcceptableLevel`.
    //! The doc was corrected; these tests lock the actual behavior so the doc
    //! and code can't drift again.
    use super::nlp_solve_succeeded;
    use super::status_to_solve_result_num;
    use pounce_nlp::return_codes::ApplicationReturnStatus as A;

    #[test]
    fn acceptable_level_counts_as_success() {
        // The crux of L27: reduced-accuracy convergence is a success.
        assert!(nlp_solve_succeeded(A::SolvedToAcceptableLevel));
        assert!(nlp_solve_succeeded(A::SolveSucceeded));
    }

    /// gh #815. A square problem solved to feasibility is a success on this
    /// channel too, and the failure mode this pins is a *disagreement*: the
    /// same process writes a `.sol` whose `solve_result_num` is Ipopt's `2`,
    /// in the solved band, so exiting 1 would have the two channels of one
    /// run contradict each other.
    #[test]
    fn a_square_problem_feasible_point_counts_as_success() {
        assert!(nlp_solve_succeeded(A::FeasiblePointFound));
    }

    /// The invariant behind the test above, over the whole enum: this
    /// binary's exit code and the `.sol` it writes must never disagree
    /// about whether the solve was a success. Stated as an `iff` so it
    /// catches a future status added to one channel and not the other, in
    /// either direction — gh #815 was this predicate failing on
    /// `FeasiblePointFound`, and gh #591 was the same shape one status
    /// over.
    #[test]
    fn the_exit_code_and_the_sol_band_never_disagree() {
        for s in ALL_STATUSES {
            let code = status_to_solve_result_num(s);
            let solved_band = (0..=99).contains(&code);
            assert_eq!(
                nlp_solve_succeeded(s),
                solved_band,
                "{s:?}: exit-code success is {} but solve_result_num {code} \
                 puts the `.sol` {} the solved band",
                nlp_solve_succeeded(s),
                if solved_band { "inside" } else { "outside" },
            );
        }
    }

    /// Spelled out rather than imported: `pounce_nlp`'s copy lives in its
    /// own `#[cfg(test)]` module. `return_codes.rs` is the source of truth
    /// for membership, and the `_ =>` arm in `status_to_solve_result_num`
    /// does not exist, so a new variant fails that match first.
    const ALL_STATUSES: [A; 20] = [
        A::SolveSucceeded,
        A::SolvedToAcceptableLevel,
        A::InfeasibleProblemDetected,
        A::SearchDirectionBecomesTooSmall,
        A::DivergingIterates,
        A::UserRequestedStop,
        A::FeasiblePointFound,
        A::MaximumIterationsExceeded,
        A::RestorationFailed,
        A::ErrorInStepComputation,
        A::MaximumCpuTimeExceeded,
        A::MaximumWallTimeExceeded,
        A::NotEnoughDegreesOfFreedom,
        A::InvalidProblemDefinition,
        A::InvalidOption,
        A::InvalidNumberDetected,
        A::UnrecoverableException,
        A::NonIpoptExceptionThrown,
        A::InsufficientMemory,
        A::InternalError,
    ];

    #[test]
    fn non_convergent_statuses_are_not_success() {
        for s in [
            A::InfeasibleProblemDetected,
            A::MaximumIterationsExceeded,
            A::RestorationFailed,
            A::DivergingIterates,
            A::MaximumCpuTimeExceeded,
            A::InternalError,
        ] {
            assert!(
                !nlp_solve_succeeded(s),
                "{s:?} must not count as a successful solve"
            );
        }
    }
}