newt-tui 0.8.0

Newt-Agent TUI surfaces (ratatui): code mode + pilot mode
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
use super::*;
use std::ffi::{OsStr, OsString};
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};

struct EnvVarGuard {
    key: &'static str,
    previous: Option<OsString>,
}

impl EnvVarGuard {
    fn set(key: &'static str, value: impl AsRef<OsStr>) -> Self {
        let guard = Self {
            key,
            previous: std::env::var_os(key),
        };
        // SAFETY: every caller is in the `serial(real_fs)` lane.
        unsafe { std::env::set_var(key, value) };
        guard
    }

    fn remove(key: &'static str) -> Self {
        let guard = Self {
            key,
            previous: std::env::var_os(key),
        };
        // SAFETY: every caller is in the `serial(real_fs)` lane.
        unsafe { std::env::remove_var(key) };
        guard
    }
}

impl Drop for EnvVarGuard {
    fn drop(&mut self) {
        // SAFETY: every caller is in the `serial(real_fs)` lane. Drop
        // restores state even when an assertion panics or `?` returns.
        unsafe {
            match self.previous.as_ref() {
                Some(value) => std::env::set_var(self.key, value),
                None => std::env::remove_var(self.key),
            }
        }
    }
}

/// Mirrors `newt_core::config::layering::expand_tilde` (crate-private to
/// `newt-core`, unreachable from here) so a test can resolve an `api_key_file`
/// reference the same way `resolve_api_key()` does in production. A recorded
/// reference is only ever `~/…`-collapsed relative to `HOME`/`USERPROFILE`
/// (`setup::collapse_home`) — never relative to `NEWT_CONFIG_DIR` — so that is
/// what a test must expand it against too.
fn expand_home_for_test(reference: &str) -> PathBuf {
    if let Some(rest) = reference.strip_prefix("~/") {
        if let Some(home) = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")) {
            return PathBuf::from(home).join(rest);
        }
    }
    PathBuf::from(reference)
}

// D1b-3 (#1913): the scripted console went with the `Console` trait.
// `setup::operator::Script` replaces it — same answers-in-order, same
// recorded output — and it hands out an `Operator` instead of
// implementing a trait, so a test cannot supply a reader of its own.
use super::operator::Script as ScriptedConsole;

/// Read the backend drop-in `<config dir>/backends/<name>.toml` the new
/// writer (#1140) produces beside the config file.
fn read_dropin(config_path: &std::path::Path, name: &str) -> BackendConfig {
    let p = config_path
        .with_file_name("backends")
        .join(format!("{name}.toml"));
    toml::from_str(&std::fs::read_to_string(&p).unwrap()).unwrap()
}

async fn mount_openai_chat(server: &MockServer) {
    Mock::given(method("POST"))
        .and(path("/v1/chat/completions"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "choices": [{"message": {"content": "OK"}}]
        })))
        .mount(server)
        .await;
}

async fn mount_authenticated_openai_chat(server: &MockServer, token: &str) {
    Mock::given(method("POST"))
        .and(path("/v1/chat/completions"))
        .and(wiremock::matchers::header(
            "authorization",
            format!("Bearer {token}").as_str(),
        ))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "choices": [{"message": {"content": "OK"}}]
        })))
        .mount(server)
        .await;
}

async fn mount_ollama_chat(server: &MockServer) {
    Mock::given(method("POST"))
        .and(path("/api/chat"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "message": {"content": "OK"},
            "done": true
        })))
        .mount(server)
        .await;
}

// --- pure helpers -----------------------------------------------------

#[test]
fn normalize_url_bare_host_gets_scheme_and_port() {
    assert_eq!(
        normalize_url("REDACTED-HOST", "http", 11434),
        "http://REDACTED-HOST:11434"
    );
}

#[test]
fn normalize_url_keeps_explicit_port_and_full_url() {
    assert_eq!(
        normalize_url("REDACTED-HOST:8000", "http", 11434),
        "http://REDACTED-HOST:8000"
    );
    assert_eq!(
        normalize_url("https://REDACTED-HOST/", "http", 11434),
        "https://REDACTED-HOST"
    );
}

#[test]
fn build_ollama_config_writes_dropin_pair_no_dgx() {
    // #1140: the wizard's chimera is dead — the result is ONE backend
    // drop-in + a minimal config pointing at it. No [dgx], no inline
    // [[backends]].
    let (cfg, backend) = build_ollama_config(
        Config::default(),
        "default",
        EndpointKind::Ollama,
        "http://127.0.0.1:11434",
        "qwen2.5-coder:7b",
    );
    assert!(cfg.dgx.is_none(), "no legacy [dgx] block ever again");
    assert!(cfg.backends.is_empty(), "the drop-in IS the backend list");
    assert_eq!(cfg.default_backend.as_deref(), Some("default"));
    assert_eq!(backend.endpoint, "http://127.0.0.1:11434");
    assert_eq!(backend.effective_model(), Some("qwen2.5-coder:7b"));
    assert_eq!(backend.kind, Some(BackendKind::Ollama));
    assert_eq!(backend.serving, Some(newt_core::Serving::Multiplexer));
    assert!(
        backend.provenance.is_some(),
        "generated files self-describe"
    );
}

#[test]
fn target_candidates_expand_a_bare_host_and_keep_an_explicit_url_single() {
    let discovery = newt_core::config::Discovery {
        hosts: vec![],
        ollama_ports: vec![11434],
        vllm_ports: vec![8000, 8080],
    };
    assert_eq!(
        candidate_endpoints("dgx1.home.arpa", &discovery).unwrap(),
        vec![
            "http://dgx1.home.arpa:11434",
            "http://dgx1.home.arpa:8000",
            "http://dgx1.home.arpa:8080",
        ]
    );
    assert_eq!(
        candidate_endpoints("http://dgx1.home.arpa:8080/v1", &discovery).unwrap(),
        vec!["http://dgx1.home.arpa:8080"]
    );
}

#[test]
fn target_candidates_deduplicate_ports_and_reject_credentials() {
    let discovery = newt_core::config::Discovery {
        hosts: vec![],
        ollama_ports: vec![8000],
        vllm_ports: vec![8000, 8080, 8080],
    };
    assert_eq!(
        candidate_endpoints("dgx1.home.arpa", &discovery).unwrap(),
        vec!["http://dgx1.home.arpa:8000", "http://dgx1.home.arpa:8080",]
    );
    assert!(
        candidate_endpoints("http://user:secret@dgx1.home.arpa:8000", &discovery)
            .unwrap_err()
            .to_string()
            .contains("credentials")
    );
}

#[test]
fn authenticated_targets_require_an_explicit_secure_transport() {
    assert!(validate_authenticated_target("dgx1.home.arpa:8000").is_err());
    assert!(validate_authenticated_target("http://dgx1.home.arpa:8000").is_err());
    assert!(validate_authenticated_target("https://dgx1.home.arpa:8000").is_ok());
    assert!(validate_authenticated_target("http://127.0.0.1:8000").is_ok());
    assert!(validate_authenticated_target("http://[::1]:8000").is_ok());
}

#[tokio::test]
async fn preset_retry_path_revalidates_transport_before_sending_a_key() {
    let preset = ProviderPreset {
        name: "remote-plaintext".into(),
        base_url: "http://192.0.2.10/v1".into(),
        env_vars: vec!["UNUSED_TEST_KEY".into()],
        ..Default::default()
    };
    let cred = WizardCred {
        api_key_env: None,
        api_key_file: None,
        probe_key: Some(Secret::new("replacement-secret")),
        pending_token: None,
    };
    let console = ScriptedConsole::new(&[]);
    let result = verify_key_with_retries(
        &console.operator(),
        &reqwest::Client::new(),
        &preset,
        Path::new("config.toml"),
        "model",
        cred,
    )
    .await;
    let error = match result {
        Ok(_) => panic!("remote plaintext credential should be rejected"),
        Err(error) => error.to_string(),
    };
    assert!(error.contains("refusing to send a bearer token"), "{error}");
}

#[tokio::test]
async fn tool_free_chat_verification_does_not_pin_chat_completions() {
    let server = MockServer::start().await;
    mount_openai_chat(&server).await;
    let hit = EndpointProbeResult {
        endpoint: server.uri(),
        kind: BackendKind::Openai,
        models: vec!["model".into()],
        serving: newt_core::Serving::Instance,
        engine: None,
        warm: vec![],
    };
    let console = ScriptedConsole::new(&[]);
    let (_, api) = verify_custom_chat_with_retries(
        &console.operator(),
        &reqwest::Client::new(),
        &hit,
        "model",
        None,
    )
    .await
    .unwrap();
    assert_eq!(api, None, "runtime tool-capability probe must choose Chat");
}

#[tokio::test]
async fn setup_never_renders_provider_error_refusal_or_bearer_material() {
    const BEARER_SENTINEL: &str = "setup-secret-must-not-escape";
    const BODY_SENTINEL: &str = "setup-provider-body-must-not-escape";
    let escape = char::from(27);
    let bell = char::from(7);
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/v1/chat/completions"))
        .and(wiremock::matchers::header(
            "authorization",
            format!("Bearer {BEARER_SENTINEL}").as_str(),
        ))
        .respond_with(ResponseTemplate::new(404))
        .expect(1)
        .mount(&server)
        .await;
    Mock::given(method("POST"))
        .and(path("/v1/responses"))
        .and(wiremock::matchers::header(
            "authorization",
            format!("Bearer {BEARER_SENTINEL}").as_str(),
        ))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "status": "completed",
            "error": {"message": format!(
                "{BEARER_SENTINEL} {BODY_SENTINEL} {escape}[31mred{bell}"
            )},
            "output": [{
                "type": "message",
                "content": [{
                    "type": "refusal",
                    "refusal": format!("{BODY_SENTINEL} {escape}[2J")
                }]
            }]
        })))
        .expect(1)
        .mount(&server)
        .await;
    let hit = EndpointProbeResult {
        endpoint: server.uri(),
        kind: BackendKind::Openai,
        models: vec!["model".into()],
        serving: newt_core::Serving::Instance,
        engine: None,
        warm: vec![],
    };
    let console = ScriptedConsole::new(&[]);

    let error = verify_custom_chat_with_retries(
        &console.operator(),
        &reqwest::Client::new(),
        &hit,
        "model",
        Some(Secret::new(BEARER_SENTINEL)),
    )
    .await
    .unwrap_err();
    let transcript = console.transcript();
    let rendered_error = error.to_string();

    assert!(transcript.contains("Responses generation payload was unusable"));
    for rendered in [&transcript, &rendered_error] {
        assert!(!rendered.contains(BEARER_SENTINEL));
        assert!(!rendered.contains(BODY_SENTINEL));
        assert!(!rendered.contains(escape));
        assert!(!rendered.contains(bell));
    }
    assert!(console
        .output
        .borrow()
        .iter()
        .all(|line| !line.chars().any(char::is_control)));
    assert!(!rendered_error.chars().any(char::is_control));
}

#[tokio::test]
async fn authentication_retry_does_not_collect_an_untested_final_key() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/v1/chat/completions"))
        .respond_with(ResponseTemplate::new(401))
        .expect(GENERATION_CHECK_ATTEMPTS as u64)
        .mount(&server)
        .await;
    let hit = EndpointProbeResult {
        endpoint: server.uri(),
        kind: BackendKind::Openai,
        models: vec!["model".into()],
        serving: newt_core::Serving::Instance,
        engine: None,
        warm: vec![],
    };
    let console = ScriptedConsole::new(&["first-key", "second-key", "must-remain"]);

    let error = verify_custom_chat_with_retries(
        &console.operator(),
        &reqwest::Client::new(),
        &hit,
        "model",
        None,
    )
    .await
    .unwrap_err();

    assert!(
        error
            .to_string()
            .contains("authentication was rejected 3 times"),
        "{error:#}"
    );
    assert_eq!(
        console.next_answer().as_deref(),
        Some("must-remain"),
        "the final rejection must not prompt for a key setup cannot test"
    );
}

#[tokio::test]
async fn preset_authentication_retry_does_not_collect_an_untested_final_key() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/v1/chat/completions"))
        .respond_with(ResponseTemplate::new(401))
        .expect(GENERATION_CHECK_ATTEMPTS as u64)
        .mount(&server)
        .await;
    let preset = ProviderPreset {
        name: "test-provider".into(),
        base_url: server.uri(),
        env_vars: vec!["UNUSED_TEST_KEY".into()],
        ..Default::default()
    };
    let cred = WizardCred {
        api_key_env: None,
        api_key_file: None,
        probe_key: Some(Secret::new("initial-key")),
        pending_token: None,
    };
    let console =
        ScriptedConsole::new(&["Y", "first-key", "", "Y", "second-key", "", "must-remain"]);

    let result = verify_key_with_retries(
        &console.operator(),
        &reqwest::Client::new(),
        &preset,
        Path::new("/unused/config.toml"),
        "model",
        cred,
    )
    .await;
    let error = match result {
        Ok(_) => panic!("the provider should reject every attempted key"),
        Err(error) => error,
    };

    assert!(
        error
            .to_string()
            .contains("authentication was rejected 3 times"),
        "{error:#}"
    );
    assert_eq!(
        console.next_answer().as_deref(),
        Some("must-remain"),
        "the preset flow must not collect a final untested key"
    );
}

/// Real-resource grounding for a late config-selection failure: once the
/// immutable token/backend tuple is published it remains coherent for
/// lock-free concurrent readers and an idempotent setup retry.
#[ignore = "real-resource: weekly/release tier; touches the filesystem"]
#[serial_test::serial(real_fs)]
#[test]
fn late_setup_write_failure_retains_a_coherent_backend_tuple() {
    let dir = tempfile::tempdir().unwrap();
    let token = dir.path().join("backends/example.token.age");
    let backend_path = dir.path().join("backends/example.toml");
    let config = dir.path().join("config.toml");
    std::fs::create_dir_all(token.parent().unwrap()).unwrap();
    std::fs::write(&token, b"old-token").unwrap();
    std::fs::write(&backend_path, b"old-backend").unwrap();
    std::fs::write(&config, b"old-config").unwrap();

    let versioned_token = dir.path().join("backends/example.token.version.age");
    let versioned_reference = collapse_home(&versioned_token);
    let backend = BackendConfig {
        name: "example".into(),
        endpoint: "https://inference.example.test".into(),
        model: Some("model".into()),
        kind: Some(BackendKind::Openai),
        api_key_file: Some(versioned_reference.clone()),
        ..Default::default()
    };
    let cfg = Config {
        default_backend: Some("example".into()),
        ..Default::default()
    };
    let pending = PendingWizardToken {
        token: Secret::new("new-secret"),
        passphrase: Some(newt_core::secrets::SecretString::from("test-passphrase")),
        path: versioned_token.clone(),
        reference: credentials::SealedSecret::new(&versioned_reference).unwrap(),
    };
    let console = ScriptedConsole::new(&[]);
    let result = persist_interactive_backend_with(
        &console.operator(),
        &config,
        &cfg,
        &backend,
        Some(&pending),
        |staged, destination| destination.durable_replace(staged),
        |_cfg, _path| anyhow::bail!("simulated late config failure"),
    );

    assert!(result.is_err());
    assert_eq!(std::fs::read(&token).unwrap(), b"old-token");
    assert_eq!(std::fs::read(&config).unwrap(), b"old-config");
    let committed: BackendConfig =
        toml::from_str(&std::fs::read_to_string(&backend_path).unwrap()).unwrap();
    assert_eq!(committed.api_key_file, backend.api_key_file);
    assert!(versioned_token.exists());
    assert_eq!(
        newt_core::secrets::resolve_token_file(&versioned_token)
            .unwrap()
            .as_deref(),
        Some("new-secret")
    );
    for directory in [dir.path(), token.parent().unwrap()] {
        let leftovers = std::fs::read_dir(directory)
            .unwrap()
            .filter_map(Result::ok)
            .filter(|entry| entry.file_name().to_string_lossy().contains(".newt-"))
            .collect::<Vec<_>>();
        assert!(leftovers.is_empty(), "staging leftovers: {leftovers:?}");
    }
}

/// Real-filesystem grounding for the backend-publication failpoint: when
/// rename commits but parent sync fails, setup must retain the credential
/// prerequisite referenced by the now-visible backend.
#[ignore = "real-resource: weekly/release tier; touches the filesystem"]
#[serial_test::serial(real_fs)]
#[test]
fn backend_post_commit_sync_failure_retains_its_credential() {
    let dir = tempfile::tempdir().unwrap();
    let backend_dir = dir.path().join("backends");
    std::fs::create_dir_all(&backend_dir).unwrap();
    let config = dir.path().join("config.toml");
    std::fs::write(&config, "default_backend = \"old\"\n").unwrap();
    let versioned_token = backend_dir.join("example.token.version.age");
    let token_reference = collapse_home(&versioned_token);
    let backend = BackendConfig {
        name: "example".into(),
        endpoint: "https://inference.example.test".into(),
        model: Some("model".into()),
        kind: Some(BackendKind::Openai),
        api_key_file: Some(token_reference.clone()),
        ..Default::default()
    };
    let cfg = Config {
        default_backend: Some("example".into()),
        ..Default::default()
    };
    let pending = PendingWizardToken {
        token: Secret::new("new-secret"),
        passphrase: Some(newt_core::secrets::SecretString::from("test-passphrase")),
        path: versioned_token.clone(),
        reference: credentials::SealedSecret::new(&token_reference).unwrap(),
    };

    let error = persist_interactive_backend_with(
        &ScriptedConsole::new(&[]).operator(),
        &config,
        &cfg,
        &backend,
        Some(&pending),
        |staged, destination| {
            std::fs::rename(staged, destination.as_path()).unwrap();
            Err(newt_core::atomic_fs::DurableReplaceError::after_commit(
                destination.as_path(),
                io::Error::other("injected parent sync failure"),
            ))
        },
        |_, _| unreachable!("config selection must not follow publication failure"),
    )
    .unwrap_err();

    assert!(error.to_string().contains("published coherently"));
    assert_eq!(
        std::fs::read_to_string(&config).unwrap(),
        "default_backend = \"old\"\n"
    );
    let committed: BackendConfig =
        toml::from_str(&std::fs::read_to_string(backend_dir.join("example.toml")).unwrap())
            .unwrap();
    assert_eq!(committed.api_key_file, backend.api_key_file);
    assert_eq!(
        newt_core::secrets::resolve_token_file(&versioned_token)
            .unwrap()
            .as_deref(),
        Some("new-secret")
    );
}

/// A process may load the old drop-in before rotation and resolve its key
/// later. Setup therefore never synchronously garbage-collects immutable
/// credential versions when it publishes a replacement.
#[ignore = "real-resource: weekly/release tier; touches the filesystem"]
#[serial_test::serial(real_fs)]
#[test]
fn successful_rotation_retains_the_previous_credential_for_live_readers() {
    let dir = tempfile::tempdir().unwrap();
    let backend_dir = dir.path().join("backends");
    std::fs::create_dir_all(&backend_dir).unwrap();
    let config = dir.path().join("config.toml");
    let backend_path = backend_dir.join("example.toml");
    let old_token = backend_dir.join("example.token.1-1-1.age");
    std::fs::write(&old_token, "old-secret\n").unwrap();
    let old_reader = BackendConfig {
        name: "example".into(),
        endpoint: "https://old.example.test".into(),
        api_key_file: Some(old_token.display().to_string()),
        ..Default::default()
    };
    std::fs::write(&backend_path, toml::to_string(&old_reader).unwrap()).unwrap();
    std::fs::write(&config, "default_backend = \"example\"\n").unwrap();

    let new_token = backend_dir.join("example.token.2-2-2.age");
    let new_reference = new_token.display().to_string();
    let replacement = BackendConfig {
        name: "example".into(),
        endpoint: "https://new.example.test".into(),
        api_key_file: Some(new_reference.clone()),
        ..Default::default()
    };
    let pending = PendingWizardToken {
        token: Secret::new("new-secret"),
        passphrase: Some(newt_core::secrets::SecretString::from("test-passphrase")),
        path: new_token,
        reference: credentials::SealedSecret::new(&new_reference).unwrap(),
    };
    let cfg = Config {
        default_backend: Some("example".into()),
        ..Default::default()
    };
    persist_interactive_backend(
        &ScriptedConsole::new(&[]).operator(),
        &config,
        &cfg,
        &replacement,
        Some(&pending),
    )
    .unwrap();

    assert_eq!(old_reader.resolve_api_key().as_deref(), Some("old-secret"));
    assert!(old_token.exists());
}

/// Real-resource grounding for the shared setup lock: an interactive
/// writer must fail before it stages or commits any file.
#[ignore = "real-resource: weekly/release tier; touches the filesystem"]
#[serial_test::serial(real_fs)]
#[test]
fn interactive_setup_lock_rejects_a_concurrent_writer_before_staging() {
    let dir = tempfile::tempdir().unwrap();
    let config = dir.path().join("config.toml");
    let held = acquire_setup_lock(&config).unwrap();
    let backend = BackendConfig {
        name: "example".into(),
        endpoint: "https://inference.example.test".into(),
        model: Some("model".into()),
        kind: Some(BackendKind::Openai),
        ..Default::default()
    };
    let cfg = Config {
        default_backend: Some("example".into()),
        ..Default::default()
    };
    let console = ScriptedConsole::new(&[]);

    let error = persist_interactive_backend_with(
        &console.operator(),
        &config,
        &cfg,
        &backend,
        None,
        |_, _| unreachable!("lock failure must precede backend publication"),
        |_, _| Ok(()),
    )
    .unwrap_err();

    assert!(error.to_string().contains("another live process"));
    assert!(!config.exists());
    assert!(!dir.path().join("backends").exists());
    drop(held);
}

#[test]
fn detected_backend_name_is_stable_and_filesystem_safe() {
    assert_eq!(
        backend_name("http://dgx1.home.arpa:8000").unwrap(),
        "dgx1-home-arpa-8000"
    );
    assert_eq!(
        backend_name("https://[2001:db8::1]:8080").unwrap(),
        "2001-db8-1-8080"
    );
}

fn openai_hit(endpoint: &str, models: &[&str]) -> newt_core::backend_probe::EndpointProbeResult {
    newt_core::backend_probe::EndpointProbeResult {
        endpoint: endpoint.to_string(),
        kind: BackendKind::Openai,
        models: models.iter().map(|m| (*m).to_string()).collect(),
        serving: newt_core::backend_probe::api_for(BackendKind::Openai).serving(models.len()),
        engine: None,
        warm: Vec::new(),
    }
}

#[test]
fn chat_setup_reuses_a_runtime_responses_writeback_but_not_the_reverse() {
    let probe = openai_hit("https://inference.example.test", &["model"]);
    let mut existing = ExistingSetupBackend {
        name: "example".into(),
        path: PathBuf::from("backends/example.toml"),
        endpoint: Some(probe.endpoint.clone()),
        api_key_env: None,
        api_key_file: None,
        kind: Some(BackendKind::Openai),
        api: Some(OpenAiApi::Responses),
        serving: Some(probe.serving),
        model: Some("model".into()),
        generated_by_setup: false,
        probe_owned: false,
    };

    assert!(existing.matches_probe(&VerifiedTargetHit {
        probe: probe.clone(),
        api: Some(OpenAiApi::ChatCompletions),
    }));
    assert!(existing.matches_probe(&VerifiedTargetHit {
        probe: probe.clone(),
        api: Some(OpenAiApi::Responses),
    }));
    existing.api = Some(OpenAiApi::ChatCompletions);
    assert!(!existing.matches_probe(&VerifiedTargetHit {
        probe,
        api: Some(OpenAiApi::Responses),
    }));
}

#[test]
fn every_injected_commit_failure_leaves_a_coherent_retryable_tuple() {
    #[derive(Clone, Default)]
    struct State {
        new_token_exists: bool,
        backend_token: &'static str,
        selected: bool,
    }

    fn coherent(state: &State) -> bool {
        state.backend_token == "old"
            || (state.backend_token == "versioned" && state.new_token_exists)
    }

    for fail_at in SETUP_COMMIT_STEPS {
        let mut state = State {
            backend_token: "old",
            ..Default::default()
        };
        let result = run_setup_commit(|step| {
            if step == fail_at {
                anyhow::bail!("injected {step:?} failure");
            }
            match step {
                SetupCommitStep::PersistVersionedToken => state.new_token_exists = true,
                SetupCommitStep::PublishBackendTuple => state.backend_token = "versioned",
                SetupCommitStep::SelectBackend => state.selected = true,
            }
            Ok(())
        });
        assert!(result.is_err());
        assert!(
            coherent(&state),
            "failure at {fail_at:?} exposed a mixed tuple"
        );

        // Replaying all idempotent phases models setup recovery after a
        // killed process and must converge on the selected new tuple.
        run_setup_commit(|step| {
            match step {
                SetupCommitStep::PersistVersionedToken => state.new_token_exists = true,
                SetupCommitStep::PublishBackendTuple => state.backend_token = "versioned",
                SetupCommitStep::SelectBackend => state.selected = true,
            }
            Ok(())
        })
        .unwrap();
        assert!(coherent(&state));
        assert!(state.selected);
    }
}

#[test]
fn detected_backend_carries_served_truth_and_secret_references_only() {
    let token_file = std::path::Path::new("~/.newt/tokens/dgx1");
    let backend = backend_from_probe(
        &openai_hit("http://dgx1.home.arpa:8080", &["qwen3-coder", "gpt-oss"]),
        Some("DGX_TOKEN"),
        Some(token_file),
    )
    .unwrap();
    assert_eq!(backend.name, "dgx1-home-arpa-8080");
    assert_eq!(backend.host.as_deref(), Some("dgx1.home.arpa"));
    assert_eq!(backend.effective_model(), Some("qwen3-coder"));
    assert_eq!(backend.serving, Some(newt_core::Serving::Multiplexer));
    assert_eq!(backend.api_key_env.as_deref(), Some("DGX_TOKEN"));
    assert_eq!(backend.api_key_file.as_deref(), Some("~/.newt/tokens/dgx1"));
    let rendered = toml::to_string(&backend).unwrap();
    assert!(!rendered.contains("secret-value"));
}

#[serial_test::serial(real_fs)]
#[test]
fn detected_setup_writes_all_backends_and_preserves_existing_config() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("config.toml");
    std::fs::write(
        &path,
        "# keep this comment\ndefault_backend = \"old\"\n\n[tui]\nno_splash = true\n",
    )
    .unwrap();
    let hits = vec![
        openai_hit("http://dgx1.home.arpa:8000", &["ornith"]),
        openai_hit("http://dgx1.home.arpa:8080", &["qwen3-coder", "gpt-oss"]),
    ];

    let written = persist_detected_setup(&path, &hits, None, None).unwrap();
    assert_eq!(written.len(), 2);
    let text = std::fs::read_to_string(&path).unwrap();
    assert!(text.contains("# keep this comment"));
    assert!(text.contains("[tui]\nno_splash = true"));
    assert_eq!(
        std::fs::read_to_string(path.with_file_name("config.toml.bak")).unwrap(),
        "# keep this comment\ndefault_backend = \"old\"\n\n[tui]\nno_splash = true\n"
    );
    let config = crate::migration_notices::read(|report| Config::load(&path, report)).unwrap();
    assert_eq!(
        config.default_backend.as_deref(),
        Some("dgx1-home-arpa-8000")
    );
    let vllm = read_dropin(&path, "dgx1-home-arpa-8000");
    let router = read_dropin(&path, "dgx1-home-arpa-8080");
    assert_eq!(vllm.serving, Some(newt_core::Serving::Instance));
    assert_eq!(router.serving, Some(newt_core::Serving::Multiplexer));

    let config_before = text;
    let vllm_before = std::fs::read_to_string(&written[0]).unwrap();
    persist_detected_setup(&path, &hits, None, None).unwrap();
    assert_eq!(std::fs::read_to_string(&path).unwrap(), config_before);
    assert_eq!(std::fs::read_to_string(&written[0]).unwrap(), vllm_before);
}

#[serial_test::serial(real_fs)]
#[test]
fn detected_setup_suffixes_a_colliding_name_without_overwriting() {
    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("config.toml");
    let backend_dir = dir.path().join("backends");
    std::fs::create_dir_all(&backend_dir).unwrap();
    let occupied = backend_dir.join("dgx1-home-arpa-8000.toml");
    let hand_authored = concat!(
        "# operator-owned backend\n",
        "name = \"ignored-by-filename\"\n",
        "endpoint = \"http://dgx1-home-arpa:8000\"\n",
        "model = \"hand-model\"\n",
        "tiers = [\"FAST\"]\n",
        "kind = \"openai\"\n",
    );
    std::fs::write(&occupied, hand_authored).unwrap();
    let hits = vec![openai_hit(
        "http://dgx1.home.arpa:8000",
        &["detected-model"],
    )];

    let written = persist_detected_setup(&config_path, &hits, None, None).unwrap();

    assert_eq!(std::fs::read_to_string(&occupied).unwrap(), hand_authored);
    assert_eq!(written.len(), 1);
    assert_eq!(
        written[0].file_name().and_then(|name| name.to_str()),
        Some("dgx1-home-arpa-8000-2.toml")
    );
    assert_eq!(
        crate::migration_notices::read(|report| Config::load(&config_path, report))
            .unwrap()
            .default_backend
            .as_deref(),
        Some("dgx1-home-arpa-8000-2")
    );

    let first_bytes = std::fs::read(&written[0]).unwrap();
    let rerun = persist_detected_setup(&config_path, &hits, None, None).unwrap();
    assert!(rerun.is_empty(), "the collision alias should be reused");
    assert_eq!(std::fs::read(&written[0]).unwrap(), first_bytes);
    assert!(!backend_dir.join("dgx1-home-arpa-8000-3.toml").exists());
}

#[serial_test::serial(real_fs)]
#[test]
fn detected_setup_reuses_a_matching_dropin_byte_for_byte() {
    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("config.toml");
    let backend_dir = dir.path().join("backends");
    std::fs::create_dir_all(&backend_dir).unwrap();
    let existing = backend_dir.join("operator-dgx.toml");
    let hand_authored = concat!(
        "# retain this comment and operator choices\n",
        "name = \"ignored-by-filename\"\n",
        "endpoint = \"http://dgx1.home.arpa:8080/\"\n",
        "model = \"operator-model\"\n",
        "tiers = [\"STANDARD\", \"REVIEW\"]\n",
        "kind = \"openai\"\n",
        "num_ctx = 32768\n",
    );
    std::fs::write(&existing, hand_authored).unwrap();
    let hits = vec![openai_hit(
        "http://dgx1.home.arpa:8080",
        &["detected-model", "operator-model"],
    )];

    let written = persist_detected_setup(&config_path, &hits, None, None).unwrap();

    assert!(written.is_empty());
    assert_eq!(std::fs::read_to_string(&existing).unwrap(), hand_authored);
    assert!(!backend_dir.join("dgx1-home-arpa-8080.toml").exists());
    assert_eq!(
        crate::migration_notices::read(|report| Config::load(&config_path, report))
            .unwrap()
            .default_backend
            .as_deref(),
        Some("operator-dgx")
    );
}

/// Real-resource grounding for setup × runtime-probe ownership: a
/// runtime `probe_v1` overlay at the setup slot's filename is
/// MACHINE-owned cache — it reserves the filename but is never REUSED
/// as the backend definition (pre-#1819 the reuse silently adopted the
/// probe cache as the definition, and the real declaration vanished).
/// A setup re-run writes a real definition under the next name and
/// leaves the probe cache's bytes untouched.
#[ignore = "real-resource: weekly/release tier; touches the filesystem"]
#[serial_test::serial(real_fs)]
#[test]
fn detected_setup_never_reuses_a_runtime_probe_overlay_as_a_definition() {
    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("config.toml");
    let _config_env = EnvVarGuard::set(newt_core::config::NEWT_CONFIG_DIR_ENV, dir.path());
    let verified = vec![VerifiedTargetHit {
        probe: openai_hit("https://inference.example.test", &["model"]),
        api: Some(OpenAiApi::ChatCompletions),
    }];

    persist_verified_setup(&config_path, &verified, None, None).unwrap();
    let backend_dir = dir.path().join("backends");
    let name = backend_name("https://inference.example.test").unwrap();
    let backend_path = backend_dir.join(format!("{name}.toml"));
    // The setup definition exists; replace it with a runtime probe
    // overlay at the same path (delete first: the typed writeback
    // rightly refuses to overwrite an operator-owned file).
    std::fs::remove_file(&backend_path).unwrap();
    let outcome = newt_core::persist_probe_observation(&newt_core::ProbeObservation {
        name,
        endpoint: "https://inference.example.test".into(),
        kind: Some(BackendKind::Openai),
        api: Some(OpenAiApi::Responses),
        serving: newt_core::ProbedServing::Instance {
            model: Some("model".into()),
        },
    })
    .unwrap();
    assert!(matches!(outcome, newt_core::ProbeWriteback::Written(_)));
    let runtime_bytes = std::fs::read(&backend_path).unwrap();

    let written = persist_verified_setup(&config_path, &verified, None, None).unwrap();

    assert_eq!(
        written.len(),
        1,
        "a probe overlay is not a definition — setup writes a real one"
    );
    assert_eq!(
        std::fs::read(&backend_path).unwrap(),
        runtime_bytes,
        "the machine-owned cache's bytes stay untouched"
    );
    assert_eq!(std::fs::read_dir(&backend_dir).unwrap().count(), 2);
}

#[serial_test::serial(real_fs)]
#[test]
fn detected_setup_preserves_but_does_not_select_a_stale_operator_dropin() {
    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("config.toml");
    let backend_dir = dir.path().join("backends");
    std::fs::create_dir_all(&backend_dir).unwrap();
    let existing = backend_dir.join("dgx1-home-arpa-8080.toml");
    let hand_authored = concat!(
        "# preserve even when stale\n",
        "name = \"dgx1-home-arpa-8080\"\n",
        "endpoint = \"http://dgx1.home.arpa:8080\"\n",
        "model = \"retired-model\"\n",
        "tiers = [\"STANDARD\"]\n",
        "kind = \"openai\"\n",
    );
    std::fs::write(&existing, hand_authored).unwrap();
    let hits = vec![openai_hit("http://dgx1.home.arpa:8080", &["current-model"])];

    let written = persist_detected_setup(&config_path, &hits, None, None).unwrap();

    assert_eq!(std::fs::read_to_string(existing).unwrap(), hand_authored);
    assert_eq!(written.len(), 1);
    assert_eq!(
        crate::migration_notices::read(|report| Config::load(&config_path, report))
            .unwrap()
            .default_backend
            .as_deref(),
        Some("dgx1-home-arpa-8080-2")
    );
}

#[serial_test::serial(real_fs)]
#[test]
fn detected_setup_does_not_reuse_a_different_auth_reference() {
    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("config.toml");
    let backend_dir = dir.path().join("backends");
    std::fs::create_dir_all(&backend_dir).unwrap();
    let existing = backend_dir.join("dgx1-home-arpa-8000.toml");
    let body = concat!(
        "name = \"dgx1-home-arpa-8000\"\n",
        "endpoint = \"http://dgx1.home.arpa:8000\"\n",
        "model = \"model\"\n",
        "tiers = [\"FAST\"]\n",
        "kind = \"openai\"\n",
        "serving = \"instance\"\n",
        "api_key_env = \"UNRELATED_TOKEN\"\n",
    );
    std::fs::write(&existing, body).unwrap();
    let hits = vec![openai_hit("http://dgx1.home.arpa:8000", &["model"])];

    let written = persist_detected_setup(&config_path, &hits, None, None).unwrap();

    assert_eq!(std::fs::read_to_string(existing).unwrap(), body);
    assert_eq!(written.len(), 1);
    assert_eq!(
        written[0].file_name().and_then(|name| name.to_str()),
        Some("dgx1-home-arpa-8000-2.toml")
    );
}

#[serial_test::serial(real_fs)]
#[test]
fn detected_setup_does_not_reuse_stale_generated_served_truth() {
    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("config.toml");
    let backend_dir = dir.path().join("backends");
    std::fs::create_dir_all(&backend_dir).unwrap();
    let existing = backend_dir.join("dgx1-home-arpa-8000.toml");
    let body = concat!(
        "name = \"dgx1-home-arpa-8000\"\n",
        "endpoint = \"http://dgx1.home.arpa:8000\"\n",
        "model = \"old-model\"\n",
        "tiers = [\"FAST\"]\n",
        "kind = \"openai\"\n",
        "serving = \"instance\"\n",
        "\n[provenance]\n",
        "source = \"newt setup v0.7.2 (auto-detected Openai)\"\n",
    );
    std::fs::write(&existing, body).unwrap();
    let hits = vec![openai_hit("http://dgx1.home.arpa:8000", &["new-model"])];

    let written = persist_detected_setup(&config_path, &hits, None, None).unwrap();

    assert_eq!(std::fs::read_to_string(existing).unwrap(), body);
    assert_eq!(written.len(), 1);
    assert_eq!(
        read_dropin(&config_path, "dgx1-home-arpa-8000-2")
            .model
            .as_deref(),
        Some("new-model")
    );
}

#[cfg(unix)]
#[serial_test::serial(real_fs)]
#[test]
fn detected_setup_preserves_private_config_permissions() {
    use std::os::unix::fs::PermissionsExt as _;

    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("config.toml");
    std::fs::write(&config_path, "# private config\n").unwrap();
    std::fs::set_permissions(&config_path, std::fs::Permissions::from_mode(0o600)).unwrap();
    let hits = vec![openai_hit("http://dgx1.home.arpa:8000", &["model"])];

    persist_detected_setup(&config_path, &hits, None, None).unwrap();

    assert_eq!(
        std::fs::metadata(&config_path)
            .unwrap()
            .permissions()
            .mode()
            & 0o777,
        0o600
    );
    assert_eq!(
        std::fs::metadata(config_path.with_file_name("config.toml.bak"))
            .unwrap()
            .permissions()
            .mode()
            & 0o777,
        0o600
    );
}

#[cfg(unix)]
#[serial_test::serial(real_fs)]
#[test]
fn detected_setup_updates_a_symlink_target_without_replacing_the_link() {
    use std::os::unix::fs::symlink;

    let dir = tempfile::tempdir().unwrap();
    let real_config = dir.path().join("dotfiles/newt.toml");
    std::fs::create_dir_all(real_config.parent().unwrap()).unwrap();
    std::fs::write(&real_config, "# linked config\n").unwrap();
    let config_path = dir.path().join("config.toml");
    symlink(&real_config, &config_path).unwrap();
    let hits = vec![openai_hit("http://dgx1.home.arpa:8000", &["model"])];

    persist_detected_setup(&config_path, &hits, None, None).unwrap();

    assert!(std::fs::symlink_metadata(&config_path)
        .unwrap()
        .file_type()
        .is_symlink());
    assert!(std::fs::read_to_string(&real_config)
        .unwrap()
        .contains("default_backend"));
}

/// Real-filesystem grounding for the bound setup destination: retargeting
/// the operator's config symlink after staging cannot move the commit away
/// from the file whose lock setup acquired.
#[cfg(unix)]
#[ignore = "real-resource: weekly/release tier; retargets a filesystem symlink"]
#[serial_test::serial(real_fs)]
#[test]
fn setup_symlink_retarget_cannot_escape_the_locked_destination() {
    use std::os::unix::fs::symlink;

    let dir = tempfile::tempdir().unwrap();
    let first = dir.path().join("first/config.toml");
    let second = dir.path().join("second/config.toml");
    std::fs::create_dir_all(first.parent().unwrap()).unwrap();
    std::fs::create_dir_all(second.parent().unwrap()).unwrap();
    std::fs::write(&first, "# first\n").unwrap();
    std::fs::write(&second, "# second\n").unwrap();
    let config = dir.path().join("config.toml");
    symlink(&first, &config).unwrap();
    let backend = BackendConfig {
        name: "example".into(),
        endpoint: "https://inference.example.test".into(),
        model: Some("model".into()),
        kind: Some(BackendKind::Openai),
        ..Default::default()
    };
    let cfg = Config {
        default_backend: Some("example".into()),
        ..Default::default()
    };

    persist_interactive_backend_with(
        &ScriptedConsole::new(&[]).operator(),
        &config,
        &cfg,
        &backend,
        None,
        |staged, destination| destination.durable_replace(staged),
        |staged, destination| {
            std::fs::remove_file(&config)?;
            symlink(&second, &config)?;
            destination
                .durable_replace(staged)
                .map_err(anyhow::Error::from)
        },
    )
    .unwrap();

    assert!(std::fs::read_to_string(&first)
        .unwrap()
        .contains("default_backend"));
    assert_eq!(std::fs::read_to_string(&second).unwrap(), "# second\n");
    assert_eq!(
        std::fs::canonicalize(&config).unwrap(),
        std::fs::canonicalize(&second).unwrap()
    );
}

#[serial_test::serial(real_fs)]
#[test]
fn failed_setup_staging_cleans_earlier_temporary_files() {
    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("config.toml");
    let backend_dir = dir.path().join("backends");
    let blocked_parent = dir.path().join("not-a-directory");
    std::fs::write(&blocked_parent, "occupied").unwrap();
    let planned = vec![
        PlannedSetupBackend {
            name: "first".into(),
            endpoint: "http://first:8000".into(),
            path: backend_dir.join("first.toml"),
            body: Some(b"name = \"first\"\n".to_vec()),
            replace: false,
        },
        PlannedSetupBackend {
            name: "second".into(),
            endpoint: "http://second:8000".into(),
            path: blocked_parent.join("second.toml"),
            body: Some(b"name = \"second\"\n".to_vec()),
            replace: false,
        },
    ];

    let destination = setup_config_destination(&config_path).unwrap();
    assert!(commit_setup_plan(
        &config_path,
        &destination,
        "",
        "default_backend = \"first\"\n",
        &planned,
        &mut Vec::new(),
    )
    .is_err());
    let leftovers = std::fs::read_dir(&backend_dir)
        .into_iter()
        .flatten()
        .filter_map(Result::ok)
        .collect::<Vec<_>>();
    assert!(leftovers.is_empty(), "leftover staged files: {leftovers:?}");
    assert!(!config_path.exists());
}

/// #1667: the backend panel's ADD persists through the SAME setup-lock plan
/// commit as the wizard (#1660) — a fresh drop-in appears, config.toml is
/// never rewritten, a duplicate add is refused, and the lock is released.
#[cfg(feature = "rich-tui")]
#[serial_test::serial(real_fs)]
#[test]
fn panel_backend_add_creates_a_dropin_and_never_touches_config() {
    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("config.toml");
    std::fs::write(&config_path, "# operator config\n").unwrap();
    let edit = crate::backend_panel::BackendEdit {
        name: "dgx1".into(),
        kind: Some(BackendKind::Openai),
        endpoint: "http://dgx1:8000".into(),
        model: Some("gpt-oss-120b".into()),
        api_key_env: Some("DGX_KEY".into()),
        api_key_file: None,
        dirty: crate::backend_panel::DirtyFields::default(),
        replace: false,
    };
    let saved = persist_panel_backend(&config_path, &edit).unwrap();
    let path = saved.path;
    assert!(
        saved.warnings.is_empty(),
        "a clean write warns about nothing"
    );
    assert_eq!(path, dir.path().join("backends/dgx1.toml"));
    let written: BackendConfig = toml::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
    assert_eq!(written.name, "dgx1");
    assert_eq!(written.endpoint, "http://dgx1:8000");
    assert_eq!(written.kind, Some(BackendKind::Openai));
    assert_eq!(written.model.as_deref(), Some("gpt-oss-120b"));
    assert_eq!(written.api_key_env.as_deref(), Some("DGX_KEY"));
    assert_eq!(
        std::fs::read_to_string(&config_path).unwrap(),
        "# operator config\n",
        "the editor never rewrites config.toml"
    );
    // Adding the same name again is refused (no clobber)…
    let error = persist_panel_backend(&config_path, &edit).unwrap_err();
    assert!(error.to_string().contains("already exists"), "{error:#}");
    // …the drop-in list names it for the chooser's editability marker…
    assert_eq!(
        panel_backend_file_names(&config_path),
        vec!["dgx1".to_string()]
    );
    // …and the setup lock was released (a fresh acquire succeeds).
    drop(acquire_setup_lock(&config_path).unwrap());
}

/// #1667: the panel's EDIT overlays ONLY the fields the operator actually
/// changed — wizard/probe-written fields the form does not show (tiers,
/// serving), operator comments, keys `BackendConfig` does not model, and a
/// `kind` the operator never dialed all round-trip untouched
/// (review §1/§6/§8).
#[cfg(feature = "rich-tui")]
#[serial_test::serial(real_fs)]
#[test]
fn panel_backend_edit_overlays_only_dirty_fields_and_preserves_the_rest() {
    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("config.toml");
    let backend_dir = dir.path().join("backends");
    std::fs::create_dir_all(&backend_dir).unwrap();
    std::fs::write(
            backend_dir.join("gpu-runner.toml"),
            "# operator notes for the lab box\n\
             name = \"gpu-runner\"\nendpoint = \"http://gpu-runner:11434\" # LAN\nmodel = \"qwen3:30b\"\n\
             tiers = [\"FAST\"]\nkind = \"anthropic\"\nserving = \"multiplexer\"\n\
             operator_hint = \"keep me\"\n",
        )
        .unwrap();
    // The operator changed ONLY the model — the kind dial was never
    // touched, so `kind = "anthropic"` (outside the form's ladder) must
    // survive verbatim.
    let edit = crate::backend_panel::BackendEdit {
        name: "gpu-runner".into(),
        kind: Some(BackendKind::Anthropic),
        endpoint: "http://gpu-runner:11434".into(),
        model: Some("llama3.1:8b".into()),
        api_key_env: None,
        api_key_file: None,
        dirty: crate::backend_panel::DirtyFields {
            model: true,
            ..crate::backend_panel::DirtyFields::default()
        },
        replace: true,
    };
    let saved = persist_panel_backend(&config_path, &edit).unwrap();
    let body = std::fs::read_to_string(&saved.path).unwrap();
    let written: BackendConfig = toml::from_str(&body).unwrap();
    assert_eq!(
        written.model.as_deref(),
        Some("llama3.1:8b"),
        "the form field applied"
    );
    assert_eq!(
        written.kind,
        Some(BackendKind::Anthropic),
        "an out-of-ladder kind survived an edit that never touched it (§1)"
    );
    assert_eq!(
        written.serving,
        Some(newt_core::Serving::Multiplexer),
        "an unmanaged field survived the edit"
    );
    assert_eq!(
        written.tiers,
        vec![Tier::Fast],
        "an unmanaged field survived the edit"
    );
    assert!(body.contains("# operator notes"), "comment lost: {body}");
    assert!(body.contains("# LAN"), "inline comment lost: {body}");
    assert!(
        body.contains("operator_hint = \"keep me\""),
        "unmodelled key lost: {body}"
    );
    // Clearing an auth field IS written (a dirty None removes the key).
    let clear = crate::backend_panel::BackendEdit {
        api_key_env: None,
        dirty: crate::backend_panel::DirtyFields {
            api_key_env: true,
            ..crate::backend_panel::DirtyFields::default()
        },
        ..edit.clone()
    };
    std::fs::write(
        backend_dir.join("gpu-runner.toml"),
        format!("{body}api_key_env = \"OLD\"\n"),
    )
    .unwrap();
    let saved = persist_panel_backend(&config_path, &clear).unwrap();
    let written: BackendConfig =
        toml::from_str(&std::fs::read_to_string(&saved.path).unwrap()).unwrap();
    assert_eq!(written.api_key_env, None, "the cleared key is gone");
    // Editing a drop-in that vanished is a visible error, not a create.
    let ghost = crate::backend_panel::BackendEdit {
        name: "ghost".into(),
        replace: true,
        ..edit
    };
    assert!(persist_panel_backend(&config_path, &ghost).is_err());
    assert!(!backend_dir.join("ghost.toml").exists());
}

/// #1667: `:d <name>` deletes exactly one drop-in under the setup lock;
/// a missing name and a path-traversal shape are refused visibly.
#[cfg(feature = "rich-tui")]
#[serial_test::serial(real_fs)]
#[test]
fn panel_backend_remove_deletes_the_dropin_under_the_lock() {
    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("config.toml");
    let backend_dir = dir.path().join("backends");
    std::fs::create_dir_all(&backend_dir).unwrap();
    std::fs::write(
        backend_dir.join("old.toml"),
        "name = \"old\"\nendpoint = \"http://old:1\"\n",
    )
    .unwrap();
    assert!(remove_panel_backend(&config_path, "old", None)
        .unwrap()
        .is_empty());
    assert!(!backend_dir.join("old.toml").exists());
    let error = remove_panel_backend(&config_path, "old", None).unwrap_err();
    assert!(
        error.to_string().contains("no backend drop-in"),
        "{error:#}"
    );
    let error = remove_panel_backend(&config_path, "../evil", None).unwrap_err();
    assert!(
        error.to_string().contains("invalid backend name"),
        "{error:#}"
    );
    drop(acquire_setup_lock(&config_path).unwrap());
}

/// #1667 review §2/§7/§11 REGRESSION: removing the backend config.toml's
/// `default_backend` names must never leave a dangling pointer — which
/// `Config::select_backend` reports as a hard `UnknownNamed` error to
/// `newt solve` / the ACP worker (no settings.toml mask exists there). It is
/// refused outright, and accepted only as one transaction that repoints the
/// default at the backend the caller just applied.
#[cfg(feature = "rich-tui")]
#[serial_test::serial(real_fs)]
#[test]
fn panel_backend_remove_never_orphans_the_config_default() {
    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("config.toml");
    let backend_dir = dir.path().join("backends");
    std::fs::create_dir_all(&backend_dir).unwrap();
    // The #1140 wizard shape: the backends live ONLY as drop-ins.
    let original = "# hand-authored\ndefault_backend = \"dgx1\" # keep this note\n";
    std::fs::write(&config_path, original).unwrap();
    for name in ["dgx1", "gpu-runner"] {
        std::fs::write(
            backend_dir.join(format!("{name}.toml")),
            format!("endpoint = \"http://{name}:8000\"\n"),
        )
        .unwrap();
    }

    // Refused without a replacement…
    let error = remove_panel_backend(&config_path, "dgx1", None).unwrap_err();
    assert!(error.to_string().contains("default_backend"), "{error:#}");
    assert!(
        backend_dir.join("dgx1.toml").exists(),
        "a refused remove deletes nothing"
    );
    assert_eq!(std::fs::read_to_string(&config_path).unwrap(), original);
    // …and refused when the replacement is not a real backend.
    let error = remove_panel_backend(&config_path, "dgx1", Some("ghost")).unwrap_err();
    assert!(error.to_string().contains("unknown backend"), "{error:#}");
    assert!(backend_dir.join("dgx1.toml").exists());

    // Accepted as ONE transaction: the pointer moves first, then the file.
    let notes = remove_panel_backend(&config_path, "dgx1", Some("gpu-runner")).unwrap();
    assert!(!backend_dir.join("dgx1.toml").exists());
    let config = std::fs::read_to_string(&config_path).unwrap();
    assert!(
        config.contains("default_backend = \"gpu-runner\""),
        "the durable pointer followed the switch: {config}"
    );
    assert!(
        config.contains("# keep this note") && config.contains("# hand-authored"),
        "the repoint preserved operator content: {config}"
    );
    assert!(
        notes
            .iter()
            .any(|n| n.contains("default_backend now points")),
        "the repoint is reported: {notes:?}"
    );
    // A non-default backend still removes with no config rewrite at all.
    std::fs::write(
        backend_dir.join("spare.toml"),
        "endpoint = \"http://spare:1\"\n",
    )
    .unwrap();
    assert!(remove_panel_backend(&config_path, "spare", None)
        .unwrap()
        .is_empty());
    assert_eq!(std::fs::read_to_string(&config_path).unwrap(), config);
    drop(acquire_setup_lock(&config_path).unwrap());
}

/// #1667 review §10: a post-rename parent-sync failure is a WARNING on a
/// successful write (the bytes are the file), never a "save failed" that
/// would leave the panel reporting a visible edit as lost. A before-commit
/// failure is still a failure.
#[test]
fn an_after_commit_sync_failure_is_a_warning_not_a_failure() {
    let path = Path::new("/tmp/newt-test/backends/dgx1.toml");
    assert_eq!(replace_warning(Ok(())).unwrap(), None);
    let warning = replace_warning(Err(
        newt_core::atomic_fs::DurableReplaceError::after_commit(
            path,
            io::Error::other("injected parent sync failure"),
        ),
    ))
    .unwrap()
    .expect("an after-commit failure is a warning");
    assert!(
        warning.contains("could not durably sync") && warning.contains("dgx1.toml"),
        "{warning}"
    );
}

/// #1667 review §4: the inline `[[backends]]` names are what the panel uses
/// to warn that a same-named drop-in does not fully own its fields.
#[cfg(feature = "rich-tui")]
#[test]
fn inline_backend_names_reads_the_declared_entries() {
    let text = "default_backend = \"dgx1\"\n\
                    [[backends]]\nname = \"dgx1\"\nendpoint = \"http://dgx1:8000\"\n\
                    [[backends]]\nname = \"relic\"\nendpoint = \"http://relic:1\"\n";
    assert_eq!(inline_backend_names_in(text), vec!["dgx1", "relic"]);
    assert_eq!(default_backend_in(text).as_deref(), Some("dgx1"));
    assert!(inline_backend_names_in("# nothing here\n").is_empty());
    assert_eq!(default_backend_in("# nothing here\n"), None);
}

/// Real-filesystem grounding for the detected-setup config failpoint: a
/// post-rename sync failure must not delete drop-ins already selected by
/// the visible replacement config.
#[ignore = "real-resource: weekly/release tier; touches the filesystem"]
#[serial_test::serial(real_fs)]
#[test]
fn detected_config_post_commit_sync_failure_retains_selected_backends() {
    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("config.toml");
    let old_config = "default_backend = \"old\"\n";
    let updated_config = "default_backend = \"example\"\n";
    std::fs::write(&config_path, old_config).unwrap();
    let backend_path = dir.path().join("backends/example.toml");
    let planned = vec![PlannedSetupBackend {
        name: "example".into(),
        endpoint: "https://inference.example.test".into(),
        path: backend_path.clone(),
        body: Some(b"name = \"example\"\nendpoint = \"https://inference.example.test\"\n".to_vec()),
        replace: false,
    }];
    let destination = setup_config_destination(&config_path).unwrap();

    let error = commit_setup_plan_with(
        &config_path,
        &destination,
        old_config,
        updated_config,
        &planned,
        &mut Vec::new(),
        |staged, destination| {
            destination.durable_replace(staged).unwrap();
            Err(newt_core::atomic_fs::DurableReplaceError::after_commit(
                destination.as_path(),
                io::Error::other("injected parent sync failure"),
            ))
        },
    )
    .unwrap_err();

    assert!(error.to_string().contains("could not durably sync"));
    assert_eq!(
        std::fs::read_to_string(&config_path).unwrap(),
        updated_config
    );
    assert_eq!(
        std::fs::read_to_string(config_path.with_file_name("config.toml.bak")).unwrap(),
        old_config
    );
    assert!(backend_path.exists());
    assert!(std::fs::read_to_string(backend_path)
        .unwrap()
        .contains("https://inference.example.test"));
}

#[serial_test::serial(real_fs)]
#[test]
fn setup_lock_blocks_a_second_writer_and_can_be_reacquired() {
    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("config.toml");

    let first = acquire_setup_lock(&config_path).unwrap();
    let error = acquire_setup_lock(&config_path).unwrap_err();
    assert!(error.to_string().contains("another live process"));
    drop(first);

    let reacquired = acquire_setup_lock(&config_path).unwrap();
    drop(reacquired);
    assert!(!dir.path().join("config.toml.lock").exists());
}

/// Per-PR mocked BAT for the regression where a public model catalog was
/// mistaken for authentication success and setup persisted an unusable
/// backend. No real filesystem or credential is involved in this lane.
#[tokio::test]
async fn bat_public_catalog_auth_rejection_never_calls_persistence() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/v1/models"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "data": [{"id": "publicly-listed-model"}]
        })))
        .expect(1)
        .mount(&server)
        .await;
    Mock::given(method("POST"))
        .and(path("/v1/chat/completions"))
        .respond_with(ResponseTemplate::new(401))
        .expect(1)
        .mount(&server)
        .await;
    let persistence_called = std::cell::Cell::new(false);
    let console = ScriptedConsole::new(&[]);

    let error = run_target_with_persist(
        &console.operator(),
        &reqwest::Client::new(),
        Path::new("unused/config.toml"),
        TargetSetupRequest {
            target: &server.uri(),
            token_env: None,
            token_file: None,
            model: None,
            yes: true,
        },
        &Discovery::default(),
        |_, _, _, _| {
            persistence_called.set(true);
            Ok(Vec::new())
        },
    )
    .await
    .unwrap_err();

    assert!(error
        .to_string()
        .contains("no inference backend passed a minimal generation check"));
    assert!(console.transcript().contains("requires authentication"));
    assert!(!persistence_called.get());
}

/// Real-resource grounding for the mocked multi-port target flow;
/// weekly/release only because it writes config files.
#[ignore = "real-resource: weekly/release tier; touches the filesystem"]
#[serial_test::serial(real_fs)]
#[tokio::test]
async fn target_flow_probes_multiple_ports_and_writes_each_live_endpoint() {
    let vllm = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/v1/models"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "data": [{"id": "ornith"}]
        })))
        .mount(&vllm)
        .await;
    mount_openai_chat(&vllm).await;
    let router = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/v1/models"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "data": [{"id": "qwen"}, {"id": "gpt-oss"}]
        })))
        .mount(&router)
        .await;
    mount_openai_chat(&router).await;
    let discovery = newt_core::config::Discovery {
        hosts: vec![],
        ollama_ports: vec![],
        vllm_ports: vec![vllm.address().port(), router.address().port()],
    };
    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("config.toml");
    let client = reqwest::Client::new();
    let console = ScriptedConsole::new(&[]);

    run_target_with(
        &console.operator(),
        &client,
        &config_path,
        TargetSetupRequest {
            target: "127.0.0.1",
            token_env: None,
            token_file: None,
            model: None,
            yes: true,
        },
        &discovery,
    )
    .await
    .unwrap();

    let backend_dir = dir.path().join("backends");
    assert_eq!(
        std::fs::read_dir(&backend_dir).unwrap().count(),
        2,
        "one drop-in per live endpoint"
    );
    let config =
        crate::migration_notices::read(|report| Config::load(&config_path, report)).unwrap();
    assert_eq!(
        config.default_backend.as_deref(),
        Some(format!("127-0-0-1-{}", vllm.address().port()).as_str())
    );
    assert!(console
        .transcript()
        .contains("Detected 2 inference backends"));
}

#[serial_test::serial(real_fs)]
#[tokio::test]
async fn target_flow_reports_auth_failure_alongside_a_successful_probe() {
    let open = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/v1/models"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "data": [{"id": "open-model"}]
        })))
        .mount(&open)
        .await;
    mount_openai_chat(&open).await;
    let secured = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/v1/models"))
        .respond_with(ResponseTemplate::new(401))
        .mount(&secured)
        .await;
    let discovery = newt_core::config::Discovery {
        hosts: vec![],
        ollama_ports: vec![],
        vllm_ports: vec![open.address().port(), secured.address().port()],
    };
    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("config.toml");
    let console = ScriptedConsole::new(&[]);

    run_target_with(
        &console.operator(),
        &reqwest::Client::new(),
        &config_path,
        TargetSetupRequest {
            target: "127.0.0.1",
            token_env: None,
            token_file: None,
            model: None,
            yes: true,
        },
        &discovery,
    )
    .await
    .unwrap();

    let transcript = console.transcript();
    assert!(transcript.contains("Detected 1 inference backend"));
    assert!(transcript.contains("authentication required"));
    assert!(transcript.contains(&secured.address().port().to_string()));
}

#[serial_test::serial(real_fs)]
#[tokio::test]
async fn target_flow_decline_writes_nothing() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/v1/models"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "data": [{"id": "served-model"}]
        })))
        .mount(&server)
        .await;
    mount_openai_chat(&server).await;
    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("config.toml");
    let console = ScriptedConsole::new(&["n"]);

    run_target_with(
        &console.operator(),
        &reqwest::Client::new(),
        &config_path,
        TargetSetupRequest {
            target: &server.uri(),
            token_env: None,
            token_file: None,
            model: None,
            yes: false,
        },
        &newt_core::config::Discovery::default(),
    )
    .await
    .unwrap();

    assert!(console.transcript().contains("Aborted. Nothing written."));
    assert!(!config_path.exists());
    assert!(!dir.path().join("backends").exists());
}

#[serial_test::serial(real_fs)]
#[tokio::test]
async fn target_flow_requires_an_explicit_endpoint_before_sending_a_token() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/v1/models"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "data": [{"id": "secured-model"}]
        })))
        .expect(0)
        .mount(&server)
        .await;
    let discovery = newt_core::config::Discovery {
        hosts: vec![],
        ollama_ports: vec![],
        vllm_ports: vec![server.address().port()],
    };
    let dir = tempfile::tempdir().unwrap();
    let token_path = dir.path().join("token");
    std::fs::write(&token_path, "secret-value\n").unwrap();
    let console = ScriptedConsole::new(&[]);

    let error = run_target_with(
        &console.operator(),
        &reqwest::Client::new(),
        &dir.path().join("config.toml"),
        TargetSetupRequest {
            target: "127.0.0.1",
            token_env: None,
            token_file: Some(&token_path),
            model: None,
            yes: true,
        },
        &discovery,
    )
    .await
    .unwrap_err();

    assert!(error.to_string().contains("explicit URL"));
    assert!(!dir.path().join("config.toml").exists());
}

#[serial_test::serial(real_fs)]
#[tokio::test]
async fn target_flow_uses_token_file_for_probe_without_echoing_it() {
    use wiremock::matchers::header;
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/v1/models"))
        .and(header("authorization", "Bearer secret-value"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "data": [{"id": "secured-model"}]
        })))
        .mount(&server)
        .await;
    mount_authenticated_openai_chat(&server, "secret-value").await;
    let dir = tempfile::tempdir().unwrap();
    let token_path = dir.path().join("token");
    std::fs::write(&token_path, "secret-value\n").unwrap();
    let config_path = dir.path().join("config.toml");
    let client = reqwest::Client::new();
    let console = ScriptedConsole::new(&[]);

    run_target_with(
        &console.operator(),
        &client,
        &config_path,
        TargetSetupRequest {
            target: &server.uri(),
            token_env: None,
            token_file: Some(&token_path),
            model: None,
            yes: true,
        },
        &newt_core::config::Discovery::default(),
    )
    .await
    .unwrap();

    let name = backend_name(&server.uri()).unwrap();
    let backend = read_dropin(&config_path, &name);
    assert_eq!(
        backend.api_key_file.as_deref(),
        std::fs::canonicalize(&token_path).unwrap().to_str(),
        "persist the reference, never the token"
    );
    assert!(!console.transcript().contains("secret-value"));
    assert!(!std::fs::read_to_string(&config_path)
        .unwrap()
        .contains("secret-value"));
}

#[serial_test::serial(real_fs)]
#[tokio::test]
async fn target_flow_failure_is_actionable_and_writes_nothing() {
    let server = MockServer::start().await;
    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("config.toml");
    let client = reqwest::Client::new();
    let console = ScriptedConsole::new(&[]);

    let err = run_target_with(
        &console.operator(),
        &client,
        &config_path,
        TargetSetupRequest {
            target: &server.uri(),
            token_env: None,
            token_file: None,
            model: None,
            yes: true,
        },
        &newt_core::config::Discovery::default(),
    )
    .await
    .unwrap_err();

    assert!(err.to_string().contains("no supported inference API"));
    assert!(!config_path.exists());
    assert!(!dir.path().join("backends").exists());
}

#[serial_test::serial(real_fs)]
#[tokio::test]
async fn target_flow_rejects_an_endpoint_with_no_served_models() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/v1/models"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "data": []
        })))
        .mount(&server)
        .await;
    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("config.toml");
    let client = reqwest::Client::new();
    let console = ScriptedConsole::new(&[]);

    let error = run_target_with(
        &console.operator(),
        &client,
        &config_path,
        TargetSetupRequest {
            target: &server.uri(),
            token_env: None,
            token_file: None,
            model: None,
            yes: true,
        },
        &newt_core::config::Discovery::default(),
    )
    .await
    .unwrap_err();

    assert!(error.to_string().contains("no supported inference API"));
    assert!(console.transcript().contains("listed no models"));
    assert!(!config_path.exists());
    assert!(!dir.path().join("backends").exists());
}

// --- HTTP probes ------------------------------------------------------

#[tokio::test]
async fn fetch_ollama_models_parses_tags() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/tags"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "models": [{"name": "llama3.1:8b"}, {"name": "qwen2.5-coder:7b"}]
        })))
        .mount(&server)
        .await;
    let client = reqwest::Client::new();
    let models = fetch_ollama_models(&client, &server.uri()).await.unwrap();
    assert_eq!(models, vec!["llama3.1:8b", "qwen2.5-coder:7b"]);
}

#[tokio::test]
async fn fetch_openai_models_auth_sends_bearer() {
    // Regression: the session-start adopt probe hit authenticated
    // gateways WITHOUT the backend's bearer token -> 401 -> a spurious
    // "unreachable" banner every launch and no adoption.
    use wiremock::matchers::header;
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/v1/models"))
        .and(header("authorization", "Bearer sekrit"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "data": [{"id": "gated-model"}]
        })))
        .mount(&server)
        .await;
    let client = reqwest::Client::new();
    let models =
        newt_core::backend_probe::fetch_openai_models_auth(&client, &server.uri(), Some("sekrit"))
            .await
            .unwrap();
    assert_eq!(models, vec!["gated-model".to_string()]);
    // Without the token the mock does not match -> error, never a silent [].
    assert!(
        newt_core::backend_probe::fetch_openai_models(&client, &server.uri())
            .await
            .is_err()
    );
}

#[tokio::test]
async fn fetch_openai_models_parses_data() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/v1/models"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "data": [{"id": "meta/llama-3.1-8b-instruct"}]
        })))
        .mount(&server)
        .await;
    let client = reqwest::Client::new();
    let models = newt_core::backend_probe::fetch_openai_models(&client, &server.uri())
        .await
        .unwrap();
    assert_eq!(models, vec!["meta/llama-3.1-8b-instruct"]);
}

#[tokio::test]
async fn fetch_ollama_models_errors_on_500() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/tags"))
        .respond_with(ResponseTemplate::new(500))
        .mount(&server)
        .await;
    let client = reqwest::Client::new();
    assert!(fetch_ollama_models(&client, &server.uri()).await.is_err());
}

// --- full driver flows ------------------------------------------------

#[serial_test::serial(real_fs)]
#[tokio::test]
async fn ollama_flow_writes_config() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/tags"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "models": [{"name": "llama3.1:8b"}, {"name": "qwen2.5-coder:7b"}]
        })))
        .mount(&server)
        .await;
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("config.toml");
    let client = reqwest::Client::new();
    // backend=1 (Ollama), host=<mock>, model=2 (qwen), write=Y
    let console = ScriptedConsole::new(&["1", &server.uri(), "2", "y"]);
    run_with(&console.operator(), &client, &path).await.unwrap();

    let cfg = crate::migration_notices::read(|report| Config::load(&path, report)).unwrap();
    assert!(cfg.dgx.is_none(), "no legacy [dgx] block (#1140)");
    assert_eq!(cfg.default_backend.as_deref(), Some("default"));
    let b = read_dropin(&path, "default");
    assert_eq!(b.effective_model(), Some("qwen2.5-coder:7b"));
    assert_eq!(b.endpoint, server.uri());
}

#[serial_test::serial(real_fs)]
#[tokio::test]
async fn bad_pasted_key_is_caught_by_the_live_test_and_reentered() {
    // Field regression: ollama.com serves the model catalog to anyone, so
    // a mistyped key sailed through setup and 401'd on the first message.
    // The wizard now live-tests the key (1-token chat on the ollama wire)
    // and offers re-entry.
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/tags"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "models": [{"name": "big-cloud-model"}]
        })))
        .mount(&server)
        .await;
    Mock::given(method("POST"))
        .and(path("/api/chat"))
        .and(wiremock::matchers::header(
            "authorization",
            "Bearer good-key",
        ))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "message": {"content": "hi"}, "done": true
        })))
        .mount(&server)
        .await;
    Mock::given(method("POST"))
        .and(path("/api/chat"))
        .respond_with(
            ResponseTemplate::new(401).set_body_json(serde_json::json!({"error": "Unauthorized"})),
        )
        .mount(&server)
        .await;
    let dir = tempfile::tempdir().unwrap();
    let cfg_path = dir.path().join("config.toml");
    // Pin the config dir: the machine identity for blank-passphrase
    // encryption lives under it.
    let _config_env = EnvVarGuard::set(newt_core::config::NEWT_CONFIG_DIR_ENV, dir.path());
    newt_core::secrets::session().reset_for_test();
    let preset = ProviderPreset {
        name: "cloudish".into(),
        base_url: server.uri(),
        api_mode: newt_core::provider_preset::ApiMode::Ollama,
        env_vars: vec!["NEWT_TEST_NO_SUCH_VAR_EXISTS".into()],
        ..Default::default()
    };
    // paste bad key → blank passphrase → model 1 → re-enter? Y →
    // paste good key → blank passphrase.
    let console = ScriptedConsole::new(&["bad-key", "", "1", "Y", "good-key", ""]);
    let result = configure_preset(
        &console.operator(),
        &reqwest::Client::new(),
        &preset,
        &cfg_path,
    )
    .await;
    let (_cfg, backend, _pending) = result.unwrap();
    let t = console.transcript();
    assert!(t.contains("✗ authentication rejected (HTTP 401)"), "{t}");
    assert!(t.contains("✓ generation accepted"), "{t}");
    assert!(backend.api_key_file.is_some(), "re-entered key is stored");
}

#[serial_test::serial(real_fs)]
#[tokio::test]
async fn two_backends_in_one_sitting_with_default_pick() {
    // The multi-backend loop: local ollama, then a custom host, then the
    // default-backend pick — all in one wizard pass.
    let s1 = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/tags"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "models": [{"name": "llama3.1:8b"}]
        })))
        .mount(&s1)
        .await;
    let s2 = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/tags"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "models": [{"name": "qwen3:30b"}]
        })))
        .mount(&s2)
        .await;
    mount_ollama_chat(&s2).await;
    let dir = tempfile::tempdir().unwrap();
    let cfg_path = dir.path().join("config.toml");
    let client = reqwest::Client::new();
    let host2_name = format!("127-0-0-1-{}", s2.address().port());
    // ollama door → write → add another → custom host door → write →
    // stop → pick backend 2 as the default.
    let console = ScriptedConsole::new(&[
        "1",
        &s1.uri(),
        "1",
        "y",
        "y",
        "2",
        &s2.uri(),
        "1",
        "1",
        "y",
        "n",
        "2",
    ]);
    run_with(&console.operator(), &client, &cfg_path)
        .await
        .unwrap();

    assert!(cfg_path
        .with_file_name("backends")
        .join("default.toml")
        .exists());
    assert!(cfg_path
        .with_file_name("backends")
        .join(format!("{host2_name}.toml"))
        .exists());
    let cfg = crate::migration_notices::read(|report| Config::load(&cfg_path, report)).unwrap();
    assert_eq!(
        cfg.default_backend.as_deref(),
        Some(host2_name.as_str()),
        "the end-of-loop pick wins over last-written"
    );
}

#[serial_test::serial(real_fs)]
#[tokio::test]
async fn custom_host_flow_detects_openai_backend() {
    // The custom-host door subsumes the old DGX flavour menu: the probe
    // detects the wire (here: OpenAI-compatible, one model = instance).
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/v1/models"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "data": [{"id": "meta/llama-3.1-8b-instruct"}]
        })))
        .mount(&server)
        .await;
    mount_openai_chat(&server).await;
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("config.toml");
    let client = reqwest::Client::new();
    // custom host=2, host=<mock url>, endpoint=1, model=1, write=Y
    let console = ScriptedConsole::new(&["2", &server.uri(), "1", "1", "y"]);
    run_with(&console.operator(), &client, &path).await.unwrap();

    let name = format!("127-0-0-1-{}", server.address().port());
    let cfg = crate::migration_notices::read(|report| Config::load(&path, report)).unwrap();
    assert_eq!(cfg.default_backend.as_deref(), Some(name.as_str()));
    let b = read_dropin(&path, &name);
    assert_eq!(b.kind, Some(BackendKind::Openai));
    assert_eq!(b.serving, Some(newt_core::Serving::Instance));
    assert_eq!(b.effective_model(), Some("meta/llama-3.1-8b-instruct"));
    assert_eq!(b.endpoint, server.uri());
}

#[serial_test::serial(real_fs)]
#[tokio::test]
async fn custom_host_adopts_the_warm_model_as_the_enter_default() {
    // /api/tags lists install order; /api/ps says what's LOADED. The menu
    // must put the warm model first so a blank Enter adopts it.
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/tags"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "models": [
                {"name": "cold-a:7b"}, {"name": "cold-b:13b"}, {"name": "warm:32b"}
            ]
        })))
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/api/ps"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "models": [{"name": "warm:32b"}]
        })))
        .mount(&server)
        .await;
    mount_ollama_chat(&server).await;
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("config.toml");
    let client = reqwest::Client::new();
    // custom host=2, host, endpoint=1, model=<Enter> (default = warm), write=Y
    let console = ScriptedConsole::new(&["2", &server.uri(), "1", "", "y"]);
    run_with(&console.operator(), &client, &path).await.unwrap();

    let name = format!("127-0-0-1-{}", server.address().port());
    assert_eq!(
        read_dropin(&path, &name).effective_model(),
        Some("warm:32b"),
        "a blank Enter adopts the WARM model, not install order"
    );
    let seen = console.transcript();
    assert!(seen.contains("warm: warm:32b"), "row shows warmth: {seen}");
}

#[serial_test::serial(real_fs)]
#[tokio::test]
async fn manual_model_when_endpoint_unreachable() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("config.toml");
    let client = reqwest::Client::builder()
        .timeout(std::time::Duration::from_millis(200))
        .build()
        .unwrap();
    // Ollama, an unroutable host → probe fails → manual model name → write.
    let console = ScriptedConsole::new(&[
        "1",
        "http://127.0.0.1:1", // connection refused
        "phi3:mini",
        "y",
    ]);
    run_with(&console.operator(), &client, &path).await.unwrap();
    let cfg = crate::migration_notices::read(|report| Config::load(&path, report)).unwrap();
    assert_eq!(cfg.default_backend.as_deref(), Some("default"));
    assert_eq!(
        read_dropin(&path, "default").effective_model(),
        Some("phi3:mini")
    );
}

#[serial_test::serial(real_fs)]
#[tokio::test]
async fn decline_overwrite_keeps_existing() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("config.toml");
    std::fs::write(&path, "# sentinel\n").unwrap();
    let client = reqwest::Client::new();
    // Overwrite? → N (default).
    let console = ScriptedConsole::new(&["n"]);
    run_with(&console.operator(), &client, &path).await.unwrap();
    // Untouched.
    assert_eq!(std::fs::read_to_string(&path).unwrap(), "# sentinel\n");
}

#[serial_test::serial(real_fs)]
#[tokio::test]
async fn decline_final_write_leaves_no_file() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/tags"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "models": [{"name": "llama3.1:8b"}]
        })))
        .mount(&server)
        .await;
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("config.toml");
    let client = reqwest::Client::new();
    // Ollama, host, model=1, write=n → nothing written.
    let console = ScriptedConsole::new(&["1", &server.uri(), "1", "n"]);
    run_with(&console.operator(), &client, &path).await.unwrap();
    assert!(!path.exists());
}

// --- custom-host / preset pure helpers ----------------------------------

#[test]
fn format_endpoint_row_shows_engine_and_warmth() {
    let hit = newt_core::backend_probe::EndpointProbeResult {
        endpoint: "http://gpu-box:8080".into(),
        kind: BackendKind::Openai,
        models: vec!["a".into(), "b".into()],
        serving: newt_core::Serving::Multiplexer,
        engine: Some(newt_core::config::Engine::LlamaCpp),
        warm: vec!["b".into()],
    };
    let row = format_endpoint_row(&hit);
    assert!(row.contains("llama.cpp"), "{row}");
    assert!(row.contains("2 models"), "{row}");
    assert!(row.contains("warm: b"), "{row}");
    // Unknown engine degrades to the wire-kind label; no warmth shown.
    let bare = newt_core::backend_probe::EndpointProbeResult {
        engine: None,
        warm: vec![],
        ..hit
    };
    let row = format_endpoint_row(&bare);
    assert!(row.contains("openai"), "{row}");
    assert!(!row.contains("warm:"), "{row}");
}

#[test]
fn order_models_warm_first_promotes_only_served_warm_entries() {
    let models: Vec<String> = ["a", "b", "c"].map(String::from).into();
    let warm: Vec<String> = ["c", "ghost"].map(String::from).into();
    assert_eq!(
        order_models_warm_first(&models, &warm),
        ["c", "a", "b"].map(String::from).to_vec(),
        "warm first, stale warm entries ignored, order stable"
    );
    assert_eq!(order_models_warm_first(&models, &[]), models);
}

#[test]
fn parse_identity_line_accepts_name_email_and_rejects_malformed() {
    assert_eq!(
        parse_identity_line("Ada Lovelace <ada@example.com>"),
        Some(("Ada Lovelace".to_string(), "ada@example.com".to_string()))
    );
    assert_eq!(parse_identity_line("no brackets"), None);
    assert_eq!(parse_identity_line("<ada@example.com>"), None, "empty name");
    assert_eq!(parse_identity_line("Ada <not-an-email>"), None);
}

#[test]
fn select_hosted_provider_lists_available_and_notes_unavailable_rows() {
    // The picker over the core roster: supported rows are numbered;
    // an oauth-auth drop-in shows as an "(unavailable: …)" note with
    // the reason — visible, never silently dropped, never numbered.
    let mut presets = newt_core::provider_preset::builtin_presets();
    presets.push(ProviderPreset {
        name: "corp-sso".into(),
        display_name: Some("Corp SSO".into()),
        base_url: "https://llm.corp.example/v1".into(),
        auth_type: newt_core::provider_preset::AuthType::OauthDeviceCode,
        ..Default::default()
    });
    // 9 available rows == FILTER_THRESHOLD → straight numbered list
    // (no filter prompt); row 4 is OpenRouter in roster order. The
    // filter path itself is pinned by select_row_filter_maps_back….
    let console = ScriptedConsole::new(&["4"]);
    let picked = select_hosted_provider(&console.operator(), &presets).unwrap();
    assert!(matches!(
        picked,
        HostedProviderChoice::Preset(preset) if preset.name == "openrouter"
    ));
    assert!(
        !console.transcript().contains("Filter"),
        "at the threshold the list shows directly: {}",
        console.transcript()
    );
    let seen = console.transcript();
    assert!(
        seen.contains("(unavailable: Corp SSO — auth oauth_device_code"),
        "{seen}"
    );
    assert!(
        !seen.contains(") Corp SSO"),
        "unavailable rows are never numbered: {seen}"
    );
}

#[test]
fn select_hosted_provider_accepts_custom_endpoint() {
    let presets = newt_core::provider_preset::builtin_presets();
    let console = ScriptedConsole::new(&["0"]);

    let picked = select_hosted_provider(&console.operator(), &presets).unwrap();

    assert_eq!(picked, HostedProviderChoice::CustomEndpoint);
    // C0c renders options as `[0] label`, one per line, where the wizard
    // used to `say` a hand-numbered "  0) label".
    assert!(console
        .transcript()
        .contains("[0] I have a URL (custom endpoint)"));
}

#[test]
fn select_row_filter_maps_back_to_original_indices() {
    let rows: Vec<String> = (1..=12).map(|i| format!("row-{i}")).collect();
    // Filter to "row-1" matches row-1, row-10..12; pick 2 → "row-10"
    // (original index 9) — the picker must return ORIGINAL indices.
    let console = ScriptedConsole::new(&["row-1", "2"]);
    let idx = select_row(&console.operator(), &rows, "rows").unwrap();
    assert_eq!(idx, 9);
}

#[test]
fn zero_choice_is_available_before_filtering_a_large_roster() {
    let rows: Vec<String> = (1..=12).map(|i| format!("provider-{i}")).collect();
    let console = ScriptedConsole::new(&["0"]);

    let picked = select_row_with_zero(
        &console.operator(),
        &rows,
        "providers",
        "I have a URL (custom endpoint)",
    )
    .unwrap();

    assert_eq!(picked, None);
}

// --- custom-host / preset integration tests ------------------------------

/// Real-resource grounding for the mocked custom-endpoint generation and
/// credential checks; weekly/release only because it writes config files.
#[ignore = "real-resource: weekly/release tier; touches the filesystem"]
#[serial_test::serial(real_fs)]
#[tokio::test]
async fn hosted_provider_custom_endpoint_uses_supplied_base_url() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/v1/models"))
        .and(wiremock::matchers::header(
            "Authorization",
            "Bearer test-remote-key",
        ))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "data": [{"id": "example/model-a"}]
        })))
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/v1/models"))
        .respond_with(ResponseTemplate::new(401))
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/api/tags"))
        .respond_with(ResponseTemplate::new(404))
        .mount(&server)
        .await;
    mount_authenticated_openai_chat(&server, "test-remote-key").await;

    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("config.toml");
    let _config_env = EnvVarGuard::set(newt_core::config::NEWT_CONFIG_DIR_ENV, dir.path());
    newt_core::secrets::session().reset_for_test();
    let server_with_v1 = format!("{}/v1/", server.uri());
    let console = ScriptedConsole::new(&[
        "3",
        "0",
        &server_with_v1,
        "test-remote-key",
        "1",
        "1",
        "",
        "y",
    ]);

    run_with_flow(
        &console.operator(),
        &reqwest::Client::new(),
        &path,
        Flow::FirstRun,
    )
    .await
    .unwrap();

    let name = format!("127-0-0-1-{}", server.address().port());
    let dropin = read_dropin(&path, &name);
    assert_eq!(dropin.endpoint, server.uri());
    assert_eq!(dropin.effective_model(), Some("example/model-a"));
    assert_eq!(dropin.kind, Some(BackendKind::Openai));
    assert!(dropin.api_key_file.is_some());
    // The menu renders `[0] label` since #1915 (C0c); this weekly-tier copy
    // of that assertion kept the old "0) label" and went red unseen.
    assert!(console
        .transcript()
        .contains("[0] I have a URL (custom endpoint)"));
    assert!(!console.transcript().contains("test-remote-key"));

    newt_core::secrets::session().reset_for_test();
    assert_eq!(dropin.resolve_api_key().as_deref(), Some("test-remote-key"));
    newt_core::secrets::session().reset_for_test();
}

#[serial_test::serial(real_fs)]
#[tokio::test]
async fn custom_host_auth_required_stores_the_token_encrypted() {
    // An authenticated endpoint 401s the bare probe; the wizard asks for
    // the key ONCE (hidden input), re-probes, and stores the pasted token
    // ENCRYPTED at rest — plaintext never lands on disk or in output.
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/v1/models"))
        .and(wiremock::matchers::header(
            "Authorization",
            "Bearer test-remote-key",
        ))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "data": [
                {"id": "example/model-a"},
                {"id": "example/model-b"}
            ]
        })))
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/v1/models"))
        .respond_with(ResponseTemplate::new(401))
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/api/tags"))
        .respond_with(ResponseTemplate::new(404))
        .mount(&server)
        .await;
    mount_authenticated_openai_chat(&server, "test-remote-key").await;

    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("config.toml");
    // Pin the config dir: the machine identity for blank-passphrase
    // encryption lives under it.
    let _config_env = EnvVarGuard::set(newt_core::config::NEWT_CONFIG_DIR_ENV, dir.path());
    newt_core::secrets::session().reset_for_test();
    let client = reqwest::Client::new();

    let server_with_v1 = format!("{}/v1", server.uri());
    // custom host=2, host (with /v1 — stripped), key (hidden), endpoint=1,
    // model=1, passphrase=<Enter: machine key>, write=Y
    let console =
        ScriptedConsole::new(&["2", &server_with_v1, "test-remote-key", "1", "1", "", "y"]);
    run_with(&console.operator(), &client, &path).await.unwrap();

    let name = format!("127-0-0-1-{}", server.address().port());
    let dropin = read_dropin(&path, &name);
    assert_eq!(dropin.effective_model(), Some("example/model-a"));
    assert!(!dropin.endpoint.ends_with("/v1"), "probe suffix stripped");
    let token_ref = dropin.api_key_file.as_deref().expect("key recorded");
    // `token_ref` may be `~/…`-collapsed (`setup::collapse_home`) when the
    // config dir happens to sit under HOME/USERPROFILE — true on a real
    // Windows profile, where %TEMP% is %USERPROFILE%\AppData\Local\Temp.
    // A raw `PathBuf::from` here (previously) treated a literal `~` as a
    // relative path component on Windows, resolved against the test's CWD
    // instead of home, and failed with "The system cannot find the path
    // specified." `expand_home_for_test` matches what production's
    // `resolve_api_key()` actually does.
    let token_path = expand_home_for_test(token_ref);
    let token_name = token_path
        .file_name()
        .and_then(|name| name.to_str())
        .unwrap();
    assert!(
        token_name.starts_with(&format!("{name}.token.")) && token_name.ends_with(".age"),
        "versioned encrypted ref: {token_ref}"
    );
    let body = std::fs::read_to_string(&token_path).unwrap();
    assert!(
        body.starts_with("-----BEGIN AGE ENCRYPTED FILE-----"),
        "ciphertext on disk"
    );
    assert!(!body.contains("test-remote-key"), "no plaintext token");
    assert!(
        !console.transcript().contains("test-remote-key"),
        "the token is never echoed"
    );
    // The freshly stored token resolves transparently (machine identity).
    newt_core::secrets::session().reset_for_test();
    assert_eq!(dropin.resolve_api_key().as_deref(), Some("test-remote-key"));

    newt_core::secrets::session().reset_for_test();
}

#[serial_test::serial(real_fs)]
#[tokio::test]
async fn token_reference_resolves_when_config_dir_sits_under_home() {
    // Regression for a Windows-only failure (caster, a real user profile):
    // `%TEMP%` there is `%USERPROFILE%\AppData\Local\Temp`, i.e. nested
    // under home. `custom_host_auth_required_stores_the_token_encrypted`
    // pins NEWT_CONFIG_DIR to a `tempfile::tempdir()`, and
    // `setup::collapse_home` tilde-collapses the recorded `api_key_file`
    // whenever the config dir happens to sit under HOME/USERPROFILE —
    // independent of NEWT_CONFIG_DIR, by design. Linux's `/tmp` and
    // windows-latest CI's redirected `%TEMP%` (outside the profile) never
    // trigger that collapse, which is why this was invisible there.
    //
    // Force the same nesting deterministically, on every OS: point
    // HOME/USERPROFILE at a fake home and pin NEWT_CONFIG_DIR underneath
    // it. Before the fix (a raw `PathBuf::from` on the collapsed
    // reference), this reproduces caster's exact
    // `Os { code: 3, kind: NotFound, .. }` on Linux too.
    let fake_home = tempfile::tempdir().unwrap();
    let dir_path = fake_home.path().join("cfg");
    std::fs::create_dir_all(&dir_path).unwrap();
    let _home = EnvVarGuard::set("HOME", fake_home.path());
    let _userprofile = EnvVarGuard::set("USERPROFILE", fake_home.path());
    let _config_env = EnvVarGuard::set(newt_core::config::NEWT_CONFIG_DIR_ENV, &dir_path);
    newt_core::secrets::session().reset_for_test();

    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/v1/models"))
        .and(wiremock::matchers::header(
            "Authorization",
            "Bearer test-remote-key",
        ))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "data": [{"id": "example/model-a"}]
        })))
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/v1/models"))
        .respond_with(ResponseTemplate::new(401))
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/api/tags"))
        .respond_with(ResponseTemplate::new(404))
        .mount(&server)
        .await;
    mount_authenticated_openai_chat(&server, "test-remote-key").await;

    let path = dir_path.join("config.toml");
    let client = reqwest::Client::new();
    let server_with_v1 = format!("{}/v1", server.uri());
    let console =
        ScriptedConsole::new(&["2", &server_with_v1, "test-remote-key", "1", "1", "", "y"]);
    run_with(&console.operator(), &client, &path).await.unwrap();

    let name = format!("127-0-0-1-{}", server.address().port());
    let dropin = read_dropin(&path, &name);
    let token_ref = dropin.api_key_file.as_deref().expect("key recorded");
    assert!(
        token_ref.starts_with("~/"),
        "expected collapse_home to fire once the config dir sits under home: {token_ref}"
    );
    let token_path = expand_home_for_test(token_ref);
    let body = std::fs::read_to_string(&token_path).unwrap_or_else(|e| {
        panic!("token file must be readable at the resolved path {token_path:?}: {e}")
    });
    assert!(
        body.starts_with("-----BEGIN AGE ENCRYPTED FILE-----"),
        "ciphertext on disk"
    );

    newt_core::secrets::session().reset_for_test();
}

#[serial_test::serial(real_fs)]
#[tokio::test]
async fn preset_skip_key_records_the_env_reference() {
    // A preset with no pasted key writes the backend anyway, recording
    // the provider's canonical env var — nothing stored on disk.
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/v1/models"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "data": [{"id": "open-model"}]
        })))
        .mount(&server)
        .await;
    mount_openai_chat(&server).await;
    let _preset_env = EnvVarGuard::remove("NEWT_TEST_PRESET_KEY");
    let preset = ProviderPreset {
        name: "testcloud".into(),
        display_name: Some("Test Cloud".into()),
        base_url: format!("{}/v1", server.uri()),
        env_vars: vec!["NEWT_TEST_PRESET_KEY".into()],
        fallback_models: vec!["fallback-model".into()],
        signup_url: Some("https://example.invalid/keys".into()),
        ..Default::default()
    };
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("config.toml");
    let client = reqwest::Client::new();
    // key=<Enter: skip>, model=1
    let console = ScriptedConsole::new(&["", "1"]);
    let (_cfg, backend, _pending) = configure_preset(&console.operator(), &client, &preset, &path)
        .await
        .unwrap();
    assert_eq!(backend.api_key_env.as_deref(), Some("NEWT_TEST_PRESET_KEY"));
    assert!(backend.api_key_file.is_none(), "nothing stored on skip");
    assert_eq!(backend.effective_model(), Some("open-model"));
    assert_eq!(backend.kind, Some(BackendKind::Openai));
    assert!(
        console
            .transcript()
            .contains("export $NEWT_TEST_PRESET_KEY"),
        "the skip warns how to supply the key: {}",
        console.transcript()
    );
}

#[serial_test::serial(real_fs)]
#[tokio::test]
async fn preset_pasted_token_is_stored_encrypted_with_a_passphrase() {
    // The pasted-key path: hidden input, optional passphrase, encrypted
    // .token.age reference — and the model probe runs WITH the key.
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/v1/models"))
        .and(wiremock::matchers::header(
            "Authorization",
            "Bearer sk-preset-secret",
        ))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "data": [{"id": "gated-model"}]
        })))
        .mount(&server)
        .await;
    mount_authenticated_openai_chat(&server, "sk-preset-secret").await;
    let _preset_env = EnvVarGuard::remove("NEWT_TEST_PRESET_KEY");
    let preset = ProviderPreset {
        name: "gatedcloud".into(),
        display_name: Some("Gated Cloud".into()),
        base_url: format!("{}/v1", server.uri()),
        env_vars: vec!["NEWT_TEST_PRESET_KEY".into()],
        fallback_models: vec!["fallback-model".into()],
        signup_url: Some("https://example.invalid/keys".into()),
        ..Default::default()
    };
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("config.toml");
    let _config_env = EnvVarGuard::set(newt_core::config::NEWT_CONFIG_DIR_ENV, dir.path());
    newt_core::secrets::session().reset_for_test();
    let client = reqwest::Client::new();
    // key (hidden), passphrase, model=1
    let console = ScriptedConsole::new(&["sk-preset-secret", "open sesame", "1"]);
    let (_cfg, backend, pending) = configure_preset(&console.operator(), &client, &preset, &path)
        .await
        .unwrap();
    assert!(backend.api_key_env.is_none());
    let token_ref = backend.api_key_file.as_deref().expect("encrypted ref");
    assert!(token_ref.contains("gatedcloud.token."));
    assert!(token_ref.ends_with(".age"));
    assert_eq!(backend.effective_model(), Some("gated-model"));
    let pending = pending.expect("token is held until final write");
    assert_eq!(
        persist_wizard_token(&console.operator(), &path, "gatedcloud", &pending).unwrap(),
        token_ref
    );
    let body = std::fs::read_to_string(&pending.path).unwrap();
    assert!(body.starts_with("-----BEGIN AGE ENCRYPTED FILE-----"));
    assert!(!body.contains("sk-preset-secret"));
    assert!(!console.transcript().contains("sk-preset-secret"));

    newt_core::secrets::session().reset_for_test();
}

#[serial_test::serial(real_fs)]
#[tokio::test]
async fn preset_uses_an_exported_env_var_without_storing_anything() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/v1/models"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "data": [{"id": "env-model"}]
        })))
        .mount(&server)
        .await;
    mount_authenticated_openai_chat(&server, "sk-from-env").await;
    let _preset_env = EnvVarGuard::set("NEWT_TEST_PRESET_KEY", "sk-from-env");
    let preset = ProviderPreset {
        name: "envcloud".into(),
        display_name: Some("Env Cloud".into()),
        base_url: format!("{}/v1", server.uri()),
        env_vars: vec!["NEWT_TEST_PRESET_KEY".into()],
        fallback_models: vec!["fallback-model".into()],
        signup_url: Some("https://example.invalid/keys".into()),
        ..Default::default()
    };
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("config.toml");
    let client = reqwest::Client::new();
    // use exported?=y, model=1.
    //
    // D1b-2 (#1903): this said `""` — Enter — because `is_yes(&ans, true)`
    // read blank as YES. Adopting a credential from the environment is a
    // decision, and the wizard no longer makes it for the operator; see
    // `an_empty_answer_does_not_adopt_the_exported_key` below.
    let console = ScriptedConsole::new(&["y", "1"]);
    let (_cfg, backend, _pending) = configure_preset(&console.operator(), &client, &preset, &path)
        .await
        .unwrap();
    assert_eq!(backend.api_key_env.as_deref(), Some("NEWT_TEST_PRESET_KEY"));
    assert!(backend.api_key_file.is_none(), "env reference only");
    assert_eq!(backend.effective_model(), Some("env-model"));
}

/// **Regression (D1b-2, #1903): a blank answer does not adopt an exported
/// credential.**
///
/// Before this slice the prompt was `"${var} is set in this shell. Use it?
/// [Y/n] "` resolved by `is_yes(&ans, true)`, so BOTH an empty answer and
/// every unrecognised word meant yes. Adopting a key from the environment is
/// a decision — one with a security consequence, since the adopted key is
/// what the backend then authenticates with — and the wizard no longer makes
/// it for the operator. Blank re-asks, and an input with nothing left to give
/// fails rather than choosing.
// Mutates the process environment, so it shares the sibling's serial
// lane (issue #514 / the #1872 env-race class): two tests setting and
// restoring the same var in parallel see each other's writes.
#[serial_test::serial(real_fs)]
#[tokio::test]
async fn an_empty_answer_does_not_adopt_the_exported_key() {
    let _preset_env = EnvVarGuard::set("NEWT_TEST_PRESET_KEY", "sk-from-env");
    let preset = ProviderPreset {
        name: "envcloud".into(),
        base_url: "http://127.0.0.1:1/v1".into(),
        env_vars: vec!["NEWT_TEST_PRESET_KEY".into()],
        ..Default::default()
    };
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("config.toml");
    // An exhausted script answers "" forever — a short pipe.
    let console = ScriptedConsole::new(&[]);
    // `let Err(..) else` rather than `expect_err`: the success type contains
    // `PendingWizardToken`, which deliberately has no `Debug` (it holds a
    // key). Reaching for `expect_err` would mean deriving `Debug` on a
    // secret-carrying record to satisfy a test, which is backwards.
    let Err(err) =
        configure_preset(&console.operator(), &reqwest::Client::new(), &preset, &path).await
    else {
        panic!("a blank answer must not adopt the key");
    };
    assert!(
        err.to_string().contains("no usable answer"),
        "gave up rather than guessing: {err}"
    );
    assert!(
        console
            .output
            .borrow()
            .iter()
            .any(|l| l.contains("not one of the choices — enter y, n")),
        "and said why: {:?}",
        console.output
    );
}

/// **The anti-vacuous twin.** If `decide` refused everything — or if the
/// prompt never resolved at all — the test above would pass while the wizard
/// became unusable. An explicit `n` must still be heard, and must take the
/// paste branch rather than the env branch.
// Mutates the process environment, so it shares the sibling's serial
// lane (issue #514 / the #1872 env-race class): two tests setting and
// restoring the same var in parallel see each other's writes.
#[serial_test::serial(real_fs)]
#[tokio::test]
async fn an_explicit_no_declines_the_exported_key_and_asks_for_one() {
    let _preset_env = EnvVarGuard::set("NEWT_TEST_PRESET_KEY", "sk-from-env");
    let preset = ProviderPreset {
        name: "envcloud".into(),
        base_url: "http://127.0.0.1:1/v1".into(),
        env_vars: vec!["NEWT_TEST_PRESET_KEY".into()],
        ..Default::default()
    };
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("config.toml");
    // n = do not use the exported key; then Enter skips the paste prompt.
    let console = ScriptedConsole::new(&["n", ""]);
    let _ = configure_preset(&console.operator(), &reqwest::Client::new(), &preset, &path).await;
    assert!(
        console
            .output
            .borrow()
            .iter()
            .any(|l| l.contains("export $NEWT_TEST_PRESET_KEY")),
        "declining routed to the paste path, which skipped: {:?}",
        console.output
    );
}

/// Regression heir: the old plaintext writer used `var_os("HOME")?`, so
/// on Windows — where the variable is `USERPROFILE` — the `?` bailed and
/// the key went unrecorded. The encrypted writer must likewise record a
/// usable (absolute) reference even with no home to collapse against.
#[test]
#[serial_test::serial(real_fs)]
fn a_token_reference_is_recorded_even_when_home_is_unset() {
    let dir = tempfile::tempdir().unwrap();
    // The machine identity needs a config root even with HOME unset.
    let _config_env = EnvVarGuard::set(newt_core::config::NEWT_CONFIG_DIR_ENV, dir.path());
    newt_core::secrets::session().reset_for_test();
    let _home = EnvVarGuard::remove("HOME");
    let _userprofile = EnvVarGuard::remove("USERPROFILE");

    let path = dir.path().join("config.toml");
    // passphrase=<Enter: machine key>
    let console = ScriptedConsole::new(&[""]);
    let pending = collect_wizard_token(
        &console.operator(),
        &Secret::new("a-secret"),
        &path,
        "example",
    )
    .unwrap();
    let recorded = persist_wizard_token(&console.operator(), &path, "example", &pending)
        .expect("a supplied key must always be recorded, home dir or not");

    assert!(
        !recorded.starts_with('~'),
        "with no home to collapse against, the path stays absolute: {recorded}"
    );
    assert!(recorded.contains("example.token."));
    assert!(recorded.ends_with(".age"));
    let body = std::fs::read_to_string(&recorded).unwrap();
    assert!(body.starts_with("-----BEGIN AGE ENCRYPTED FILE-----"));
    assert!(!body.contains("a-secret"), "never plaintext on disk");

    newt_core::secrets::session().reset_for_test();
}

// --- model selector (#1452): a llama.cpp router serves 30+ models, so the
// operator must never have to type an id exactly. ---

#[test]
fn a_short_list_is_shown_directly_with_no_filter_prompt() {
    let models: Vec<String> = (1..=3).map(|i| format!("model-{i}")).collect();
    let console = ScriptedConsole::new(&["2"]);
    assert_eq!(
        select_model(&console.operator(), &models).unwrap(),
        "model-2"
    );
    // Asking to filter three items would be pure ceremony.
    assert!(
        !console.transcript().contains("Filter"),
        "no filter prompt below the threshold: {}",
        console.transcript()
    );
}

#[test]
fn a_long_list_filters_then_picks_by_number() {
    let mut models: Vec<String> = (1..=30).map(|i| format!("filler-{i}")).collect();
    models.push("qwen3.6_35b".into());
    models.push("qwen3-coder_30b".into());

    // Type a fragment, then choose from the two matches — the operator
    // never types the full id.
    let console = ScriptedConsole::new(&["qwen", "2"]);
    assert_eq!(
        select_model(&console.operator(), &models).unwrap(),
        "qwen3-coder_30b"
    );
    let seen = console.transcript();
    assert!(seen.contains("32 models available"), "{seen}");
    assert!(!seen.contains("filler-1)"), "filtered out: {seen}");
}

#[test]
fn the_filter_is_case_insensitive_and_matches_substrings() {
    let mut models: Vec<String> = (1..=20).map(|i| format!("filler-{i}")).collect();
    models.push("Qwen3-Coder".into());
    let console = ScriptedConsole::new(&["CODER", "1"]);
    assert_eq!(
        select_model(&console.operator(), &models).unwrap(),
        "Qwen3-Coder"
    );
}

/// A filter that matches nothing must not dead-end the operator in an empty
/// menu — it falls back to the whole list.
#[test]
fn a_filter_matching_nothing_falls_back_to_the_full_list() {
    let models: Vec<String> = (1..=20).map(|i| format!("model-{i}")).collect();
    let console = ScriptedConsole::new(&["zzz-no-such-model", "3"]);
    assert_eq!(
        select_model(&console.operator(), &models).unwrap(),
        "model-3"
    );
    assert!(console.transcript().contains("showing all"));
}

#[test]
fn a_blank_filter_shows_everything() {
    let models: Vec<String> = (1..=15).map(|i| format!("model-{i}")).collect();
    let console = ScriptedConsole::new(&["", "15"]);
    assert_eq!(
        select_model(&console.operator(), &models).unwrap(),
        "model-15"
    );
}

/// An out-of-range or unparseable choice takes the first entry rather than
/// erroring out mid-setup.
#[test]
fn an_invalid_choice_falls_back_to_the_first_entry() {
    let models: Vec<String> = vec!["a".into(), "b".into()];
    for answer in ["", "99", "nonsense", "0", "-1"] {
        let console = ScriptedConsole::new(&[answer]);
        assert_eq!(select_model(&console.operator(), &models).unwrap(), "a");
    }
}

#[serial_test::serial(real_fs)]
#[tokio::test]
async fn custom_host_requires_a_host() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/tags"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "models": [{"name": "qwen2.5-coder:32b"}]
        })))
        .mount(&server)
        .await;
    mount_ollama_chat(&server).await;
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("config.toml");
    let client = reqwest::Client::new();
    // custom host, empty host (reprompt), then real host, endpoint=1, model=1, write=Y
    let console = ScriptedConsole::new(&["2", "", &server.uri(), "1", "1", "y"]);
    run_with(&console.operator(), &client, &path).await.unwrap();
    let name = format!("127-0-0-1-{}", server.address().port());
    let cfg = crate::migration_notices::read(|report| Config::load(&path, report)).unwrap();
    assert_eq!(cfg.default_backend.as_deref(), Some(name.as_str()));
    assert_eq!(
        read_dropin(&path, &name).effective_model(),
        Some("qwen2.5-coder:32b")
    );
    // The reprompt message was shown.
    assert!(console.transcript().contains("host is required"));
}

/// Setup asks the sandbox git profile through `/settings`' own fields and
/// writes it through their one path, into the operator's identity file.
#[test]
#[serial_test::serial(real_fs)]
fn setup_writes_the_sandbox_git_profile_through_settings() {
    let dir = tempfile::tempdir().unwrap();
    let _config_env = EnvVarGuard::set(newt_core::config::NEWT_CONFIG_DIR_ENV, dir.path());
    // `git-author`: [2] operator; `git-config`: [1] baseline; `git-signing`: [1] off.
    let console = ScriptedConsole::new(&["2", "1", "1"]);
    offer_sandbox_git(&console.operator());
    let saved = newt_core::AgentIdentity::load(
        &dir.path()
            .join(newt_core::agent_identity::AGENT_IDENTITY_FILENAME),
    )
    .unwrap();
    assert_eq!(
        saved.git.author,
        newt_core::agent_identity::SandboxAuthor::Operator
    );
    assert_eq!(
        saved.git.config_source,
        newt_core::agent_identity::GitConfigSource::Baseline
    );
    assert!(
        console
            .transcript()
            .contains("sandbox git commit author: operator"),
        "{}",
        console.transcript()
    );
}

/// #2660, red-first: appending `offer_caveat_pack` after `offer_sandbox_git`
/// must not disturb every existing scripted test that stops providing
/// answers once the backend write completes — `Script` returns a blank for
/// every question asked after its queue runs dry, and "writes files: blank
/// must not consent" (the same rule the backend-write confirm already uses)
/// means a dry queue must decline both new prompts (exclude names, then
/// sign-and-write) and leave `approve.toml` untouched.
#[test]
#[serial_test::serial(real_fs)]
fn offer_caveat_pack_declines_on_blank_and_writes_nothing() {
    let dir = tempfile::tempdir().unwrap();
    let _config_env = EnvVarGuard::set(newt_core::config::NEWT_CONFIG_DIR_ENV, dir.path());
    let config_path = Config::user_config_path().unwrap();
    let console = ScriptedConsole::new(&[]);

    offer_caveat_pack(&console.operator(), &config_path, Some("127.0.0.1"));

    assert!(
        !config_path
            .with_file_name("ocap")
            .join("approve.toml")
            .exists(),
        "a dry answer queue must decline the write, not default to it"
    );
}

/// #2660: the standard pack signs the low-danger text tools and the
/// configured host, names `awk`/`xargs`/`sh` as high-danger without ever
/// signing them, and never lists `git`/`gh` at all. The signed result is
/// verified back through the REAL gate question
/// (`ocap_store::evaluate_request`) with the SAME root key the step just
/// minted — proving a listed tool/host is granted and an unlisted one still
/// falls through to the prompt, per #2660's acceptance contract.
#[test]
#[serial_test::serial(real_fs)]
fn offer_caveat_pack_signs_low_danger_defers_high_danger_excludes_git() {
    let dir = tempfile::tempdir().unwrap();
    let _config_env = EnvVarGuard::set(newt_core::config::NEWT_CONFIG_DIR_ENV, dir.path());
    let config_path = Config::user_config_path().unwrap();
    // exclude: blank (keep all); sign-and-write: y.
    let console = ScriptedConsole::new(&["", "y"]);

    offer_caveat_pack(&console.operator(), &config_path, Some("127.0.0.1"));

    let transcript = console.transcript();
    assert!(transcript.contains("exec  cat"), "{transcript}");
    for high in ["awk", "xargs", "sh"] {
        assert!(
            transcript.contains(high),
            "high-danger target named in the review: {transcript}"
        );
    }
    assert!(!transcript.contains("exec  git"), "{transcript}");
    assert!(!transcript.contains("exec  gh"), "{transcript}");

    let key_path = newt_identity::default_key_path().unwrap();
    let user = newt_identity::load_or_generate(&key_path).unwrap();
    let (set, warnings) =
        newt_core::ocap_store::load_store(&config_path, Some(user.public().as_bytes()));
    assert!(warnings.is_empty(), "{warnings:?}");

    assert_eq!(
        newt_core::ocap_store::evaluate_request(&set, newt_core::DenialKind::Exec, "cat"),
        Some(newt_core::ocap_store::Verdict::Approve),
        "a listed tool is durably granted"
    );
    assert_eq!(
        newt_core::ocap_store::evaluate_request(&set, newt_core::DenialKind::Net, "127.0.0.1"),
        Some(newt_core::ocap_store::Verdict::Approve),
        "the configured host is durably granted"
    );
    assert_eq!(
        newt_core::ocap_store::evaluate_request(&set, newt_core::DenialKind::Exec, "awk"),
        None,
        "a named high-danger target is never durably signed"
    );
    assert_eq!(
        newt_core::ocap_store::evaluate_request(&set, newt_core::DenialKind::Exec, "git"),
        None,
        "an unlisted tool still falls through to the interactive gate"
    );
}

/// #2660: "every entry is visible and removable" — the operator can exclude
/// one by name before anything is signed.
#[test]
#[serial_test::serial(real_fs)]
fn offer_caveat_pack_exclude_prompt_removes_the_named_entry() {
    let dir = tempfile::tempdir().unwrap();
    let _config_env = EnvVarGuard::set(newt_core::config::NEWT_CONFIG_DIR_ENV, dir.path());
    let config_path = Config::user_config_path().unwrap();
    // exclude: "cat"; sign-and-write: y.
    let console = ScriptedConsole::new(&["cat", "y"]);

    offer_caveat_pack(&console.operator(), &config_path, None);

    let approve_path = config_path.with_file_name("ocap").join("approve.toml");
    let text = std::fs::read_to_string(&approve_path).unwrap();
    let file = newt_core::ocap_store::PolicyFile::parse(&text).unwrap();
    assert!(
        !file.exec.iter().any(|e| e.target == "cat"),
        "excluded entry was still signed: {file:?}"
    );
    assert!(
        file.exec.iter().any(|e| e.target == "head"),
        "a non-excluded entry was still written: {file:?}"
    );
}

/// #2660 round 2, item 1 (P1), red-first: `try_offer_caveat_pack` used to
/// pass the WHOLE merged approve file to `sign_approves`, which re-blesses
/// every entry that passes the danger check — including a pre-existing
/// entry the operator never saw in THIS review. Measured red: before the
/// fix, this pre-seeded, unsigned, unrelated net entry came back signed
/// after the operator confirmed only the displayed `127.0.0.1` addition.
#[test]
#[serial_test::serial(real_fs)]
fn offer_caveat_pack_signs_only_the_reviewed_additions() {
    let dir = tempfile::tempdir().unwrap();
    let _config_env = EnvVarGuard::set(newt_core::config::NEWT_CONFIG_DIR_ENV, dir.path());
    let config_path = Config::user_config_path().unwrap();
    let approve_path = config_path.with_file_name("ocap").join("approve.toml");
    std::fs::create_dir_all(approve_path.parent().unwrap()).unwrap();
    // A pre-existing, unsigned entry for a host unrelated to this run's
    // review — never displayed, never confirmed.
    std::fs::write(&approve_path, "[[net]]\nhost = \"unrelated.example\"\n").unwrap();

    // exclude: blank (keep all); sign-and-write: y.
    let console = ScriptedConsole::new(&["", "y"]);
    offer_caveat_pack(&console.operator(), &config_path, Some("127.0.0.1"));

    let text = std::fs::read_to_string(&approve_path).unwrap();
    let file = newt_core::ocap_store::PolicyFile::parse(&text).unwrap();
    let unrelated = file
        .net
        .iter()
        .find(|e| e.host == "unrelated.example")
        .expect("pre-existing entry must be preserved");
    assert!(
        unrelated.sig.is_none(),
        "setup must sign only what the operator saw this run, not every \
         existing entry: {unrelated:?}"
    );
    let reviewed = file
        .net
        .iter()
        .find(|e| e.host == "127.0.0.1")
        .expect("the reviewed addition must be written");
    assert!(
        reviewed.sig.is_some(),
        "the displayed, confirmed addition must still be signed: {reviewed:?}"
    );
}

/// #2660 round 2, item 3 / round 3, item 2: a drop-in's `exec` list can
/// spell `git` as an absolute path. With narrowing-only drop-ins (round 3),
/// this is caught even earlier than `drop_never_candidates`: `/usr/bin/git`
/// isn't already in the built-in pool, so `narrow_candidates` treats it as
/// an attempted addition and never merges it in at all — proven here
/// through the real setup/signing path, not just the pure helpers' unit
/// tests in `newt_core::caveat_pack`: never shown in the review, never
/// durably signed.
#[test]
#[serial_test::serial(real_fs)]
fn offer_caveat_pack_excludes_a_drop_in_git_path_spelling() {
    let dir = tempfile::tempdir().unwrap();
    let _config_env = EnvVarGuard::set(newt_core::config::NEWT_CONFIG_DIR_ENV, dir.path());
    let config_path = Config::user_config_path().unwrap();
    std::fs::write(
        config_path.with_file_name("caveat-pack.toml"),
        "exec = [\"/usr/bin/git\"]\n",
    )
    .unwrap();
    // exclude: blank (keep all); sign-and-write: y.
    let console = ScriptedConsole::new(&["", "y"]);

    offer_caveat_pack(&console.operator(), &config_path, None);

    let transcript = console.transcript();
    assert!(
        !transcript.contains("exec  git") && !transcript.contains("exec  /usr/bin/git"),
        "a drop-in git spelling must never reach the review: {transcript}"
    );
    assert!(
        transcript.contains("/usr/bin/git") && transcript.contains("ignored"),
        "the rejected addition attempt must be visibly reported: {transcript}"
    );

    let key_path = newt_identity::default_key_path().unwrap();
    let user = newt_identity::load_or_generate(&key_path).unwrap();
    let (set, warnings) =
        newt_core::ocap_store::load_store(&config_path, Some(user.public().as_bytes()));
    assert!(warnings.is_empty(), "{warnings:?}");
    assert_eq!(
        newt_core::ocap_store::evaluate_request(&set, newt_core::DenialKind::Exec, "git"),
        None,
        "a drop-in git spelling must never be durably signed"
    );
}

/// #2660 round 3, item 2 (P1), red-first: the exact bypass the review named
/// — with the old merge-then-filter shape, a drop-in listing `sed`/`find`/
/// `sort`/`git` reintroduced each of them to the review (only `git`/`gh`
/// were ever filtered back out) and, on confirmation, to a durable
/// signature. A drop-in may only narrow the built-in offer now: none of
/// these four is already in it, so each is an attempted addition — reported
/// with a visible notice, never merged in, never signed.
#[test]
#[serial_test::serial(real_fs)]
fn offer_caveat_pack_drop_in_addition_attempt_is_ignored_with_notice() {
    let dir = tempfile::tempdir().unwrap();
    let _config_env = EnvVarGuard::set(newt_core::config::NEWT_CONFIG_DIR_ENV, dir.path());
    let config_path = Config::user_config_path().unwrap();
    std::fs::write(
        config_path.with_file_name("caveat-pack.toml"),
        "exec = [\"sed\", \"find\", \"sort\", \"git\"]\n",
    )
    .unwrap();
    // exclude: blank (keep all); sign-and-write: y.
    let console = ScriptedConsole::new(&["", "y"]);

    offer_caveat_pack(&console.operator(), &config_path, None);

    let transcript = console.transcript();
    assert!(
        transcript.contains("sed, find, sort, git") && transcript.contains("ignored"),
        "the rejected addition attempt must be reported, not silently dropped: {transcript}"
    );
    for never in ["exec  sed", "exec  find", "exec  sort", "exec  git"] {
        assert!(
            !transcript.contains(never),
            "an attempted addition must never reach the review: {transcript}"
        );
    }

    let key_path = newt_identity::default_key_path().unwrap();
    let user = newt_identity::load_or_generate(&key_path).unwrap();
    let (set, warnings) =
        newt_core::ocap_store::load_store(&config_path, Some(user.public().as_bytes()));
    assert!(warnings.is_empty(), "{warnings:?}");
    for never in ["sed", "find", "sort", "git"] {
        assert_eq!(
            newt_core::ocap_store::evaluate_request(&set, newt_core::DenialKind::Exec, never),
            None,
            "an attempted drop-in addition must never be durably signed: {never}"
        );
    }
}

/// #2660 round 2, item 4: an unreadable existing approve file must refuse
/// the write rather than treat the read error as "no file yet" and
/// overwrite it. Injected via `chmod 000` (`#[cfg(unix)]` — POSIX
/// permissions have no Windows equivalent): the atomic-replace step only
/// needs write permission on the *directory*, so an unreadable-but-present
/// file is a case where the OLD `Err(_) => PolicyFile::default()` code would
/// have gone on to silently overwrite a file it could not read — unlike a
/// missing *directory* or a locked path, which fail at other steps
/// regardless of this fix and so would not discriminate old from new
/// behavior.
#[cfg(unix)]
#[test]
#[serial_test::serial(real_fs)]
fn offer_caveat_pack_refuses_on_an_unreadable_approve_file_without_writing() {
    use std::os::unix::fs::PermissionsExt;

    let dir = tempfile::tempdir().unwrap();
    let _config_env = EnvVarGuard::set(newt_core::config::NEWT_CONFIG_DIR_ENV, dir.path());
    let config_path = Config::user_config_path().unwrap();
    let approve_path = config_path.with_file_name("ocap").join("approve.toml");
    std::fs::create_dir_all(approve_path.parent().unwrap()).unwrap();
    std::fs::write(&approve_path, "[[net]]\nhost = \"unrelated.example\"\n").unwrap();
    std::fs::set_permissions(&approve_path, std::fs::Permissions::from_mode(0o000)).unwrap();

    // exclude: blank (keep all); sign-and-write: y.
    let console = ScriptedConsole::new(&["", "y"]);
    offer_caveat_pack(&console.operator(), &config_path, Some("127.0.0.1"));

    // Restore read access before asserting, so the check itself can read it.
    std::fs::set_permissions(&approve_path, std::fs::Permissions::from_mode(0o600)).unwrap();
    let text = std::fs::read_to_string(&approve_path).unwrap();
    assert!(
        text.contains("unrelated.example"),
        "a refused write must leave the unreadable file's content untouched: {text}"
    );
    assert!(
        !text.contains("127.0.0.1"),
        "a refused read must not go on to write the new addition: {text}"
    );
    assert!(
        console.transcript().contains("Standard caveat pack:"),
        "the read error must be reported, not swallowed silently: {}",
        console.transcript()
    );
}