pounce-cli 0.10.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
//! `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;
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::SolveStatistics;
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 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),
        ),
    }
}

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();

    // ---- Convex LP/QP interior-point knobs (pounce-convex `QpOptions`) ----
    // These only affect the `solver_selection` paths that route to
    // pounce-convex (`lp-ipm` / `qp-ipm` / `auto` on an LP / convex QP, and
    // the SOCP IPM). Each forwards only when the user *explicitly* sets it
    // (see the convex dispatch below); otherwise the driver keeps its own
    // tuned default. The standard `tol` and `max_iter` options feed the
    // convex solve too — these `qp_*` knobs cover the rest of `QpOptions`.
    let convex_knobs: Result<(), pounce_common::SolverException> = (|| {
        let r = app.registered_options();
        // τ ∈ (0,1): fraction-to-boundary step damping (Mehrotra σ is adaptive).
        r.add_bounded_number_option(
            "qp_tau",
            "Convex IPM fraction-to-boundary parameter τ ∈ (0,1).",
            0.0,
            true,
            1.0,
            true,
            0.95,
            "Convex LP/QP interior-point only. Caps each Newton step at a \
             fraction τ of the distance to the cone boundary; nearer 1 is more \
             aggressive. The floor of the adaptive rule capped by qp_tau_max, \
             and the flat value on the predictor step and on second-order / \
             PSD cone blocks. Default 0.95.",
        )?;
        // Ceiling of the adaptive (Mehrotra-tail) τ on orthant blocks.
        r.add_bounded_number_option(
            "qp_tau_max",
            "Convex IPM adaptive fraction-to-boundary ceiling τ_max ∈ (0,1).",
            0.0,
            true,
            1.0,
            true,
            1.0 - 1e-12,
            "Convex LP/QP interior-point only. As the solve converges, the \
             corrector's τ on nonnegative-orthant blocks follows the Mehrotra \
             tail τ = clamp(1 − μ, qp_tau, qp_tau_max), so a near-optimal \
             iterate can take a near-full Newton step — worth 35–60% of the \
             iterations when warm starting a sequence of nearby QPs. Set equal \
             to qp_tau to pin τ flat (the most conservative setting). Default \
             1 − 1e-12.",
        )?;
        // Static KKT regularization δ ≥ 0.
        r.add_lower_bounded_number_option(
            "qp_reg",
            "Convex IPM static KKT regularization δ ≥ 0.",
            0.0,
            false,
            1e-10,
            "Convex LP/QP interior-point only. Added on the (block) diagonal to \
             keep the reduced KKT quasi-definite for a stable LDLᵀ inertia. Too \
             large freezes the primal residual on badly-scaled LPs; the default \
             1e-10 is centered in the band that converges the LP/QP suites.",
        )?;
        // Certificate value / cone-membership tolerance > 0.
        r.add_lower_bounded_number_option(
            "qp_infeas_tol",
            "Convex IPM infeasibility-certificate value tolerance > 0.",
            0.0,
            true,
            1e-7,
            "Convex LP/QP interior-point only. Relative tolerance on the value \
             and cone-membership parts of an infeasibility / unboundedness \
             certificate. The certificate's defining-equation residual is held \
             to a far tighter internal tolerance; this only governs when a \
             status is backed by a verified proof. Default 1e-7.",
        )?;
        r.add_string_option(
            "qp_hsde",
            "Use the homogeneous self-dual embedding for the convex IPM.",
            "yes",
            &[
                ("yes", "Self-dual embedding: self-starting, native certificates, robust on ill-conditioned data."),
                ("no", "Infeasible-start primal–dual method (the warm-start / build-once substrate)."),
            ],
            "Convex LP/QP interior-point only. HSDE (default) self-starts and \
             produces infeasibility / unboundedness certificates natively; it \
             is also the substrate for non-symmetric cones. Default yes.",
        )?;
        r.add_string_option(
            "qp_equilibrate",
            "Ruiz-equilibrate the data before the direct convex IPM solve.",
            "yes",
            &[
                (
                    "yes",
                    "Apply Ruiz row/column scaling before solving (direct, non-HSDE path).",
                ),
                ("no", "Solve the raw data without equilibration."),
            ],
            "Convex LP/QP interior-point only, and only when `qp_hsde=no` (the \
             direct infeasible-start path): a conditioning aid for the raw KKT \
             factorization. HSDE conditions internally and ignores this. \
             Default yes.",
        )?;
        r.add_string_option(
            "qp_crossover",
            "Run LP crossover to purify the IPM iterate to an exact vertex.",
            "no",
            &[
                ("yes", "After the IPM, pivot the interior iterate to an exact optimal vertex (active-set purification)."),
                ("no", "Return the interior-point iterate directly (default)."),
            ],
            "Convex LP path only (pure LP, P=0); a no-op for genuine QPs. \
             Correct (never-regress) but currently slow on the degenerate / \
             large NETLIB LPs it targets and does not yet reach an exact \
             `Optimal` vertex on the GEN family (issue #133), so it is off by \
             default and offered as an opt-in for small, well-behaved LPs that \
             want exact-vertex refinement. Default no.",
        )?;
        Ok(())
    })();
    if let Err(e) = convex_knobs {
        eprintln!("pounce: failed to register convex LP/QP options: {e}");
        return ExitCode::from(2);
    }

    // NOTE: 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).

    // 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());
    // 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();
        Box::new(move || default_backend_factory(feral_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() {
        eprintln!("{msg}");
        return ExitCode::from(2);
    }
    for warning in app.unexploited_hint_warnings() {
        eprintln!("{warning}");
    }

    // 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;
    // `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)));
                    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 wants_sens = nl_suffixes
        .as_ref()
        .map(sens::is_sensitivity_input)
        .unwrap_or(false);
    let wants_nlp_postopt = wants_sens || args.compute_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#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, args.compute_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.
        let decline_convex_for_postopt =
            wants_nlp_postopt && matches!(selection, SolverSelection::Auto);

        // 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#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_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 {
            let described = if decline_convex {
                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);
            // 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 {
                    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#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)
                });
                // Build the convex IPM options from the registered CLI knobs.
                // Each tunable forwards only when the user *explicitly* set it
                // (the `true` flag from `get_*_value`); otherwise the convex
                // driver keeps its own tuned `QpOptions` default. `max_iter` in
                // particular must not be silently raised to the (far larger)
                // Ipopt default, so it too is forwarded only when set.
                let convex_opts = convex_cli_opts(&app);
                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,
                        socp_nlp_fallback,
                    ) {
                        return code;
                    }
                } else {
                    // Resolve the convex-path presolve switch (#139). See
                    // `resolve_convex_presolve` for the aliasing rationale.
                    let opts = app.options();
                    let presolve_on = resolve_convex_presolve(
                        opts.get_string_value("qp_presolve", "").ok(),
                        opts.get_string_value("presolve", "").ok(),
                    );
                    // 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. These knobs
                    // named the QP subproblem *of the SQP outer loop*, which this
                    // path no longer goes through, so every one of them silently
                    // became a no-op when the dispatch moved to the convex driver.
                    // The names are kept because they are the documented, in-use
                    // spelling; only the delivery route changed.
                    let engine_overrides = active_set_overrides(&app);
                    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(),
                        presolve_on,
                        json_cfg,
                        debug_hook.as_ref(),
                        args.ampl,
                        convex_opts,
                        matches!(choice, SolverChoice::QpActiveSet),
                        engine_overrides,
                        lp_nlp_fallback,
                    ) {
                        return code;
                    }
                }
            }
            // 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.
    let sens_active = nl_suffixes
        .as_ref()
        .map(sens::is_sensitivity_input)
        .unwrap_or(false);

    // 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 || args.compute_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 = args.compute_red_hessian;
        let rh_eigen = args.rh_eigendecomp;
        let boundcheck_eps = args.sens_boundcheck.then_some(args.sens_bound_eps);
        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,
                    ) {
                        *sens_cap.borrow_mut() = Some(xp);
                    }
                }
                if compute_rh {
                    match sens::try_compute_red_hessian(
                        data,
                        cq,
                        nlp,
                        Rc::clone(&pd),
                        suffixes,
                        rh_eigen,
                    ) {
                        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 || args.compute_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);

    // 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);
    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();

    // Local-infeasibility second-opinion ladder. A local-infeasibility verdict
    // is a *local* statement about a nonconvex problem — the IPM found a
    // stationary point of the constraint violation, not a proof that none of
    // the feasible set is reachable. Before shipping that verdict, re-solve
    // along a genuinely different trajectory and promote only if the re-solve
    // actually converges. Two rungs, in order, each varying exactly one knob
    // from the baseline options:
    //
    //  1. `feral_scaling=mc64` — *numerical* diversity
    //     (`feral_infeasibility_scaling_retry`, on by default). Some KKT
    //     trajectories are chaotic: under two equally backward-stable
    //     linear-solver scalings the iterates stay bit-identical for many
    //     iterations, then diverge by ~1 ULP and fall into different basins —
    //     one optimal, the other a spurious stationary point of the constraint
    //     violation (discs.nl: InfNorm → infeasible, MC64/Identity/MA57/IPOPT →
    //     optimal). Sensitive dependence, not a bad solve, so the a-priori
    //     scaling router can't tell the two apart and no per-factor residual
    //     flags it; the only reliable signal is the whole-solve verdict.
    //
    //  2. `mu_strategy=adaptive` — *algorithmic* diversity
    //     (`infeasibility_mu_strategy_retry`, on by default). Rung 1 perturbs
    //     only the linear algebra, so it is evidence *only* when the trajectory
    //     is ULP-hypersensitive. When it isn't, MC64 retraces the same iterates
    //     and agrees for the same reason the first solve was wrong — on gh #524
    //     (`cresc4`, 6 vars / 8 constraints, feasible, Ipopt solves it in 71
    //     iterations) the MC64 re-solve reproduced the original trajectory
    //     bit-identically and "corroborated" the false verdict. A different
    //     barrier strategy changes the iterate sequence itself, which is what
    //     the monotone-µ default gets wrong here: adaptive µ walks to the known
    //     optimum. This is also the remedy IPOPT's own documentation gives a
    //     user who gets an infeasibility verdict on a problem they believe is
    //     feasible; running it automatically just spares them the round trip.
    //
    // Rungs are *not* cumulative — rung 2 restores the baseline scaling first.
    // On gh #524's `cresc4`, `mu_strategy=adaptive` alone solves the problem and
    // `mu_strategy=adaptive` + `feral_scaling=mc64` does not, so stacking the
    // knobs would have thrown the fix away.
    let scaling_retry_enabled = app
        .options()
        .get_bool_value("feral_infeasibility_scaling_retry", "")
        .map(|(v, _found)| v)
        .unwrap_or(true);
    let mu_retry_enabled = app
        .options()
        .get_bool_value("infeasibility_mu_strategy_retry", "")
        .map(|(v, _found)| v)
        .unwrap_or(true);
    let already_mc64 = matches!(
        pounce_algorithm::application::feral_config_from_options(app.options()).scaling,
        pounce_feral::ScalingStrategy::Mc64Symmetric
    );
    // The tag the barrier rung must restore. Read the *resolved* strategy, not
    // the option string: `feral_scaling` is applied only when set explicitly,
    // and otherwise `FeralConfig::from_env()` governs via `POUNCE_FERAL_SCALING`
    // — so the option string reads "auto" for an env-configured run, and
    // writing that back would silently override the environment on the retry
    // instead of restoring it. `External` is unreachable from the string option;
    // if it ever arrives here there is no tag to write, so the barrier rung is
    // dropped rather than guessed at.
    let baseline_scaling =
        match pounce_algorithm::application::feral_config_from_options(app.options()).scaling {
            pounce_feral::ScalingStrategy::Auto => Some("auto"),
            pounce_feral::ScalingStrategy::InfNorm => Some("infnorm"),
            pounce_feral::ScalingStrategy::Mc64Symmetric => Some("mc64"),
            pounce_feral::ScalingStrategy::Identity => Some("identity"),
            pounce_feral::ScalingStrategy::External(_) => None,
        };
    let already_adaptive = app
        .options()
        .get_string_value("mu_strategy", "")
        .map(|(v, _found)| v == "adaptive")
        .unwrap_or(false);
    // A presolve-*certified* infeasibility is exempt. This 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 neither knob can affect.
    let presolve_certified = presolve_handle
        .as_ref()
        .and_then(|p| p.borrow().certified_infeasible());
    let rungs = second_opinion_rungs(SecondOpinionAvailability {
        scaling_retry_enabled,
        mu_retry_enabled,
        already_mc64,
        already_adaptive,
        baseline_scaling,
    });
    if !rungs.is_empty()
        && debug_hook.is_none()
        && presolve_certified.is_none()
        && status == ApplicationReturnStatus::InfeasibleProblemDetected
    {
        eprintln!(
            "pounce: local infeasibility — re-solving along {} different trajector{} before \
             believing it (second-opinion ladder: {}).",
            rungs.len(),
            if rungs.len() == 1 { "y" } else { "ies" },
            rungs.iter().map(|r| r.label).collect::<Vec<_>>().join(", "),
        );
        let mut retry_status = status;
        let mut retry_stats = solve_stats.clone();
        let mut tried: Vec<&'static str> = Vec::new();
        for rung in &rungs {
            eprintln!("pounce: second opinion — re-solving with {}", rung.label);
            // Apply this rung's option assignments. The main IPM rereads its
            // options fresh each solve, but the restoration sub-IPM uses the
            // provider snapshotted above at the *original* options — so rebuild
            // it too, or the restoration leg would stay on the failing settings.
            for assignment in &rung.assignments {
                let _ = app.options_mut().read_from_str(assignment, true);
            }
            let feral_cfg = pounce_algorithm::application::feral_config_from_options(app.options());
            let bff_mint = move || -> InnerBackendFactoryFactory {
                let feral_cfg = feral_cfg.clone();
                Box::new(move || default_backend_factory(feral_cfg.clone()))
            };
            let resto_provider = make_default_restoration_factory_provider(
                RestoAlgorithmBuilder::new(),
                app.algorithm_builder_from_options(),
                bff_mint,
            );
            app.set_restoration_factory_provider(resto_provider);

            retry_status = app.optimize_tnlp(Rc::clone(&tnlp));
            retry_stats = app.statistics();
            tried.push(rung.label);
            if scaling_retry_promoted(retry_status) {
                eprintln!(
                    "pounce: {} re-solve recovered the problem — promoting ({retry_status:?}).",
                    rung.label
                );
                break;
            }
            eprintln!(
                "pounce: {} re-solve did not recover ({retry_status:?}).",
                rung.label
            );
        }
        if !scaling_retry_promoted(retry_status) {
            eprintln!(
                "pounce: keeping the original local-infeasibility verdict; it survived {} \
                 independent re-solve(s) ({}).",
                tried.len(),
                tried.join(", "),
            );
        }
        // Keep `status` and `solve_stats` in lockstep: on promotion the retry
        // is authoritative (its verdict + its statistics); otherwise both stay
        // the original local-infeasibility verdict and the original solve's
        // statistics. See `resolve_scaling_retry_outcome` (code review L23).
        (status, solve_stats) =
            resolve_scaling_retry_outcome(retry_status, solve_stats, retry_stats);
        // …and keep the *console* in lockstep with them too (gh #508). Both
        // solves print their own end-of-run summary, which is expected and
        // announced — but when the retry is not promoted the last banner on the
        // terminal is the retry's, while the `.sol`, the summary and the JSON
        // report all carry the original verdict. Two banners disagreeing about
        // one solve misleads a human reading the tail of the log and a machine
        // reading it the same way: `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. Re-emitting the verdict
        // that actually shipped makes the terminal's final word the true one.
        //
        // Gated on `print_level >= 1` to match `Application::emit_end_summary`,
        // which is what printed the two banners this one arbitrates; at
        // `print_level 0` there are none to disagree.
        if !scaling_retry_promoted(retry_status)
            && app
                .options()
                .get_integer_value("print_level", "")
                .map(|(v, _found)| v >= 1)
                .unwrap_or(true)
        {
            println!();
            println!("EXIT: {}", print::status_message(status));
            println!();
            println!(
                "POUNCE {}: {}",
                env!("CARGO_PKG_VERSION"),
                print::status_message(status)
            );
        }
    }

    // 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);
        }
    }

    // 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.
    if let Some(d) = app.variable_scaling() {
        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 args.compute_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);
        }
        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);
        }

        // `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` or the reduced-accuracy `SolvedToAcceptableLevel`,
/// matching Ipopt and the `minimize()` success set (#119).
fn nlp_solve_succeeded(status: ApplicationReturnStatus) -> bool {
    matches!(
        status,
        ApplicationReturnStatus::SolveSucceeded | ApplicationReturnStatus::SolvedToAcceptableLevel
    )
}

/// 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,
    }
}

/// One rung of the local-infeasibility second-opinion ladder: a label for the
/// console plus the option assignments that define this re-solve's trajectory.
///
/// Assignments are applied on top of the *baseline* options, not on top of the
/// previous rung — see `second_opinion_rungs`.
#[derive(Debug, Clone, PartialEq, Eq)]
struct SecondOpinionRung {
    label: &'static str,
    assignments: Vec<String>,
}

/// What the baseline options already provide, so a rung that would be a no-op
/// can be dropped instead of burning a solve to re-derive the same answer.
#[derive(Debug, Clone, Copy)]
struct SecondOpinionAvailability {
    scaling_retry_enabled: bool,
    mu_retry_enabled: bool,
    already_mc64: bool,
    already_adaptive: bool,
    /// `feral_scaling` tag naming the baseline's *resolved* scaling strategy,
    /// which the barrier rung re-asserts so it varies exactly one knob.
    /// `None` when the resolved strategy has no tag to write back
    /// (`ScalingStrategy::External`), which drops the barrier rung rather than
    /// let it run under a scaling the baseline never used.
    baseline_scaling: Option<&'static str>,
}

/// Build the ladder of second-opinion re-solves for a local-infeasibility
/// verdict, in the order they should be tried.
///
/// Rung 1 (`feral_scaling=mc64`) perturbs the linear algebra only. Rung 2
/// (`mu_strategy=adaptive`) perturbs the barrier trajectory, and **restores the
/// baseline scaling first** so it varies exactly one knob from the original
/// solve. That reset is load-bearing, not tidiness: on gh #524's `cresc4`,
/// `mu_strategy=adaptive` recovers the optimum but `mu_strategy=adaptive` with
/// `feral_scaling=mc64` still reports local infeasibility, so a cumulative
/// ladder would have discarded the fix.
fn second_opinion_rungs(avail: SecondOpinionAvailability) -> Vec<SecondOpinionRung> {
    let mut rungs = Vec::new();
    if avail.scaling_retry_enabled && !avail.already_mc64 {
        rungs.push(SecondOpinionRung {
            label: "feral_scaling=mc64",
            assignments: vec!["feral_scaling mc64\n".to_string()],
        });
    }
    if let Some(baseline_scaling) = avail.baseline_scaling
        && avail.mu_retry_enabled
        && !avail.already_adaptive
    {
        rungs.push(SecondOpinionRung {
            label: "mu_strategy=adaptive",
            assignments: vec![
                format!("feral_scaling {baseline_scaling}\n"),
                "mu_strategy adaptive\n".to_string(),
            ],
        });
    }
    rungs
}

/// Did a second-opinion re-solve converge well enough to overturn the original
/// local-infeasibility verdict? Only a clean or acceptable-level solve
/// promotes; everything else (including a second infeasibility verdict) leaves
/// the original verdict standing.
fn scaling_retry_promoted(retry_status: ApplicationReturnStatus) -> bool {
    matches!(
        retry_status,
        ApplicationReturnStatus::SolveSucceeded | ApplicationReturnStatus::SolvedToAcceptableLevel
    )
}

/// Resolve the final `(status, statistics)` after an MC64 hypersensitivity
/// re-solve (code review L23).
///
/// On promotion the retry is the authoritative solve, so its status **and** its
/// statistics are reported together. Otherwise the original local-infeasibility
/// verdict is kept — and so are the *original* solve's statistics, so the
/// summary / JSON report never pair the original verdict with the failed
/// retry's iteration count or objective. The pre-fix code reverted `status` to
/// `InfeasibleProblemDetected` but read `app.statistics()` *after* the retry,
/// leaking the retry solve's stats into a report labeled with the original
/// verdict.
fn resolve_scaling_retry_outcome(
    retry_status: ApplicationReturnStatus,
    original_stats: SolveStatistics,
    retry_stats: SolveStatistics,
) -> (ApplicationReturnStatus, SolveStatistics) {
    if scaling_retry_promoted(retry_status) {
        (retry_status, retry_stats)
    } else {
        (
            ApplicationReturnStatus::InfeasibleProblemDetected,
            original_stats,
        )
    }
}

/// 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** — only the two that mean "no certificate": a
///   reduced-accuracy exit and an exhausted budget. `Optimal` needs no help,
///   and `PrimalInfeasible` / `DualInfeasible` are verdicts the convex solver
///   *verified*, which a second solve must not be allowed to overwrite.
///   `NumericalFailure` is left alone here for the same reason the QP path has
///   always reported it: it is the post-solve verification refusing a point,
///   and the LP corpus has no case of it that the NLP path recovers.
///
/// 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
        && class == pounce_cli::dispatch::ProblemClass::Lp
        && matches!(
            status,
            QpStatus::OptimalInaccurate | QpStatus::IterationLimit
        )
}

/// 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::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 to reduced
/// accuracy, 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.
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, 100)
        }
        QpStatus::PrimalInfeasible => ("Problem is primal infeasible.", false, 200),
        QpStatus::DualInfeasible => ("Problem is unbounded (dual infeasible).", false, 300),
        QpStatus::IterationLimit => ("Maximum iterations 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),
    }
}

/// Read the `sqp_qp_*` option family into inner-engine overrides for the
/// active-set QP driver.
///
/// Only options the user set **explicitly** are forwarded (the `true` flag from
/// the `OptionsList` accessors), so the driver keeps its own tuned defaults
/// otherwise — it deliberately picks a size-scaled `max_iter` and enables Schur
/// updates, and must be able to tell "unset" from "set to the default value".
///
/// These knobs were introduced for the QP subproblem of the active-set *SQP*
/// outer loop. `solver_selection=qp-active-set` used to reach the engine that
/// way, so they applied; it now drives the engine directly through the convex
/// path, and without this they would all be silent no-ops. The `sqp_qp_`
/// spelling is retained because it is the documented, already-in-use name.
fn active_set_overrides(app: &IpoptApplication) -> pounce_convex::ActiveSetOverrides {
    use pounce_qp::AntiCyclingChoice;
    let mut o = pounce_convex::ActiveSetOverrides::default();
    let opt = app.options();
    if let Ok((v, true)) = opt.get_integer_value("sqp_qp_max_iter", "") {
        if v >= 0 {
            o.max_iter = Some(v as u32);
        }
    }
    if let Ok((v, true)) = opt.get_string_value("sqp_qp_anti_cycling", "") {
        o.anti_cycling = match v.as_str() {
            "bland" => Some(AntiCyclingChoice::Bland),
            "expand" => Some(AntiCyclingChoice::Expand),
            "none" => Some(AntiCyclingChoice::None),
            _ => None,
        };
    }
    if let Ok((v, true)) = opt.get_numeric_value("sqp_qp_feas_tol", "") {
        o.feas_tol = Some(v);
    }
    if let Ok((v, true)) = opt.get_numeric_value("sqp_qp_opt_tol", "") {
        o.opt_tol = Some(v);
    }
    if let Ok((v, true)) = opt.get_numeric_value("sqp_qp_elastic_gamma", "") {
        o.elastic_gamma = Some(v);
    }
    if let Ok((v, true)) = opt.get_string_value("sqp_qp_use_schur_updates", "") {
        o.use_schur_updates = Some(v == "yes");
    }
    if let Ok((v, true)) = opt.get_string_value("sqp_qp_use_homotopy", "") {
        o.use_homotopy = Some(v == "yes");
    }
    if let Ok((v, true)) = opt.get_integer_value("sqp_qp_max_schur_updates_before_refactor", "") {
        if v >= 0 {
            o.max_schur_updates_before_refactor = Some(v as u32);
        }
    }
    o
}

/// Build the convex IPM [`pounce_convex::QpOptions`] from the registered CLI
/// knobs.
///
/// Every field is overridden only when the user *explicitly* set the option
/// (the `true` flag returned by the `OptionsList` accessors); otherwise the
/// `QpOptions` default is kept. The standard `tol` / `max_iter` options feed
/// the convex solve alongside the `qp_*` knobs registered in `main`.
/// `max_iter` is forwarded only when set so the convex driver's own (smaller)
/// cap is never silently raised to the much larger Ipopt default.
fn convex_cli_opts(app: &IpoptApplication) -> pounce_convex::QpOptions {
    let mut o = pounce_convex::QpOptions::default();
    let opt = app.options();
    if let Ok((v, true)) = opt.get_integer_value("max_iter", "") {
        // Forward `max_iter=0` too: AMPL/Ipopt semantics make it a
        // "take no iterations" request that must not reach optimality
        // (pounce#186). Only a negative value (invalid) is ignored so the
        // usize cast can't wrap.
        if v >= 0 {
            o.max_iter = v as usize;
        }
    }
    if let Ok((v, true)) = opt.get_numeric_value("tol", "") {
        o.tol = v;
    }
    if let Ok((v, true)) = opt.get_numeric_value("qp_tau", "") {
        o.tau = v;
        // A raised floor lifts the default ceiling with it, so `qp_tau` alone
        // still means "use this τ"; an explicit `qp_tau_max` below wins.
        o.tau_max = o.tau_max.max(v);
    }
    if let Ok((v, true)) = opt.get_numeric_value("qp_tau_max", "") {
        o.tau_max = v;
    }
    if let Ok((v, true)) = opt.get_numeric_value("qp_reg", "") {
        o.reg = v;
    }
    if let Ok((v, true)) = opt.get_numeric_value("qp_infeas_tol", "") {
        o.infeas_tol = v;
    }
    if let Ok((v, true)) = opt.get_string_value("qp_hsde", "") {
        o.use_hsde = v != "no";
    }
    if let Ok((v, true)) = opt.get_string_value("qp_equilibrate", "") {
        o.equilibrate = v != "no";
    }
    if let Ok((v, true)) = opt.get_string_value("qp_crossover", "") {
        o.crossover = v != "no";
    }
    o
}

/// Resolve the convex LP/QP presolve switch (#139).
///
/// The convex driver is gated by the `qp_presolve` option, but `presolve` is
/// the spelling users carry over from the NLP path; on the convex path it used
/// to be silently ignored. Honor whichever the user *explicitly* set, with the
/// more specific `qp_presolve` winning when both are given; when neither is set
/// keep the driver's default (on).
///
/// Each argument is `Some((value, explicitly_set))` as returned by
/// `OptionsList::get_string_value(..).ok()`, or `None` if the lookup failed.
fn resolve_convex_presolve(
    qp_presolve: Option<(String, bool)>,
    presolve: Option<(String, bool)>,
) -> bool {
    match (qp_presolve, presolve) {
        // `qp_presolve` explicitly set → authoritative.
        (Some((v, true)), _) => v != "no",
        // else alias an explicitly-set `presolve` onto this path.
        (_, Some((v, true))) => v != "no",
        // neither set → keep the driver's default (on).
        _ => true,
    }
}

/// 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,
    // 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,
) -> Option<ExitCode> {
    use pounce_convex::active_set::solve_qp_active_set;
    use pounce_convex::presolve::{FixpointExit, PresolveOutcome, presolve};
    use pounce_convex::{QpOptions, QpStatus, solve_qp_ipm, solve_qp_ipm_debug};

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

    // 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())
    };
    let t0 = std::time::Instant::now();
    // 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,
        ..convex_opts
    };
    // 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 let Some(hook) = debug_hook.filter(|_| !use_active_set) {
        // Interactive debug: step the IPM on the extracted QP directly.
        // Presolve is skipped so the debugger's `x`/`s`/`y`/`z` blocks
        // correspond to the user's problem rather than a reduced one.
        //
        // Guarded on `!use_active_set`: the debugger hooks barrier-IPM
        // iterations and has no active-set analogue, so on that engine this
        // arm would quietly solve with a *different solver* than the one the
        // user selected. The caller has already printed the note explaining
        // the debugger does not engage; fall through and solve normally.
        let mut h = hook.borrow_mut();
        solve_qp_ipm_debug(&qp, &qp_opts, &mut *h, backend)
    } else if presolve_on {
        match presolve(&qp) {
            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 = if use_active_set {
                    let mut mk = backend;
                    solve_qp_active_set(&ps.reduced, &qp_opts, &engine_overrides, &mut mk)
                } else {
                    solve_qp_ipm(&ps.reduced, &qp_opts, backend)
                };
                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 => trivial(QpStatus::DualInfeasible),
        }
    } else if use_active_set {
        let mut mk = backend;
        solve_qp_active_set(&qp, &qp_opts, &engine_overrides, &mut mk)
    } else {
        solve_qp_ipm(&qp, &qp_opts, backend)
    };
    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 is also a valid NLP, so it is being re-solved \
             on the general NLP interior-point path, which certifies the \
             degenerate, rank-deficient LPs the interior path stalls on (gh \
             #133). 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 #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);
    // 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(),
    );

    // 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 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 qp_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),
        },
    ];

    // 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.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();
        // 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,
    allow_nlp_fallback: bool,
) -> Option<ExitCode> {
    use pounce_convex::{QpOptions, solve_socp_ipm, solve_socp_ipm_debug};

    let (qp, con_map, obj_nl_const, cones) =
        match pounce_cli::qp_extract::extract_socp_with_map(prob) {
            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,
        ..convex_opts
    };
    let t0 = std::time::Instant::now();
    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).
        pounce_convex::QpSolution {
            status: pounce_convex::QpStatus::IterationLimit,
            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(),
        }
    } else if let Some(hook) = debug_hook {
        let mut h = hook.borrow_mut();
        solve_socp_ipm_debug(&qp, &cones, &qp_opts, &mut *h, backend)
    } else {
        solve_socp_ipm(&qp, &cones, &qp_opts, backend)
    };
    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_SIZE_BUDGET` already uses to route
    // large 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;
    }

    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);
    // 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(),
    );

    // Per-constraint duals, mapped from the cone multipliers back to `.nl`
    // constraint order (best-effort for the quadratic rows; see
    // `recover_socp_duals`).
    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),
        },
    ];

    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.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();
        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.
fn default_backend_factory(feral_cfg: pounce_feral::FeralConfig) -> 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::new())
                    }
                    #[cfg(not(feature = "ma57"))]
                    {
                        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` 100 (the "solved to acceptable/reduced accuracy"
    /// band) 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.
    #[test]
    fn optimal_inaccurate_is_distinct_from_optimal() {
        let (msg, ok, srn) = convex_status_report(QpStatus::OptimalInaccurate);
        assert_eq!(srn, 100, "reduced-accuracy solve must use the 100 band");
        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
        );
    }
}

#[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; 6] = [
        QpStatus::Optimal,
        QpStatus::OptimalInaccurate,
        QpStatus::PrimalInfeasible,
        QpStatus::DualInfeasible,
        QpStatus::IterationLimit,
        QpStatus::NumericalFailure,
    ];

    /// gh #535: the two 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.
    #[test]
    fn an_uncertified_lp_is_handed_to_the_nlp_path() {
        for status in [QpStatus::OptimalInaccurate, QpStatus::IterationLimit] {
            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`. `NumericalFailure` itself is left alone here:
    /// it is the post-solve verification refusing a point, and the LP corpus
    /// has no case of it the NLP path recovers.
    #[test]
    fn verified_verdicts_and_numerical_failure_stand() {
        for status in [
            QpStatus::PrimalInfeasible,
            QpStatus::DualInfeasible,
            QpStatus::NumericalFailure,
        ] {
            assert!(
                !lp_declines_to_nlp(ProblemClass::Lp, status, true),
                "{status:?} must not reroute"
            );
        }
    }

    /// The issue scopes the fallback to `P = 0`. A convex QP that stalls is a
    /// different and unmeasured population, so no status reroutes it — nor
    /// does any class the convex QP driver never sees.
    #[test]
    fn only_the_lp_class_reroutes() {
        for class in [
            ProblemClass::ConvexQp,
            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 scaling_retry_tests {
    use super::{
        SecondOpinionAvailability, resolve_scaling_retry_outcome, scaling_retry_promoted,
        second_opinion_rungs,
    };
    use pounce_nlp::SolveStatistics;
    use pounce_nlp::return_codes::ApplicationReturnStatus;

    fn avail() -> SecondOpinionAvailability {
        SecondOpinionAvailability {
            scaling_retry_enabled: true,
            mu_retry_enabled: true,
            already_mc64: false,
            already_adaptive: false,
            baseline_scaling: Some("auto"),
        }
    }

    /// The default ladder is two rungs, scaling first (it is the cheaper and
    /// longer-standing one), barrier strategy second.
    #[test]
    fn default_ladder_is_scaling_then_barrier_strategy() {
        let rungs = second_opinion_rungs(avail());
        let labels: Vec<_> = rungs.iter().map(|r| r.label).collect();
        assert_eq!(labels, ["feral_scaling=mc64", "mu_strategy=adaptive"]);
    }

    /// gh #524: the rungs are applied to the *baseline*, not stacked. The
    /// barrier rung re-asserts the baseline scaling, because on `cresc4`
    /// `mu_strategy=adaptive` recovers the optimum while `mu_strategy=adaptive`
    /// together with `feral_scaling=mc64` still reports local infeasibility —
    /// a cumulative ladder would throw the fix away.
    #[test]
    fn barrier_rung_restores_the_baseline_scaling() {
        for baseline in ["auto", "infnorm"] {
            let rungs = second_opinion_rungs(SecondOpinionAvailability {
                baseline_scaling: Some(baseline),
                ..avail()
            });
            let barrier = rungs
                .iter()
                .find(|r| r.label == "mu_strategy=adaptive")
                .expect("barrier rung present");
            assert!(
                barrier
                    .assignments
                    .iter()
                    .any(|a| a.trim() == format!("feral_scaling {baseline}")),
                "barrier rung must reset the scaling to the baseline {baseline}, \
                 got {:?}",
                barrier.assignments,
            );
        }
    }

    /// A rung that cannot change anything is dropped rather than burning a
    /// whole solve to re-derive the same answer.
    #[test]
    fn rungs_already_satisfied_at_baseline_are_dropped() {
        let only_barrier = second_opinion_rungs(SecondOpinionAvailability {
            already_mc64: true,
            ..avail()
        });
        assert_eq!(
            only_barrier.iter().map(|r| r.label).collect::<Vec<_>>(),
            ["mu_strategy=adaptive"],
        );

        let only_scaling = second_opinion_rungs(SecondOpinionAvailability {
            already_adaptive: true,
            ..avail()
        });
        assert_eq!(
            only_scaling.iter().map(|r| r.label).collect::<Vec<_>>(),
            ["feral_scaling=mc64"],
        );

        assert!(
            second_opinion_rungs(SecondOpinionAvailability {
                already_mc64: true,
                already_adaptive: true,
                ..avail()
            })
            .is_empty(),
            "nothing left to vary means no ladder at all",
        );
    }

    /// A resolved scaling with no `feral_scaling` tag to write back
    /// (`ScalingStrategy::External`) drops the barrier rung rather than run it
    /// under a scaling the baseline never used. The scaling rung is unaffected
    /// — it does not need to restore anything.
    #[test]
    fn barrier_rung_is_dropped_when_the_baseline_scaling_has_no_tag() {
        let rungs = second_opinion_rungs(SecondOpinionAvailability {
            baseline_scaling: None,
            ..avail()
        });
        assert_eq!(
            rungs.iter().map(|r| r.label).collect::<Vec<_>>(),
            ["feral_scaling=mc64"],
        );
    }

    /// Each rung has its own opt-out, and turning both off restores upstream
    /// IPOPT's behaviour of shipping the first verdict.
    #[test]
    fn each_rung_can_be_disabled_independently() {
        assert_eq!(
            second_opinion_rungs(SecondOpinionAvailability {
                scaling_retry_enabled: false,
                ..avail()
            })
            .iter()
            .map(|r| r.label)
            .collect::<Vec<_>>(),
            ["mu_strategy=adaptive"],
        );
        assert_eq!(
            second_opinion_rungs(SecondOpinionAvailability {
                mu_retry_enabled: false,
                ..avail()
            })
            .iter()
            .map(|r| r.label)
            .collect::<Vec<_>>(),
            ["feral_scaling=mc64"],
        );
        assert!(
            second_opinion_rungs(SecondOpinionAvailability {
                scaling_retry_enabled: false,
                mu_retry_enabled: false,
                ..avail()
            })
            .is_empty(),
        );
    }

    fn stats_with_iters(n: i32) -> SolveStatistics {
        SolveStatistics {
            iteration_count: n,
            final_objective: n as f64,
            ..SolveStatistics::default()
        }
    }

    /// Code review L23: when the MC64 hypersensitivity re-solve does **not**
    /// recover, the verdict reverts to the original local-infeasibility status
    /// — and the reported statistics must revert with it, not leak the failed
    /// retry's iteration count / objective.
    #[test]
    fn failed_retry_keeps_original_status_and_stats() {
        let original = stats_with_iters(7);
        let retry = stats_with_iters(42);
        for retry_status in [
            ApplicationReturnStatus::InfeasibleProblemDetected,
            ApplicationReturnStatus::MaximumIterationsExceeded,
            ApplicationReturnStatus::RestorationFailed,
        ] {
            assert!(!scaling_retry_promoted(retry_status));
            let (status, stats) =
                resolve_scaling_retry_outcome(retry_status, original.clone(), retry.clone());
            assert_eq!(
                status,
                ApplicationReturnStatus::InfeasibleProblemDetected,
                "a non-promoting retry ({retry_status:?}) keeps the original verdict"
            );
            assert_eq!(
                stats.iteration_count, 7,
                "stats must stay the original solve's, not the failed retry's"
            );
            assert_eq!(stats.final_objective, 7.0);
        }
    }

    /// On promotion the retry is authoritative: its status AND its statistics
    /// are reported together.
    #[test]
    fn promoted_retry_adopts_retry_status_and_stats() {
        let original = stats_with_iters(7);
        let retry = stats_with_iters(42);
        for retry_status in [
            ApplicationReturnStatus::SolveSucceeded,
            ApplicationReturnStatus::SolvedToAcceptableLevel,
        ] {
            assert!(scaling_retry_promoted(retry_status));
            let (status, stats) =
                resolve_scaling_retry_outcome(retry_status, original.clone(), retry.clone());
            assert_eq!(status, retry_status, "a promoting retry adopts its verdict");
            assert_eq!(
                stats.iteration_count, 42,
                "promoted: stats must be the retry solve's"
            );
            assert_eq!(stats.final_objective, 42.0);
        }
    }
}

#[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 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));
    }

    #[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"
            );
        }
    }
}

#[cfg(test)]
mod convex_presolve_tests {
    //! #139: the convex LP/QP driver is gated by `qp_presolve`, but `presolve`
    //! (the NLP-path spelling) used to be silently ignored on this path. These
    //! lock the aliasing: `presolve` is honored, `qp_presolve` wins ties, and
    //! only explicit settings count.
    use super::resolve_convex_presolve;

    // Helpers mirroring `OptionsList::get_string_value(..).ok()`:
    //   set(v)   → user explicitly set the option to `v`
    //   unset(v) → option carries its default `v`, not user-set
    fn set(v: &str) -> Option<(String, bool)> {
        Some((v.to_string(), true))
    }
    fn unset(v: &str) -> Option<(String, bool)> {
        Some((v.to_string(), false))
    }

    #[test]
    fn defaults_on_when_nothing_set() {
        assert!(resolve_convex_presolve(None, None));
        assert!(resolve_convex_presolve(unset("yes"), unset("yes")));
    }

    #[test]
    fn explicit_presolve_is_honored() {
        // The crux of #139: a bare `presolve no` must turn it off here.
        assert!(!resolve_convex_presolve(unset("yes"), set("no")));
        assert!(resolve_convex_presolve(unset("yes"), set("yes")));
    }

    #[test]
    fn explicit_qp_presolve_is_honored() {
        assert!(!resolve_convex_presolve(set("no"), None));
        assert!(resolve_convex_presolve(set("yes"), None));
    }

    #[test]
    fn qp_presolve_wins_when_both_explicit() {
        // More specific spelling is authoritative when the two conflict.
        assert!(!resolve_convex_presolve(set("no"), set("yes")));
        assert!(resolve_convex_presolve(set("yes"), set("no")));
    }

    #[test]
    fn explicit_presolve_overrides_unset_qp_presolve() {
        assert!(!resolve_convex_presolve(unset("yes"), set("no")));
    }
}