leviath-cli 0.2.0

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

use std::collections::HashMap;

use leviath_mcp::MCPServerConfig;
use tokio::sync::mpsc;

use super::catalog::{self, Credential, Provider};
use super::import::{self, Candidate};
use super::plan::SetupPlan;
use super::verify::Outcome;
use crate::bundled::{AgentAction, BundledAgent};
use crate::config::Config;

/// The wizard's screens, in order.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Step {
    Welcome,
    Providers,
    ProviderDetail,
    Defaults,
    Limits,
    Agents,
    Mcp,
    Review,
}

impl Step {
    /// Every step, in order.
    pub const ALL: [Step; 8] = [
        Step::Welcome,
        Step::Providers,
        Step::ProviderDetail,
        Step::Defaults,
        Step::Limits,
        Step::Agents,
        Step::Mcp,
        Step::Review,
    ];

    /// Title shown in the header.
    pub fn title(self) -> &'static str {
        match self {
            Step::Welcome => "Welcome",
            Step::Providers => "Providers",
            Step::ProviderDetail => "Credentials",
            Step::Defaults => "Defaults",
            Step::Limits => "Limits",
            Step::Agents => "Agents",
            Step::Mcp => "MCP servers",
            Step::Review => "Review",
        }
    }

    /// Position in [`Self::ALL`].
    pub fn index(self) -> usize {
        Self::ALL
            .iter()
            .position(|s| *s == self)
            .expect("every step is in ALL")
    }
}

/// One row of the provider pick-list.
#[derive(Debug, Clone)]
pub struct ProviderRow {
    pub provider: Provider,
    pub selected: bool,
    /// The credential as typed. Empty means "no value".
    pub value: String,
    /// The credential is already in the environment, under this variable, and
    /// is not being written to the config.
    pub from_env: Option<&'static str>,
    /// Reasoning effort, for the Claude Code transport only.
    pub effort: usize,
    pub outcome: Outcome,
    /// A verification is in flight.
    pub checking: bool,
}

impl ProviderRow {
    /// Whether this provider has something to verify.
    pub fn has_credential(&self) -> bool {
        match self.provider.credential {
            Credential::ApiKey => !self.value.is_empty() || self.from_env.is_some(),
            // Ollama and the Claude Code transport need no key; selecting them
            // is the whole configuration, so they are always checkable.
            Credential::BaseUrl | Credential::None => true,
        }
    }
}

/// One row of the blueprint list.
#[derive(Debug, Clone)]
pub struct AgentRow {
    pub agent: &'static BundledAgent,
    pub action: AgentAction,
    pub selected: bool,
}

/// One importable MCP server.
#[derive(Debug, Clone)]
pub struct McpRow {
    pub candidate: Candidate,
    /// Which harness it came from.
    pub source: String,
    pub selected: bool,
    /// A server of this name is already in the Leviath config.
    pub collides: bool,
    /// The name it will actually be stored under, after collision handling.
    pub name: String,
}

/// A single editable setting on the Defaults / Limits screens.
#[derive(Debug, Clone)]
pub struct Field {
    pub label: &'static str,
    pub help: &'static str,
    pub value: FieldValue,
}

/// The kinds of setting the wizard edits, and therefore the ways a key press
/// can mean something.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FieldValue {
    /// A whole number. `None` means unset.
    Number(Option<u64>),
    /// A toggle.
    Bool(bool),
    /// One of a fixed list.
    Choice { options: Vec<String>, index: usize },
}

impl FieldValue {
    /// How the value reads on screen.
    pub fn display(&self) -> String {
        match self {
            Self::Number(None) => "(unset)".to_string(),
            Self::Number(Some(n)) => n.to_string(),
            Self::Bool(true) => "yes".to_string(),
            Self::Bool(false) => "no".to_string(),
            Self::Choice { options, index } => match options.get(*index) {
                Some(chosen) => chosen.clone(),
                None => "(none)".to_string(),
            },
        }
    }

    /// The options of a choice field; empty for any other kind.
    pub fn options(&self) -> &[String] {
        match self {
            Self::Choice { options, .. } => options,
            Self::Number(_) | Self::Bool(_) => &[],
        }
    }
}

/// Asked of the background verifier.
#[derive(Debug, Clone)]
pub struct VerifyRequest {
    pub provider_id: String,
    pub creds: leviath_runtime::provider_creds::ProviderCreds,
}

/// Answered by the background verifier.
#[derive(Debug, Clone)]
pub struct VerifyReply {
    pub provider_id: String,
    pub outcome: Outcome,
}

/// Where the text being typed goes when it is committed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EditTarget {
    /// The credential of the provider at this index in `providers`.
    Credential(usize),
    /// The field at this index of the current step's fields.
    Field(usize),
}

/// An in-progress text edit.
#[derive(Debug, Clone)]
pub struct Edit {
    pub target: EditTarget,
    /// The shared single-line editor (cursor movement, masking).
    pub(crate) line: crate::tui::widgets::line_edit::LineEdit,
}

/// Why a confirmation dialog is on screen, so its Yes can be routed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConfirmPurpose {
    /// `q`/Ctrl-C with unsaved choices: quit and discard?
    QuitDiscard,
    /// Saving with the Claude Code transport selected: accept the terms risk?
    SaveTos,
    /// Leaving the Providers screen with nothing selected: continue anyway?
    NoProviders,
}

/// A pending confirmation: the dialog plus what its Yes means.
#[derive(Debug, Clone, PartialEq)]
pub struct PendingConfirm {
    pub purpose: ConfirmPurpose,
    pub(crate) dialog: crate::tui::widgets::confirm::Confirm,
}

/// The whole wizard.
pub struct Wizard {
    pub step: Step,
    /// Selected row within the current step.
    pub cursor: usize,
    pub providers: Vec<ProviderRow>,
    /// Which selected provider the credential screen is showing.
    pub detail: usize,
    pub defaults: Vec<Field>,
    pub limits: Vec<Field>,
    pub agents: Vec<AgentRow>,
    pub mcp: Vec<McpRow>,
    pub mcp_scan_errors: Vec<String>,
    pub edit: Option<Edit>,
    /// Show credentials in clear text.
    pub reveal: bool,
    pub show_help: bool,
    /// A confirmation dialog is on screen, and (after Ctrl-C) it is the only
    /// thing keys mean until it is answered.
    pub confirm: Option<PendingConfirm>,
    /// The user has changed something since the wizard opened, so quitting
    /// silently would discard real choices.
    pub dirty: bool,
    /// The user has acknowledged the Claude Code transport's terms risk. A
    /// hard gate on saving: the transport cannot be written to the config
    /// without it, and deselecting the transport withdraws it.
    pub claude_code_tos_accepted: bool,
    pub should_quit: bool,
    /// Set once the plan has been applied, so the loop knows to stop.
    pub finished: bool,
    /// A one-line status message.
    pub message: Option<String>,
    /// The config as loaded *from the file*, which is what the plan is
    /// diffed against and built on.
    pub base: Config,
    /// Credentials present only in the environment. Shown, never written.
    pub env_only: HashMap<&'static str, String>,
    /// Opens a provider's signup page. Injected rather than called directly:
    /// `lev dash` once had a unit test launch a real browser, and this is the
    /// same shape of hazard.
    pub opener: leviath_mcp::BrowserOpener,
    pub verify_tx: mpsc::UnboundedSender<VerifyRequest>,
    verify_rx: Option<mpsc::UnboundedReceiver<VerifyRequest>>,
    reply_tx: mpsc::UnboundedSender<VerifyReply>,
    pub reply_rx: mpsc::UnboundedReceiver<VerifyReply>,
    /// Tick counter, for the spinner.
    pub ticks: u64,
}

/// The environment variables the wizard reports as already-supplying a
/// credential, paired with their provider.
fn env_credentials(lookup: &dyn Fn(&str) -> Option<String>) -> HashMap<&'static str, String> {
    catalog::providers()
        .iter()
        .filter_map(|p| {
            let var = p.env_var?;
            let value = lookup(var)?;
            (!value.is_empty()).then_some((var, value))
        })
        .collect()
}

impl Wizard {
    /// Build the wizard from the config *file* and the surrounding environment.
    ///
    /// `base` must come from reading the file, not from `Config::load()`:
    /// `load` folds `$ANTHROPIC_API_KEY` and friends into the struct, and the
    /// old wizard then re-serialized the whole thing - silently writing a key
    /// the user had deliberately kept in their environment into
    /// `~/.leviath/config.toml`. Environment-supplied credentials are tracked
    /// separately in `env_only` and shown as such.
    pub fn new(
        base: Config,
        env_lookup: &dyn Fn(&str) -> Option<String>,
        candidates: Vec<(String, Candidate)>,
        scan_errors: Vec<String>,
        agents_dir: &std::path::Path,
        opener: leviath_mcp::BrowserOpener,
    ) -> Self {
        let env_only = env_credentials(env_lookup);

        let providers = catalog::providers()
            .into_iter()
            .map(|provider| {
                let stored = catalog::stored_credential(&base, provider.id);
                let from_env = provider
                    .env_var
                    .filter(|v| stored.is_none() && env_only.contains_key(v));
                ProviderRow {
                    selected: catalog::is_configured(&base, provider.id) || from_env.is_some(),
                    value: stored.unwrap_or_default(),
                    from_env,
                    effort: effort_index(base.providers.claude_code_effort.as_deref()),
                    outcome: Outcome::Skipped,
                    checking: false,
                    provider,
                }
            })
            .collect();

        let agents = crate::bundled::plan_agent_actions(agents_dir)
            .into_iter()
            .map(|(agent, action)| AgentRow {
                selected: action.is_change(),
                agent,
                action,
            })
            .collect();

        let mcp = candidates
            .into_iter()
            .map(|(source, candidate)| {
                let collides =
                    import::already_configured(&base.mcp_servers, &candidate.config.name);
                let name = import::dedup_name(&base.mcp_servers, &candidate.config.name);
                McpRow {
                    // A server already configured under this name is offered
                    // unchecked: the user has it, and silently adding a second
                    // copy under a suffixed name is not what "import" means.
                    selected: !collides,
                    source,
                    collides,
                    name,
                    candidate,
                }
            })
            .collect();

        let (verify_tx, verify_rx) = mpsc::unbounded_channel();
        let (reply_tx, reply_rx) = mpsc::unbounded_channel();

        let mut wizard = Self {
            step: Step::Welcome,
            cursor: 0,
            providers,
            detail: 0,
            defaults: Vec::new(),
            limits: limits_fields(&base),
            agents,
            mcp,
            mcp_scan_errors: scan_errors,
            edit: None,
            reveal: false,
            show_help: false,
            confirm: None,
            dirty: false,
            claude_code_tos_accepted: false,
            should_quit: false,
            finished: false,
            message: None,
            base,
            env_only,
            opener,
            verify_tx,
            verify_rx: Some(verify_rx),
            reply_tx,
            reply_rx,
            ticks: 0,
        };
        wizard.rebuild_defaults();
        wizard
    }

    /// Hand the background verifier loop its channel ends. Returns `None` if
    /// already taken.
    pub fn take_verify_ends(
        &mut self,
    ) -> Option<(
        mpsc::UnboundedReceiver<VerifyRequest>,
        mpsc::UnboundedSender<VerifyReply>,
    )> {
        self.verify_rx.take().map(|rx| (rx, self.reply_tx.clone()))
    }

    // ── Rows and navigation ─────────────────────────────────────────────────

    /// Providers the user picked, in table order.
    pub fn selected_providers(&self) -> Vec<usize> {
        self.providers
            .iter()
            .enumerate()
            .filter(|(_, r)| r.selected)
            .map(|(i, _)| i)
            .collect()
    }

    /// The provider row the credential screen is currently showing.
    pub fn detail_row(&self) -> Option<usize> {
        self.selected_providers().get(self.detail).copied()
    }

    /// Whether the Claude Code transport is one of the picked providers.
    pub fn claude_code_selected(&self) -> bool {
        self.providers
            .iter()
            .any(|r| r.selected && r.provider.id == "claude-code")
    }

    /// Whether saving must first ask the user to acknowledge Anthropic's
    /// terms. Enabling the transport routes inference through a subscription
    /// session, so the risk is confirmed once, explicitly, rather than being
    /// buried in a paragraph nobody reads.
    pub fn needs_tos_confirmation(&self) -> bool {
        self.claude_code_selected() && !self.claude_code_tos_accepted
    }

    /// The fields the current step edits, if it edits fields.
    pub fn fields(&self) -> &[Field] {
        match self.step {
            Step::Defaults => &self.defaults,
            Step::Limits => &self.limits,
            _ => &[],
        }
    }

    pub(super) fn fields_mut(&mut self) -> Option<&mut Vec<Field>> {
        match self.step {
            Step::Defaults => Some(&mut self.defaults),
            Step::Limits => Some(&mut self.limits),
            _ => None,
        }
    }

    /// How many selectable rows the current step has.
    pub fn row_count(&self) -> usize {
        match self.step {
            Step::Welcome | Step::Review => 0,
            Step::Providers => self.providers.len(),
            Step::ProviderDetail => usize::from(self.detail_row().is_some()),
            Step::Defaults => self.defaults.len(),
            Step::Limits => self.limits.len(),
            Step::Agents => self.agents.len(),
            Step::Mcp => self.mcp.len(),
        }
    }

    /// How many cursor positions the current step has: its rows plus the
    /// Continue/action button that every step ends with.
    pub fn nav_rows(&self) -> usize {
        self.row_count() + 1
    }

    /// Whether the cursor sits on the step's Continue/action button (the
    /// virtual row after the last real one).
    pub fn on_continue(&self) -> bool {
        self.cursor == self.row_count()
    }

    /// The label of the current step's Continue/action button. It carries
    /// state (selection counts, what screen is next) so advancing is never a
    /// surprise.
    pub fn continue_label(&self) -> String {
        match self.step {
            Step::Welcome => "Get started".to_string(),
            Step::Review => "Apply and finish".to_string(),
            Step::Providers => {
                let count = self.selected_providers().len();
                if count == 0 {
                    "Continue (no providers selected)".to_string()
                } else {
                    format!("Continue: {} ({count} selected)", self.next_step_title())
                }
            }
            Step::ProviderDetail => {
                let selected = self.selected_providers();
                match selected.get(self.detail + 1) {
                    Some(&next) => format!("Next: {}", self.providers[next].provider.display),
                    None => format!("Continue: {}", self.next_step_title()),
                }
            }
            Step::Defaults | Step::Limits | Step::Agents | Step::Mcp => {
                format!("Continue: {}", self.next_step_title())
            }
        }
    }

    /// The title of the step `next_step` would land on.
    fn next_step_title(&self) -> &'static str {
        let mut index = self.step.index();
        while index + 1 < Step::ALL.len() {
            index += 1;
            let step = Step::ALL[index];
            if !self.is_empty_step(step) {
                return step.title();
            }
        }
        Step::Review.title()
    }

    /// Move the selection, clamped to the step's rows plus its button.
    pub fn move_cursor(&mut self, delta: isize) {
        let count = self.nav_rows();
        let next = self.cursor as isize + delta;
        self.cursor = next.clamp(0, count as isize - 1) as usize;
    }

    /// Advance to the next step, skipping ones with nothing to show. Skipping
    /// the credential screen is announced rather than silent: it looks exactly
    /// like a bug when a screen the breadcrumb promises never appears.
    pub fn next_step(&mut self) {
        let mut index = self.step.index();
        while index + 1 < Step::ALL.len() {
            index += 1;
            let step = Step::ALL[index];
            if !self.is_empty_step(step) {
                self.enter(step);
                return;
            }
            if step == Step::ProviderDetail {
                self.message =
                    Some("Skipped Credentials: no selected provider needs setup.".to_string());
            }
        }
        // Past the last step: the Review screen's action is to save.
        self.enter(Step::Review);
    }

    /// Go back a step, skipping empty ones. No-op on the first.
    pub fn prev_step(&mut self) {
        let mut index = self.step.index();
        while index > 0 {
            index -= 1;
            let step = Step::ALL[index];
            if !self.is_empty_step(step) {
                self.enter(step);
                return;
            }
        }
    }

    /// Whether a step has nothing worth showing, and should be skipped.
    ///
    /// Only the two discovery-driven screens can be empty: nobody should have
    /// to press Enter through "no MCP servers found" on a clean machine.
    fn is_empty_step(&self, step: Step) -> bool {
        match step {
            Step::Mcp => self.mcp.is_empty() && self.mcp_scan_errors.is_empty(),
            Step::ProviderDetail => self.detail_row().is_none(),
            _ => false,
        }
    }

    /// Switch to `step`, resetting per-step state.
    pub fn enter(&mut self, step: Step) {
        self.step = step;
        self.cursor = 0;
        self.edit = None;
        if step == Step::Defaults {
            // The model picker is populated by verification, which may have
            // finished since the last visit.
            self.rebuild_defaults();
        }
    }

    /// Within the credential screen, move to the next selected provider;
    /// returns false when there is no next one.
    pub fn next_detail(&mut self) -> bool {
        if self.detail + 1 < self.selected_providers().len() {
            self.detail += 1;
            self.cursor = 0;
            self.edit = None;
            return true;
        }
        false
    }

    /// The reverse of [`Self::next_detail`].
    pub fn prev_detail(&mut self) -> bool {
        if self.detail > 0 {
            self.detail -= 1;
            self.cursor = 0;
            self.edit = None;
            return true;
        }
        false
    }

    // ── Verification ────────────────────────────────────────────────────────

    /// Ask the background verifier about the provider at `index`.
    ///
    /// A provider with nothing to check is left alone rather than queued: a
    /// blank API key would fail with a message about the key rather than saying
    /// the obvious, that none was given.
    pub fn request_verification(&mut self, index: usize) {
        let Some(row) = self.providers.get_mut(index) else {
            return;
        };
        if !row.has_credential() {
            row.outcome = Outcome::Skipped;
            return;
        }
        let id = row.provider.id.to_string();
        let key = if row.value.is_empty() {
            self.env_only
                .get(row.provider.env_var.unwrap_or_default())
                .cloned()
        } else {
            Some(row.value.clone())
        };
        let base_url = (row.provider.credential == Credential::BaseUrl).then(|| {
            if row.value.is_empty() {
                catalog::DEFAULT_OLLAMA_URL.to_string()
            } else {
                row.value.clone()
            }
        });
        row.checking = true;

        let creds = leviath_runtime::provider_creds::ProviderCreds {
            name: id.clone(),
            api_key: base_url.is_none().then_some(key).flatten(),
            base_url,
            model_capabilities: HashMap::new(),
            request_timeout_secs: Some(20),
            rate_limit: None,
            options: HashMap::new(),
        };
        // A closed receiver means the background task is gone; the row simply
        // stays "checking" and nothing else breaks.
        let _ = self.verify_tx.send(VerifyRequest {
            provider_id: id,
            creds,
        });
    }

    /// Ask about every selected provider at once.
    pub fn verify_all(&mut self) {
        for index in self.selected_providers() {
            self.request_verification(index);
        }
    }

    /// Take whatever the background verifier has answered.
    pub fn drain_verifications(&mut self) {
        let mut landed = false;
        while let Ok(reply) = self.reply_rx.try_recv() {
            if let Some(row) = self
                .providers
                .iter_mut()
                .find(|r| r.provider.id == reply.provider_id)
            {
                row.checking = false;
                row.outcome = reply.outcome;
                landed = true;
            }
        }
        // A reply carries the model list, and the picker was built from
        // whatever had arrived when the screen opened. Without this, moving on
        // from a credential and straight into Defaults shows an empty picker
        // for the provider that was verified half a second ago. Rebuilding
        // keeps the current selection, so nothing the user chose is lost.
        if landed && self.step == Step::Defaults {
            self.rebuild_defaults();
        }
    }

    /// Every model id any provider reported, deduplicated, for the picker.
    pub fn discovered_models(&self) -> Vec<String> {
        let mut models: Vec<String> = self
            .providers
            .iter()
            .filter(|r| r.selected)
            .flat_map(|r| r.outcome.models().iter().cloned())
            .collect();
        models.sort();
        models.dedup();
        models
    }

    // ── Forms ───────────────────────────────────────────────────────────────

    /// Rebuild the Defaults screen. Called on entry, since both the provider
    /// list and the discovered models can change between visits.
    pub fn rebuild_defaults(&mut self) {
        let chosen = self.current_default_provider();
        let providers: Vec<String> = self
            .selected_providers()
            .iter()
            .map(|i| self.providers[*i].provider.id.to_string())
            .collect();
        // Fall back to whatever is configured when nothing is selected, so the
        // field is never empty.
        let providers = if providers.is_empty() {
            vec![self.base.default_provider.clone()]
        } else {
            providers
        };
        let index = providers.iter().position(|p| *p == chosen).unwrap_or(0);

        let mut models = vec!["(provider default)".to_string()];
        models.extend(self.discovered_models());
        let current_model = self
            .current_default_model()
            .unwrap_or_else(|| "(provider default)".to_string());
        if !models.contains(&current_model) {
            models.push(current_model.clone());
        }
        let model_index = models
            .iter()
            .position(|m| *m == current_model)
            .unwrap_or_default();

        let timeout = self.current_request_timeout();
        self.defaults = vec![
            Field {
                label: "Default provider",
                help: "Used by any blueprint that allows a user default.",
                value: FieldValue::Choice {
                    options: providers,
                    index,
                },
            },
            Field {
                label: "Default model",
                help: "Filled in from the models your providers reported.",
                value: FieldValue::Choice {
                    options: models,
                    index: model_index,
                },
            },
            Field {
                label: "Request timeout (seconds)",
                help: "How long to wait on one inference. Unset uses the provider default.",
                value: FieldValue::Number(timeout),
            },
        ];
        // Re-pick the concurrency default now that the provider choice is
        // settled. Doing this only on an arrow press missed the commonest
        // Ollama case entirely: when it is the *only* provider selected it is
        // already at index 0, nobody ever presses an arrow, and the limit
        // stayed at the hosted-API default of 8.
        self.apply_provider_concurrency_default();
    }

    /// The default provider as it currently stands in the form, or the base
    /// config's value before the form exists.
    fn current_default_provider(&self) -> String {
        match self.defaults.first().map(|f| &f.value) {
            Some(FieldValue::Choice { options, index }) => match options.get(*index) {
                Some(chosen) => chosen.clone(),
                None => self.base.default_provider.clone(),
            },
            _ => self.base.default_provider.clone(),
        }
    }

    fn current_default_model(&self) -> Option<String> {
        match self.defaults.get(1).map(|f| &f.value) {
            Some(FieldValue::Choice { options, index }) => options.get(*index).cloned(),
            _ => self.base.default_model.clone(),
        }
    }

    fn current_request_timeout(&self) -> Option<u64> {
        match self.defaults.get(2).map(|f| &f.value) {
            Some(FieldValue::Number(n)) => *n,
            _ => self.base.request_timeout_secs,
        }
    }

    /// Set the concurrency default that suits the chosen provider.
    ///
    /// A local Ollama serves one model at a time, so eight concurrent
    /// inferences against it queue and thrash rather than going faster. Only
    /// applied while the field still holds the general default, so a number the
    /// user typed is never overwritten.
    pub fn apply_provider_concurrency_default(&mut self) {
        let ollama = self.current_default_provider() == "ollama";
        let general = Config::default().limits.max_concurrent_inferences;
        let local = Some(catalog::OLLAMA_MAX_CONCURRENT_INFERENCES as u64);
        let general = general.map(|n| n as u64);

        // `limits[0]` is the concurrency field, built as a `Number` by
        // `limits_fields`, so this is a total match rather than a fallible
        // lookup with an arm nothing can reach.
        let Some(FieldValue::Number(current)) = self.limits.first_mut().map(|f| &mut f.value)
        else {
            return;
        };
        if ollama && *current == general {
            *current = local;
        } else if !ollama && *current == local {
            *current = general;
        }
    }

    // ── Confirmations ───────────────────────────────────────────────────────

    /// `q`/Ctrl-C with unsaved choices: ask before discarding them.
    pub fn open_quit_confirm(&mut self) {
        use ratatui::text::Line;
        self.confirm = Some(PendingConfirm {
            purpose: ConfirmPurpose::QuitDiscard,
            dialog: crate::tui::widgets::confirm::Confirm::new(
                "Quit setup?",
                vec![Line::from(
                    "Nothing has been written yet. Your choices so far will be discarded.",
                )],
                "Quit",
                "Stay",
            ),
        });
    }

    /// Saving with the Claude Code transport selected: the terms risk is
    /// confirmed once, explicitly, on a dialog with real buttons.
    pub fn open_tos_confirm(&mut self) {
        use ratatui::text::Line;
        self.confirm = Some(PendingConfirm {
            purpose: ConfirmPurpose::SaveTos,
            dialog: crate::tui::widgets::confirm::Confirm::new(
                "Claude Code terms of service",
                vec![
                    Line::from("Anthropic's terms prohibit third-party developers from offering"),
                    Line::from("claude.ai subscription auth for their products without prior"),
                    Line::from("approval. The Claude Code transport routes inference through"),
                    Line::from("your subscription via the CLI's OAuth session."),
                    Line::from(""),
                    Line::from("For unambiguous compliance, use a direct Anthropic API key."),
                    Line::from(""),
                    Line::from("Accepting means you take responsibility for compliance."),
                ],
                "Accept and save",
                "Cancel",
            )
            .danger(),
        });
    }

    /// Leaving the Providers screen with nothing selected: Leviath cannot run
    /// an agent without a provider, so this is almost always a slip.
    pub fn open_no_providers_confirm(&mut self) {
        use ratatui::text::Line;
        self.confirm = Some(PendingConfirm {
            purpose: ConfirmPurpose::NoProviders,
            dialog: crate::tui::widgets::confirm::Confirm::new(
                "No providers selected",
                vec![
                    Line::from("Without a provider, Leviath cannot run any agent."),
                    Line::from("Select one with Space or Enter, or continue anyway to"),
                    Line::from("configure providers later."),
                ],
                "Continue anyway",
                "Go back",
            ),
        });
    }

    /// Commit an edited text buffer into wherever it belongs.
    pub fn commit_edit(&mut self) {
        let Some(edit) = self.edit.take() else {
            return;
        };
        match edit.target {
            EditTarget::Credential(index) => {
                if let Some(row) = self.providers.get_mut(index) {
                    row.value = edit.line.value().trim().to_string();
                    // A typed credential replaces the environment's, and the
                    // row stops claiming the environment supplies it.
                    if !row.value.is_empty() {
                        row.from_env = None;
                    }
                    row.outcome = Outcome::Skipped;
                }
            }
            EditTarget::Field(index) => {
                let Some(fields) = self.fields_mut() else {
                    return;
                };
                if let Some(field) = fields.get_mut(index) {
                    match &mut field.value {
                        FieldValue::Number(n) => {
                            let trimmed = edit.line.value().trim();
                            *n = if trimmed.is_empty() {
                                None
                            } else {
                                trimmed.parse().ok().or(*n)
                            };
                        }
                        // Booleans and choices are never text-edited.
                        FieldValue::Bool(_) | FieldValue::Choice { .. } => {}
                    }
                }
            }
        }
    }

    // ── Producing the plan ──────────────────────────────────────────────────

    /// Fold every choice into the config that will be written.
    pub fn build_config(&self) -> Config {
        let mut config = self.base.clone();

        for row in &self.providers {
            match row.provider.credential {
                Credential::None => {}
                _ if !row.selected => catalog::set_credential(&mut config, row.provider.id, None),
                // An environment-supplied credential is left out of the file:
                // the user put it in their environment on purpose, and
                // `Config::load` already reads it back from there.
                _ if row.value.is_empty() => {
                    catalog::set_credential(&mut config, row.provider.id, None)
                }
                Credential::BaseUrl if row.value == catalog::DEFAULT_OLLAMA_URL => {
                    // Storing the default would pin it; leaving it unset lets
                    // the built-in default (and `$OLLAMA_HOST`) apply.
                    catalog::set_credential(&mut config, row.provider.id, None)
                }
                _ => catalog::set_credential(&mut config, row.provider.id, Some(row.value.clone())),
            }
        }

        // The transport is always in the table, so this reads its row when
        // selected rather than guarding a lookup that cannot miss.
        let transport = self
            .providers
            .iter()
            .find(|r| r.provider.id == "claude-code")
            .filter(|r| r.selected);
        config.providers.claude_code_enabled = transport.is_some();
        if let Some(row) = transport {
            config.providers.claude_code_effort =
                Some(effort_options()[row.effort.min(effort_options().len() - 1)].to_string());
        }

        config.default_provider = self.current_default_provider();
        config.default_model = self
            .current_default_model()
            .filter(|m| m != "(provider default)");
        config.request_timeout_secs = self.current_request_timeout();

        apply_limits_fields(&mut config, &self.limits);

        for row in self.mcp.iter().filter(|r| r.selected) {
            let mut server = row.candidate.config.clone();
            server.name = row.name.clone();
            config.mcp_servers.push(server);
        }

        config
    }

    /// The plan this wizard describes.
    pub fn build_plan(&self) -> SetupPlan {
        SetupPlan {
            config: self.build_config(),
            agents: self
                .agents
                .iter()
                .filter(|r| r.selected)
                .map(|r| r.agent)
                .collect(),
        }
    }

    /// Lines for the review screen.
    pub fn review_lines(&self) -> Vec<String> {
        let plan = self.build_plan();
        let changes = super::plan::changes(&self.base, &plan);
        if changes.is_empty() {
            vec!["Nothing would change.".to_string()]
        } else {
            changes
        }
    }

    /// MCP rows carrying a credential copied verbatim out of another tool's
    /// config, which importing would duplicate into `~/.leviath/config.toml`.
    pub fn selected_inline_secrets(&self) -> Vec<String> {
        self.mcp
            .iter()
            .filter(|r| r.selected && !r.candidate.inline_secrets.is_empty())
            .map(|r| format!("{}: {}", r.name, r.candidate.inline_secrets.join(", ")))
            .collect()
    }
}

/// Reasoning-effort levels for the Claude Code transport, from the provider
/// rather than re-typed here.
pub fn effort_options() -> &'static [&'static str] {
    &leviath_providers::claude_code::EFFORT_LEVELS
}

/// Index of `effort` in [`effort_options`], defaulting to the provider default.
fn effort_index(effort: Option<&str>) -> usize {
    let wanted = effort.unwrap_or(leviath_providers::claude_code::DEFAULT_EFFORT);
    effort_options()
        .iter()
        .position(|e| *e == wanted)
        .unwrap_or_default()
}

/// The Limits screen's fields, seeded from a config.
fn limits_fields(config: &Config) -> Vec<Field> {
    vec![
        Field {
            label: "Max concurrent inferences",
            help: "How many model calls run at once across all agents.",
            value: FieldValue::Number(config.limits.max_concurrent_inferences.map(|n| n as u64)),
        },
        Field {
            label: "Max concurrent tools",
            help: "How many tool calls run at once within one batch.",
            value: FieldValue::Number(Some(config.limits.max_concurrent_tools as u64)),
        },
        Field {
            label: "Default max iterations",
            help: "Per-stage ceiling when a blueprint sets none.",
            value: FieldValue::Number(config.limits.default_max_iterations.map(|n| n as u64)),
        },
        Field {
            label: "Exact token counting",
            help: "Ask the provider for real token counts instead of estimating. Slower.",
            value: FieldValue::Bool(config.limits.exact_token_counting),
        },
        Field {
            label: "Batch tool-call hint",
            help: "Nudge models to request several tools in one turn.",
            value: FieldValue::Bool(config.batch_tool_hint),
        },
        Field {
            label: "Platform shell hint",
            help: "Tell models what shell they get. Only says anything on Windows (cmd.exe).",
            value: FieldValue::Bool(config.shell_hint),
        },
        Field {
            label: "Stall timeout (seconds)",
            help: "Fail a run that can never dispatch (unconfigured provider). 0 waits forever.",
            value: FieldValue::Number(Some(config.limits.stall_timeout_secs)),
        },
        Field {
            label: "Dead cycles before relief",
            help: "Widen the tool lane after this many 30s cycles with work queued and nothing moving. 0 never does.",
            value: FieldValue::Number(Some(config.limits.dead_cycles_before_relief as u64)),
        },
        Field {
            label: "Finished run retention (seconds)",
            help: "Keep a run in `lev ps` this long after it ends, so a script polling on an interval sees how it ended. 0 drops it at once.",
            value: FieldValue::Number(Some(config.limits.finished_retention_secs)),
        },
        Field {
            label: "Wedge timeout (seconds)",
            help: "Fail a run nothing in the engine can reach any more. 0 is off; 300 is a sensible value.",
            value: FieldValue::Number(Some(config.limits.wedge_timeout_secs)),
        },
        Field {
            label: "Interaction timeout (seconds)",
            help: "Resolve a prompt nobody answered after this long, so the run carries on. 0 waits for ever.",
            value: FieldValue::Number(Some(config.limits.interaction_timeout_secs)),
        },
    ]
}

/// Write the Limits screen's fields back into a config.
fn apply_limits_fields(config: &mut Config, fields: &[Field]) {
    for (index, field) in fields.iter().enumerate() {
        match (index, &field.value) {
            (0, FieldValue::Number(n)) => {
                config.limits.max_concurrent_inferences = n.map(|n| n as usize)
            }
            // A zero here would deadlock every tool batch, so an explicit unset
            // or 0 falls back to the default rather than being stored.
            (1, FieldValue::Number(n)) => {
                config.limits.max_concurrent_tools = n
                    .filter(|n| *n > 0)
                    .map(|n| n as usize)
                    .unwrap_or(Config::default().limits.max_concurrent_tools)
            }
            (2, FieldValue::Number(n)) => {
                config.limits.default_max_iterations = n.map(|n| n as usize)
            }
            (3, FieldValue::Bool(b)) => config.limits.exact_token_counting = *b,
            (4, FieldValue::Bool(b)) => config.batch_tool_hint = *b,
            (5, FieldValue::Bool(b)) => config.shell_hint = *b,
            // Unset means "leave the watchdog at its default", not "disable it";
            // disabling is an explicit 0.
            (6, FieldValue::Number(n)) => {
                config.limits.stall_timeout_secs =
                    n.unwrap_or(Config::default().limits.stall_timeout_secs)
            }
            // Same rule: unset keeps the default, 0 is an explicit "never".
            (7, FieldValue::Number(n)) => {
                config.limits.dead_cycles_before_relief = n
                    .map(|n| n as u32)
                    .unwrap_or(Config::default().limits.dead_cycles_before_relief)
            }
            // And again: unset keeps the default, 0 means keep nothing.
            (8, FieldValue::Number(n)) => {
                config.limits.finished_retention_secs =
                    n.unwrap_or(Config::default().limits.finished_retention_secs)
            }
            // Same rule once more, and here the default is itself 0 (off).
            (9, FieldValue::Number(n)) => {
                config.limits.wedge_timeout_secs =
                    n.unwrap_or(Config::default().limits.wedge_timeout_secs)
            }
            // Same rule again: unset keeps the default hour, 0 is an explicit
            // "wait for a person however long it takes".
            (10, FieldValue::Number(n)) => {
                config.limits.interaction_timeout_secs =
                    n.unwrap_or(Config::default().limits.interaction_timeout_secs)
            }
            _ => {}
        }
    }
}

/// Merge every scan into the flat `(source, candidate)` list the wizard takes,
/// alongside the human-readable errors.
pub fn candidates_from_scans(scans: Vec<import::Scan>) -> (Vec<(String, Candidate)>, Vec<String>) {
    let mut candidates = Vec::new();
    let mut errors = Vec::new();
    for scan in scans {
        match scan.result {
            Ok(found) => candidates.extend(
                found
                    .into_iter()
                    .map(|c| (scan.source.display.to_string(), c)),
            ),
            Err(message) => errors.push(format!("{}: {message}", scan.source.display)),
        }
    }
    (candidates, errors)
}

/// Build an [`MCPServerConfig`] list from selected rows. Exposed for tests and
/// for any future non-terminal front-end.
pub fn selected_servers(rows: &[McpRow]) -> Vec<MCPServerConfig> {
    rows.iter()
        .filter(|r| r.selected)
        .map(|r| {
            let mut server = r.candidate.config.clone();
            server.name = r.name.clone();
            server
        })
        .collect()
}

#[cfg(test)]
pub(super) mod tests {
    use super::*;
    use crate::bundled::BUNDLED_AGENTS;

    /// A wizard over tempdirs and a fixed environment, with a browser opener
    /// that records rather than launches.
    pub(in crate::commands::setup) fn test_wizard(agents_dir: &std::path::Path) -> Wizard {
        Wizard::new(
            Config::default(),
            &|_| None,
            Vec::new(),
            Vec::new(),
            agents_dir,
            std::sync::Arc::new(|_| true),
        )
    }

    fn candidate(name: &str) -> Candidate {
        Candidate {
            config: MCPServerConfig::stdio(name, "npx", vec![]),
            scope: String::new(),
            inline_secrets: Vec::new(),
        }
    }

    // ─── Step ───────────────────────────────────────────────────────────────

    #[test]
    fn every_step_is_titled_and_ordered() {
        for (index, step) in Step::ALL.iter().enumerate() {
            assert!(!step.title().is_empty(), "{step:?} has no title");
            assert_eq!(step.index(), index);
        }
    }

    // ─── construction ───────────────────────────────────────────────────────

    #[test]
    fn a_fresh_install_starts_with_nothing_selected_and_every_agent_queued() {
        let dir = tempfile::tempdir().unwrap();

        let wizard = test_wizard(dir.path());

        assert_eq!(wizard.step, Step::Welcome);
        assert!(wizard.selected_providers().is_empty());
        assert_eq!(wizard.agents.len(), BUNDLED_AGENTS.len());
        assert!(
            wizard.agents.iter().all(|r| r.selected),
            "a fresh install should offer to install everything"
        );
        assert!(
            wizard
                .agents
                .iter()
                .all(|r| r.action == AgentAction::Install)
        );
    }

    #[test]
    fn already_installed_agents_are_listed_but_not_reselected() {
        let dir = tempfile::tempdir().unwrap();
        for agent in BUNDLED_AGENTS {
            crate::bundled::install_bundled(agent, dir.path()).unwrap();
        }

        let wizard = test_wizard(dir.path());

        assert!(
            wizard.agents.iter().all(|r| !r.selected),
            "nothing needs doing, so nothing should be pre-checked"
        );
    }

    #[test]
    fn a_configured_provider_starts_selected_with_its_credential() {
        let dir = tempfile::tempdir().unwrap();
        let base = Config {
            providers: crate::config::ProviderConfig {
                anthropic_api_key: Some("sk-ant-stored".to_string()),
                ..Config::default().providers
            },
            ..Config::default()
        };

        let wizard = Wizard::new(
            base,
            &|_| None,
            Vec::new(),
            Vec::new(),
            dir.path(),
            std::sync::Arc::new(|_| true),
        );

        let row = wizard
            .providers
            .iter()
            .find(|r| r.provider.id == "anthropic")
            .expect("anthropic is in the table");
        assert!(row.selected);
        assert_eq!(row.value, "sk-ant-stored");
        assert!(row.from_env.is_none());
    }

    #[test]
    fn a_key_that_lives_only_in_the_environment_is_shown_and_never_written() {
        // The bug this closes: `Config::load` folds env keys into the struct,
        // so a wizard that re-serializes the whole thing silently writes a key
        // the user deliberately kept in their environment into
        // ~/.leviath/config.toml.
        let dir = tempfile::tempdir().unwrap();

        let wizard = Wizard::new(
            Config::default(),
            &|name| (name == "ANTHROPIC_API_KEY").then(|| "sk-ant-from-env".to_string()),
            Vec::new(),
            Vec::new(),
            dir.path(),
            std::sync::Arc::new(|_| true),
        );

        let row = wizard
            .providers
            .iter()
            .find(|r| r.provider.id == "anthropic")
            .expect("anthropic is in the table");
        assert!(row.selected, "the provider is usable, so it is selected");
        assert_eq!(row.from_env, Some("ANTHROPIC_API_KEY"));
        assert!(row.value.is_empty());

        let written = wizard.build_config();
        assert!(
            written.providers.anthropic_api_key.is_none(),
            "an environment-supplied key must not be copied into the config"
        );
    }

    #[test]
    fn a_stored_key_wins_over_the_environment() {
        // Both present: the file is what setup is editing, so that is what is
        // shown and kept.
        let dir = tempfile::tempdir().unwrap();
        let base = Config {
            providers: crate::config::ProviderConfig {
                anthropic_api_key: Some("sk-ant-stored".to_string()),
                ..Config::default().providers
            },
            ..Config::default()
        };

        let wizard = Wizard::new(
            base,
            &|_| Some("sk-ant-from-env".to_string()),
            Vec::new(),
            Vec::new(),
            dir.path(),
            std::sync::Arc::new(|_| true),
        );

        let row = &wizard.providers[0];
        assert!(row.from_env.is_none());
        assert_eq!(row.value, "sk-ant-stored");
    }

    #[test]
    fn an_empty_environment_variable_does_not_count_as_a_credential() {
        let dir = tempfile::tempdir().unwrap();

        let wizard = Wizard::new(
            Config::default(),
            &|_| Some(String::new()),
            Vec::new(),
            Vec::new(),
            dir.path(),
            std::sync::Arc::new(|_| true),
        );

        assert!(wizard.env_only.is_empty());
        assert!(wizard.selected_providers().is_empty());
    }

    // ─── MCP rows ───────────────────────────────────────────────────────────

    #[test]
    fn an_importable_server_is_preselected_and_named_as_found() {
        let dir = tempfile::tempdir().unwrap();

        let wizard = Wizard::new(
            Config::default(),
            &|_| None,
            vec![("Claude Code".to_string(), candidate("fs"))],
            Vec::new(),
            dir.path(),
            std::sync::Arc::new(|_| true),
        );

        assert_eq!(wizard.mcp.len(), 1);
        assert!(wizard.mcp[0].selected);
        assert!(!wizard.mcp[0].collides);
        assert_eq!(wizard.mcp[0].name, "fs");
        assert_eq!(wizard.mcp[0].source, "Claude Code");
    }

    #[test]
    fn a_server_already_configured_is_offered_unchecked_under_a_free_name() {
        // The user already has it. Silently adding a second copy under a
        // suffixed name is not what "import" means.
        let dir = tempfile::tempdir().unwrap();
        let base = Config {
            mcp_servers: vec![MCPServerConfig::stdio("fs", "npx", vec![])],
            ..Config::default()
        };

        let wizard = Wizard::new(
            base,
            &|_| None,
            vec![("Cursor".to_string(), candidate("fs"))],
            Vec::new(),
            dir.path(),
            std::sync::Arc::new(|_| true),
        );

        assert!(!wizard.mcp[0].selected);
        assert!(wizard.mcp[0].collides);
        assert_eq!(wizard.mcp[0].name, "fs-2");

        // Selecting it anyway stores it under the free name, leaving the
        // original alone.
        let mut wizard = wizard;
        wizard.mcp[0].selected = true;
        let config = wizard.build_config();
        let names: Vec<&str> = config.mcp_servers.iter().map(|s| s.name.as_str()).collect();
        assert_eq!(names, vec!["fs", "fs-2"]);
    }

    #[test]
    fn selected_servers_renames_and_filters() {
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = Wizard::new(
            Config::default(),
            &|_| None,
            vec![
                ("A".to_string(), candidate("keep")),
                ("B".to_string(), candidate("drop")),
            ],
            Vec::new(),
            dir.path(),
            std::sync::Arc::new(|_| true),
        );
        wizard.mcp[1].selected = false;
        wizard.mcp[0].name = "renamed".to_string();

        let servers = selected_servers(&wizard.mcp);

        assert_eq!(servers.len(), 1);
        assert_eq!(servers[0].name, "renamed");
    }

    #[test]
    fn inline_secrets_are_reported_only_for_selected_rows() {
        let dir = tempfile::tempdir().unwrap();
        let mut secretive = candidate("leaky");
        secretive.inline_secrets = vec!["API_TOKEN".to_string()];

        let mut wizard = Wizard::new(
            Config::default(),
            &|_| None,
            vec![
                ("A".to_string(), secretive),
                ("B".to_string(), candidate("clean")),
            ],
            Vec::new(),
            dir.path(),
            std::sync::Arc::new(|_| true),
        );

        assert_eq!(wizard.selected_inline_secrets(), vec!["leaky: API_TOKEN"]);
        wizard.mcp[0].selected = false;
        assert!(wizard.selected_inline_secrets().is_empty());
    }

    // ─── navigation ─────────────────────────────────────────────────────────

    #[test]
    fn the_cursor_stays_inside_the_current_step() {
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = test_wizard(dir.path());
        wizard.enter(Step::Providers);

        wizard.move_cursor(-5);
        assert_eq!(wizard.cursor, 0);
        wizard.move_cursor(100);
        assert_eq!(
            wizard.cursor,
            wizard.providers.len(),
            "clamped to the Continue button after the last row"
        );
        assert!(wizard.on_continue());
    }

    #[test]
    fn a_step_with_no_rows_pins_the_cursor_at_zero() {
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = test_wizard(dir.path());
        wizard.enter(Step::Welcome);
        wizard.cursor = 4;

        wizard.move_cursor(1);

        assert_eq!(wizard.cursor, 0);
        assert_eq!(wizard.row_count(), 0);
    }

    #[test]
    fn the_continue_label_names_where_it_goes() {
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = test_wizard(dir.path());

        wizard.enter(Step::Welcome);
        assert_eq!(wizard.continue_label(), "Get started");

        wizard.enter(Step::Providers);
        assert_eq!(wizard.continue_label(), "Continue (no providers selected)");
        wizard.providers[0].selected = true;
        wizard.providers[1].selected = true;
        assert_eq!(
            wizard.continue_label(),
            "Continue: Credentials (2 selected)"
        );

        // On the credential walk: the next selected provider, then the next step.
        wizard.enter(Step::ProviderDetail);
        assert_eq!(
            wizard.continue_label(),
            format!("Next: {}", wizard.providers[1].provider.display)
        );
        wizard.detail = 1;
        assert_eq!(wizard.continue_label(), "Continue: Defaults");

        wizard.enter(Step::Limits);
        assert_eq!(wizard.continue_label(), "Continue: Agents");

        wizard.enter(Step::Review);
        assert_eq!(wizard.continue_label(), "Apply and finish");
    }

    #[test]
    fn next_step_title_past_the_last_step_falls_back_to_review() {
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = test_wizard(dir.path());
        wizard.enter(Step::Review);
        assert_eq!(wizard.next_step_title(), "Review");
    }

    #[test]
    fn empty_discovery_steps_are_skipped_in_both_directions() {
        // Nobody should have to press Enter through "no MCP servers found" on a
        // clean machine, or through a credentials screen with no providers
        // picked.
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = test_wizard(dir.path());
        assert!(wizard.mcp.is_empty());

        wizard.enter(Step::Providers);
        wizard.next_step();
        assert_eq!(wizard.step, Step::Defaults, "credentials screen was empty");

        wizard.enter(Step::Agents);
        wizard.next_step();
        assert_eq!(wizard.step, Step::Review, "MCP screen was empty");

        wizard.prev_step();
        assert_eq!(wizard.step, Step::Agents);
    }

    #[test]
    fn a_nonempty_discovery_step_is_visited() {
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = Wizard::new(
            Config::default(),
            &|_| None,
            vec![("A".to_string(), candidate("fs"))],
            Vec::new(),
            dir.path(),
            std::sync::Arc::new(|_| true),
        );

        wizard.enter(Step::Agents);
        wizard.next_step();

        assert_eq!(wizard.step, Step::Mcp);
    }

    #[test]
    fn a_scan_error_alone_is_enough_to_show_the_mcp_step() {
        // "We couldn't read your Zed config" is worth a screen even with no
        // servers to import.
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = Wizard::new(
            Config::default(),
            &|_| None,
            Vec::new(),
            vec!["Zed: unreadable".to_string()],
            dir.path(),
            std::sync::Arc::new(|_| true),
        );

        wizard.enter(Step::Agents);
        wizard.next_step();

        assert_eq!(wizard.step, Step::Mcp);
    }

    #[test]
    fn the_first_step_has_nowhere_to_go_back_to() {
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = test_wizard(dir.path());

        wizard.prev_step();

        assert_eq!(wizard.step, Step::Welcome);
    }

    #[test]
    fn advancing_past_the_last_step_stays_on_review() {
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = test_wizard(dir.path());
        wizard.enter(Step::Review);

        wizard.next_step();

        assert_eq!(wizard.step, Step::Review);
    }

    #[test]
    fn the_credential_screen_walks_the_selected_providers() {
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = test_wizard(dir.path());
        wizard.providers[0].selected = true;
        wizard.providers[1].selected = true;

        assert_eq!(wizard.detail_row(), Some(0));
        assert!(wizard.next_detail());
        assert_eq!(wizard.detail_row(), Some(1));
        assert!(!wizard.next_detail(), "there is no third provider");
        assert!(wizard.prev_detail());
        assert_eq!(wizard.detail_row(), Some(0));
        assert!(!wizard.prev_detail());
    }

    #[test]
    fn the_credential_screen_has_no_row_when_nothing_is_selected() {
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = test_wizard(dir.path());
        wizard.enter(Step::ProviderDetail);

        assert!(wizard.detail_row().is_none());
        assert_eq!(wizard.row_count(), 0);
    }

    // ─── verification ───────────────────────────────────────────────────────

    #[tokio::test]
    async fn verification_is_requested_for_a_provider_with_a_credential() {
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = test_wizard(dir.path());
        let (mut requests, _replies) = wizard.take_verify_ends().expect("first take");
        wizard.providers[0].selected = true;
        wizard.providers[0].value = "sk-ant-x".to_string();

        wizard.request_verification(0);

        assert!(wizard.providers[0].checking);
        let request = requests.try_recv().expect("a request was queued");
        assert_eq!(request.provider_id, "anthropic");
        assert_eq!(request.creds.api_key.as_deref(), Some("sk-ant-x"));
    }

    #[tokio::test]
    async fn a_blank_api_key_is_not_queued_for_checking() {
        // Failing with "check the key" when none was given says nothing useful.
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = test_wizard(dir.path());
        let (mut requests, _replies) = wizard.take_verify_ends().expect("first take");
        wizard.providers[0].selected = true;

        wizard.request_verification(0);

        assert!(!wizard.providers[0].checking);
        assert_eq!(wizard.providers[0].outcome, Outcome::Skipped);
        assert!(requests.try_recv().is_err());
    }

    #[tokio::test]
    async fn an_environment_supplied_key_is_what_gets_checked() {
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = Wizard::new(
            Config::default(),
            &|name| (name == "ANTHROPIC_API_KEY").then(|| "sk-ant-env".to_string()),
            Vec::new(),
            Vec::new(),
            dir.path(),
            std::sync::Arc::new(|_| true),
        );
        let (mut requests, _replies) = wizard.take_verify_ends().expect("first take");

        wizard.request_verification(0);

        let request = requests.try_recv().expect("a request was queued");
        assert_eq!(request.creds.api_key.as_deref(), Some("sk-ant-env"));
    }

    #[tokio::test]
    async fn ollama_is_checked_by_url_with_no_key() {
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = test_wizard(dir.path());
        let (mut requests, _replies) = wizard.take_verify_ends().expect("first take");
        let index = wizard
            .providers
            .iter()
            .position(|r| r.provider.id == "ollama")
            .expect("ollama is offered");

        wizard.request_verification(index);
        let request = requests.try_recv().expect("a request was queued");
        assert!(request.creds.api_key.is_none());
        assert_eq!(
            request.creds.base_url.as_deref(),
            Some(catalog::DEFAULT_OLLAMA_URL),
            "an empty field means the default endpoint"
        );

        wizard.providers[index].value = "http://box:11434".to_string();
        wizard.request_verification(index);
        let request = requests.try_recv().expect("a second request was queued");
        assert_eq!(request.creds.base_url.as_deref(), Some("http://box:11434"));
    }

    #[tokio::test]
    async fn verify_all_covers_every_selected_provider() {
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = test_wizard(dir.path());
        let (mut requests, _replies) = wizard.take_verify_ends().expect("first take");
        wizard.providers[0].selected = true;
        wizard.providers[0].value = "sk-ant".to_string();
        let ollama = wizard
            .providers
            .iter()
            .position(|r| r.provider.id == "ollama")
            .expect("ollama is offered");
        wizard.providers[ollama].selected = true;

        wizard.verify_all();

        let mut seen = Vec::new();
        while let Ok(request) = requests.try_recv() {
            seen.push(request.provider_id);
        }
        assert_eq!(seen, vec!["anthropic", "ollama"]);
    }

    #[tokio::test]
    async fn an_out_of_range_verification_request_is_a_no_op() {
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = test_wizard(dir.path());
        let (mut requests, _replies) = wizard.take_verify_ends().expect("first take");

        wizard.request_verification(999);

        assert!(requests.try_recv().is_err());
    }

    #[tokio::test]
    async fn replies_land_on_the_right_provider_and_feed_the_model_picker() {
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = test_wizard(dir.path());
        let (_requests, replies) = wizard.take_verify_ends().expect("first take");
        wizard.providers[0].selected = true;
        wizard.providers[0].checking = true;

        replies
            .send(VerifyReply {
                provider_id: "anthropic".to_string(),
                outcome: Outcome::Reachable {
                    models: vec!["claude-opus-5".to_string()],
                },
            })
            .unwrap();
        // A reply for something not in the table is ignored rather than panicking.
        replies
            .send(VerifyReply {
                provider_id: "not-a-provider".to_string(),
                outcome: Outcome::Skipped,
            })
            .unwrap();
        wizard.drain_verifications();

        assert!(!wizard.providers[0].checking);
        assert_eq!(wizard.discovered_models(), vec!["claude-opus-5"]);
    }

    #[tokio::test]
    async fn a_late_reply_refills_the_model_picker() {
        // Moving straight from a credential into Defaults gets there before the
        // check comes back, so the picker was built from an empty model list
        // and stayed that way - caught by driving the real TUI against a live
        // API key.
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = test_wizard(dir.path());
        let (_requests, replies) = wizard.take_verify_ends().expect("first take");
        wizard.providers[0].selected = true;
        wizard.enter(Step::Defaults);
        assert_eq!(
            wizard.defaults[1].value.options(),
            ["(provider default)".to_string()],
            "nothing has been reported yet"
        );

        replies
            .send(VerifyReply {
                provider_id: "anthropic".to_string(),
                outcome: Outcome::Reachable {
                    models: vec!["claude-opus-5".to_string()],
                },
            })
            .unwrap();
        wizard.drain_verifications();

        assert!(
            wizard.defaults[1]
                .value
                .options()
                .contains(&"claude-opus-5".to_string()),
            "the picker should have refilled"
        );
    }

    #[tokio::test]
    async fn a_late_reply_does_not_disturb_another_screen() {
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = test_wizard(dir.path());
        let (_requests, replies) = wizard.take_verify_ends().expect("first take");
        wizard.providers[0].selected = true;
        wizard.enter(Step::Limits);
        wizard.limits[0].value = FieldValue::Number(Some(3));

        replies
            .send(VerifyReply {
                provider_id: "anthropic".to_string(),
                outcome: Outcome::Reachable {
                    models: vec!["m".to_string()],
                },
            })
            .unwrap();
        wizard.drain_verifications();

        assert_eq!(wizard.limits[0].value, FieldValue::Number(Some(3)));
    }

    #[test]
    fn the_verification_channel_ends_can_only_be_taken_once() {
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = test_wizard(dir.path());

        assert!(wizard.take_verify_ends().is_some());
        assert!(wizard.take_verify_ends().is_none());
    }

    #[test]
    fn models_from_unselected_providers_are_not_offered() {
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = test_wizard(dir.path());
        wizard.providers[0].outcome = Outcome::Reachable {
            models: vec!["hidden".to_string()],
        };

        assert!(wizard.discovered_models().is_empty());
    }

    // ─── forms ──────────────────────────────────────────────────────────────

    #[test]
    fn the_provider_choice_is_a_radio_over_what_was_actually_selected() {
        // A free-text prompt lets a typo through and only fails at the
        // first agent run.
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = test_wizard(dir.path());
        let ollama = wizard
            .providers
            .iter()
            .position(|r| r.provider.id == "ollama")
            .expect("ollama is offered");
        wizard.providers[ollama].selected = true;
        wizard.enter(Step::Defaults);

        assert_eq!(wizard.defaults[0].value.options(), ["ollama".to_string()]);
    }

    #[test]
    fn the_provider_choice_falls_back_to_the_configured_one_when_nothing_is_picked() {
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = test_wizard(dir.path());
        wizard.enter(Step::Defaults);

        assert_eq!(
            wizard.defaults[0].value.display(),
            Config::default().default_provider
        );
    }

    #[test]
    fn the_model_picker_is_filled_from_verification_and_keeps_a_stored_value() {
        let dir = tempfile::tempdir().unwrap();
        let base = Config {
            default_model: Some("hand-typed".to_string()),
            ..Config::default()
        };
        let mut wizard = Wizard::new(
            base,
            &|_| None,
            Vec::new(),
            Vec::new(),
            dir.path(),
            std::sync::Arc::new(|_| true),
        );
        wizard.providers[0].selected = true;
        wizard.providers[0].outcome = Outcome::Reachable {
            models: vec!["claude-opus-5".to_string()],
        };

        wizard.enter(Step::Defaults);

        let options = wizard.defaults[1].value.options();
        assert!(options.contains(&"(provider default)".to_string()));
        assert!(options.contains(&"claude-opus-5".to_string()));
        assert_eq!(
            wizard.defaults[1].value.display(),
            "hand-typed",
            "a model already in the config must survive"
        );
    }

    #[test]
    fn only_a_choice_field_has_options() {
        assert_eq!(
            FieldValue::Choice {
                options: vec!["a".into()],
                index: 0
            }
            .options(),
            ["a".to_string()]
        );
        assert!(FieldValue::Number(Some(1)).options().is_empty());
        assert!(FieldValue::Bool(true).options().is_empty());
    }

    #[test]
    fn field_values_read_naturally() {
        assert_eq!(FieldValue::Number(None).display(), "(unset)");
        assert_eq!(FieldValue::Number(Some(7)).display(), "7");
        assert_eq!(FieldValue::Bool(true).display(), "yes");
        assert_eq!(FieldValue::Bool(false).display(), "no");
        assert_eq!(
            FieldValue::Choice {
                options: vec!["a".into()],
                index: 0
            }
            .display(),
            "a"
        );
        assert_eq!(
            FieldValue::Choice {
                options: vec![],
                index: 0
            }
            .display(),
            "(none)"
        );
    }

    #[test]
    fn picking_ollama_drops_the_concurrency_default_to_one() {
        // A local box serves one model at a time; eight concurrent inferences
        // against one Ollama instance queue and thrash rather than going faster.
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = test_wizard(dir.path());
        let ollama = wizard
            .providers
            .iter()
            .position(|r| r.provider.id == "ollama")
            .expect("ollama is offered");
        wizard.providers[ollama].selected = true;
        wizard.enter(Step::Defaults);

        wizard.apply_provider_concurrency_default();

        assert_eq!(
            wizard.limits[0].value,
            FieldValue::Number(Some(catalog::OLLAMA_MAX_CONCURRENT_INFERENCES as u64))
        );
    }

    #[test]
    fn ollama_as_the_only_provider_still_lowers_the_concurrency_limit() {
        // Regression: re-picking the default only when an arrow key moves the
        // provider choice misses this case. With Ollama the sole selection it
        // is already at index 0, no arrow is ever pressed, and the limit stays
        // at the hosted-API default of 8 - caught by driving the real TUI.
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = test_wizard(dir.path());
        let ollama = wizard
            .providers
            .iter()
            .position(|r| r.provider.id == "ollama")
            .expect("ollama is offered");
        wizard.providers[ollama].selected = true;

        wizard.enter(Step::Defaults);

        assert_eq!(wizard.defaults[0].value.display(), "ollama");
        assert_eq!(
            wizard.build_config().limits.max_concurrent_inferences,
            Some(catalog::OLLAMA_MAX_CONCURRENT_INFERENCES)
        );
    }

    #[test]
    fn switching_back_off_ollama_restores_the_general_default() {
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = test_wizard(dir.path());
        let ollama = wizard
            .providers
            .iter()
            .position(|r| r.provider.id == "ollama")
            .expect("ollama is offered");
        wizard.providers[ollama].selected = true;
        wizard.enter(Step::Defaults);
        wizard.apply_provider_concurrency_default();

        wizard.providers[ollama].selected = false;
        wizard.providers[0].selected = true;
        wizard.rebuild_defaults();
        wizard.apply_provider_concurrency_default();

        assert_eq!(
            wizard.limits[0].value,
            FieldValue::Number(
                Config::default()
                    .limits
                    .max_concurrent_inferences
                    .map(|n| n as u64)
            )
        );
    }

    #[test]
    fn a_hand_typed_concurrency_is_never_overwritten() {
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = test_wizard(dir.path());
        let ollama = wizard
            .providers
            .iter()
            .position(|r| r.provider.id == "ollama")
            .expect("ollama is offered");
        wizard.providers[ollama].selected = true;
        wizard.enter(Step::Defaults);
        wizard.limits[0].value = FieldValue::Number(Some(3));

        wizard.apply_provider_concurrency_default();

        assert_eq!(wizard.limits[0].value, FieldValue::Number(Some(3)));
    }

    // ─── editing ────────────────────────────────────────────────────────────

    #[test]
    fn committing_a_credential_clears_its_stale_verification() {
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = test_wizard(dir.path());
        wizard.providers[0].outcome = Outcome::Reachable {
            models: vec!["m".into()],
        };
        wizard.edit = Some(Edit {
            target: EditTarget::Credential(0),
            line: crate::tui::widgets::line_edit::LineEdit::new("  sk-ant-new  ".to_string(), true),
        });

        wizard.commit_edit();

        assert_eq!(wizard.providers[0].value, "sk-ant-new");
        assert_eq!(
            wizard.providers[0].outcome,
            Outcome::Skipped,
            "the old result was for a different key"
        );
        assert!(wizard.edit.is_none());
    }

    #[test]
    fn typing_a_credential_supersedes_the_environments() {
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = Wizard::new(
            Config::default(),
            &|_| Some("sk-ant-env".to_string()),
            Vec::new(),
            Vec::new(),
            dir.path(),
            std::sync::Arc::new(|_| true),
        );
        assert!(wizard.providers[0].from_env.is_some());
        wizard.edit = Some(Edit {
            target: EditTarget::Credential(0),
            line: crate::tui::widgets::line_edit::LineEdit::new("sk-ant-typed".to_string(), true),
        });

        wizard.commit_edit();

        assert!(wizard.providers[0].from_env.is_none());
        assert_eq!(
            wizard.build_config().providers.anthropic_api_key.as_deref(),
            Some("sk-ant-typed")
        );
    }

    #[test]
    fn committing_numbers_handles_blank_and_unparseable_input() {
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = test_wizard(dir.path());
        wizard.enter(Step::Limits);

        wizard.edit = Some(Edit {
            target: EditTarget::Field(0),
            line: crate::tui::widgets::line_edit::LineEdit::new("16".to_string(), false),
        });
        wizard.commit_edit();
        assert_eq!(wizard.limits[0].value, FieldValue::Number(Some(16)));

        // Garbage keeps the previous value rather than silently unsetting it.
        wizard.edit = Some(Edit {
            target: EditTarget::Field(0),
            line: crate::tui::widgets::line_edit::LineEdit::new("not a number".to_string(), false),
        });
        wizard.commit_edit();
        assert_eq!(wizard.limits[0].value, FieldValue::Number(Some(16)));

        // Blank means unset, which is a real and different choice.
        wizard.edit = Some(Edit {
            target: EditTarget::Field(0),
            line: crate::tui::widgets::line_edit::LineEdit::new("   ".to_string(), false),
        });
        wizard.commit_edit();
        assert_eq!(wizard.limits[0].value, FieldValue::Number(None));
    }

    #[test]
    fn committing_with_nothing_open_or_out_of_range_is_a_no_op() {
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = test_wizard(dir.path());
        wizard.commit_edit();

        wizard.edit = Some(Edit {
            target: EditTarget::Credential(999),
            line: crate::tui::widgets::line_edit::LineEdit::new("x".to_string(), false),
        });
        wizard.commit_edit();

        wizard.enter(Step::Limits);
        wizard.edit = Some(Edit {
            target: EditTarget::Field(999),
            line: crate::tui::widgets::line_edit::LineEdit::new("x".to_string(), false),
        });
        wizard.commit_edit();

        // A step with no fields at all.
        wizard.enter(Step::Welcome);
        wizard.edit = Some(Edit {
            target: EditTarget::Field(0),
            line: crate::tui::widgets::line_edit::LineEdit::new("x".to_string(), false),
        });
        wizard.commit_edit();

        assert!(wizard.edit.is_none());
    }

    #[test]
    fn every_step_reports_a_sensible_row_count() {
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = Wizard::new(
            Config::default(),
            &|_| None,
            vec![("A".to_string(), candidate("fs"))],
            Vec::new(),
            dir.path(),
            std::sync::Arc::new(|_| true),
        );
        wizard.providers[0].selected = true;

        for step in Step::ALL {
            wizard.enter(step);
            let rows = wizard.row_count();
            match step {
                Step::Welcome | Step::Review => assert_eq!(rows, 0, "{step:?}"),
                _ => assert!(rows > 0, "{step:?} has no rows"),
            }
            // Fields exist for exactly the two form screens.
            let fields = wizard.fields().len();
            match step {
                Step::Defaults | Step::Limits => assert_eq!(fields, rows, "{step:?}"),
                _ => assert_eq!(fields, 0, "{step:?} should have no fields"),
            }
        }
    }

    #[test]
    fn committing_onto_a_defaults_field_reaches_that_form_too() {
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = test_wizard(dir.path());
        wizard.providers[0].selected = true;
        wizard.enter(Step::Defaults);

        wizard.edit = Some(Edit {
            target: EditTarget::Field(2),
            line: crate::tui::widgets::line_edit::LineEdit::new("45".to_string(), false),
        });
        wizard.commit_edit();

        assert_eq!(wizard.defaults[2].value, FieldValue::Number(Some(45)));
        assert_eq!(wizard.build_config().request_timeout_secs, Some(45));
    }

    #[test]
    fn clearing_a_credential_leaves_the_environment_marker_alone() {
        // Blanking the field is how a user says "use what's in my environment".
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = Wizard::new(
            Config::default(),
            &|_| Some("sk-ant-env".to_string()),
            Vec::new(),
            Vec::new(),
            dir.path(),
            std::sync::Arc::new(|_| true),
        );
        wizard.edit = Some(Edit {
            target: EditTarget::Credential(0),
            line: crate::tui::widgets::line_edit::LineEdit::new("   ".to_string(), true),
        });

        wizard.commit_edit();

        assert!(wizard.providers[0].value.is_empty());
        assert_eq!(wizard.providers[0].from_env, Some("ANTHROPIC_API_KEY"));
    }

    #[test]
    fn a_defaults_form_with_no_choice_field_falls_back_to_the_base_config() {
        // Defensive: a future reorder must not silently drop the setting.
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = test_wizard(dir.path());
        wizard.defaults[0].value = FieldValue::Bool(true);

        assert_eq!(
            wizard.build_config().default_provider,
            Config::default().default_provider
        );
    }

    #[test]
    fn an_empty_choice_list_falls_back_to_the_base_config() {
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = test_wizard(dir.path());
        wizard.defaults[0].value = FieldValue::Choice {
            options: Vec::new(),
            index: 0,
        };

        assert_eq!(
            wizard.build_config().default_provider,
            Config::default().default_provider
        );
    }

    #[test]
    fn the_concurrency_default_is_left_alone_when_the_form_is_not_a_number() {
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = test_wizard(dir.path());
        wizard.limits[0].value = FieldValue::Bool(true);

        wizard.apply_provider_concurrency_default();

        assert_eq!(wizard.limits[0].value, FieldValue::Bool(true));
    }

    #[test]
    fn a_text_buffer_committed_onto_a_toggle_leaves_it_alone() {
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = test_wizard(dir.path());
        wizard.enter(Step::Limits);
        let before = wizard.limits[3].value.clone();

        wizard.edit = Some(Edit {
            target: EditTarget::Field(3),
            line: crate::tui::widgets::line_edit::LineEdit::new("yes".to_string(), false),
        });
        wizard.commit_edit();

        assert_eq!(wizard.limits[3].value, before);
    }

    // ─── building the config ────────────────────────────────────────────────

    #[test]
    fn deselecting_a_provider_clears_its_credential() {
        let dir = tempfile::tempdir().unwrap();
        let base = Config {
            providers: crate::config::ProviderConfig {
                anthropic_api_key: Some("sk-ant-stored".to_string()),
                ..Config::default().providers
            },
            ..Config::default()
        };
        let mut wizard = Wizard::new(
            base,
            &|_| None,
            Vec::new(),
            Vec::new(),
            dir.path(),
            std::sync::Arc::new(|_| true),
        );

        wizard.providers[0].selected = false;

        assert!(wizard.build_config().providers.anthropic_api_key.is_none());
    }

    #[test]
    fn ollamas_default_url_is_left_unset_rather_than_pinned() {
        // Storing the default would freeze it and shadow $OLLAMA_HOST.
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = test_wizard(dir.path());
        let ollama = wizard
            .providers
            .iter()
            .position(|r| r.provider.id == "ollama")
            .expect("ollama is offered");
        wizard.providers[ollama].selected = true;
        wizard.providers[ollama].value = catalog::DEFAULT_OLLAMA_URL.to_string();

        assert!(wizard.build_config().ollama_base_url.is_none());

        wizard.providers[ollama].value = "http://box:11434".to_string();
        assert_eq!(
            wizard.build_config().ollama_base_url.as_deref(),
            Some("http://box:11434")
        );
    }

    #[test]
    fn the_claude_code_transport_carries_its_effort_only_when_enabled() {
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = test_wizard(dir.path());
        let index = wizard
            .providers
            .iter()
            .position(|r| r.provider.id == "claude-code")
            .expect("the transport is offered");

        assert!(!wizard.build_config().providers.claude_code_enabled);

        wizard.providers[index].selected = true;
        wizard.providers[index].effort = effort_options().len() - 1;
        let config = wizard.build_config();
        assert!(config.providers.claude_code_enabled);
        assert_eq!(
            config.providers.claude_code_effort.as_deref(),
            Some(*effort_options().last().expect("levels exist"))
        );
    }

    #[test]
    fn an_out_of_range_effort_index_clamps_rather_than_panicking() {
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = test_wizard(dir.path());
        let index = wizard
            .providers
            .iter()
            .position(|r| r.provider.id == "claude-code")
            .expect("the transport is offered");
        wizard.providers[index].selected = true;
        wizard.providers[index].effort = 99;

        let config = wizard.build_config();

        assert_eq!(
            config.providers.claude_code_effort.as_deref(),
            Some(*effort_options().last().expect("levels exist"))
        );
    }

    #[test]
    fn the_stored_effort_selects_the_matching_option() {
        let dir = tempfile::tempdir().unwrap();
        let base = Config {
            providers: crate::config::ProviderConfig {
                claude_code_effort: Some("max".to_string()),
                ..Config::default().providers
            },
            ..Config::default()
        };
        let wizard = Wizard::new(
            base,
            &|_| None,
            Vec::new(),
            Vec::new(),
            dir.path(),
            std::sync::Arc::new(|_| true),
        );

        let index = wizard
            .providers
            .iter()
            .position(|r| r.provider.id == "claude-code")
            .expect("the transport is offered");
        assert_eq!(effort_options()[wizard.providers[index].effort], "max");
    }

    #[test]
    fn an_unrecognised_stored_effort_falls_back_to_the_first_level() {
        assert_eq!(effort_index(Some("not-a-level")), 0);
        assert_eq!(
            effort_options()[effort_index(None)],
            leviath_providers::claude_code::DEFAULT_EFFORT
        );
    }

    #[test]
    fn the_provider_default_model_is_stored_as_unset() {
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = test_wizard(dir.path());
        wizard.providers[0].selected = true;
        wizard.enter(Step::Defaults);

        // Index 0 of the model picker is always "(provider default)".
        assert!(wizard.build_config().default_model.is_none());
    }

    #[test]
    fn limits_are_written_back_including_the_zero_guard() {
        // A zero here would deadlock every tool batch, so it falls back to the
        // default rather than being stored.
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = test_wizard(dir.path());
        wizard.enter(Step::Limits);
        wizard.limits[0].value = FieldValue::Number(Some(2));
        wizard.limits[1].value = FieldValue::Number(Some(0));
        wizard.limits[2].value = FieldValue::Number(None);
        wizard.limits[3].value = FieldValue::Bool(true);
        wizard.limits[4].value = FieldValue::Bool(false);
        wizard.limits[5].value = FieldValue::Bool(false);
        wizard.limits[6].value = FieldValue::Number(Some(11));
        wizard.limits[7].value = FieldValue::Number(Some(22));
        wizard.limits[8].value = FieldValue::Number(Some(33));
        wizard.limits[9].value = FieldValue::Number(Some(44));

        let config = wizard.build_config();

        assert_eq!(config.limits.max_concurrent_inferences, Some(2));
        assert_eq!(
            config.limits.max_concurrent_tools,
            Config::default().limits.max_concurrent_tools
        );
        assert!(config.limits.default_max_iterations.is_none());
        assert!(config.limits.exact_token_counting);
        assert!(!config.batch_tool_hint);
        assert!(!config.shell_hint);
        // Every remaining field gets a distinct value, so a form that grows a
        // row without renumbering `apply_limits_fields` fails here rather than
        // silently dropping whichever field the duplicated index shadowed.
        assert_eq!(config.limits.stall_timeout_secs, 11);
        assert_eq!(config.limits.dead_cycles_before_relief, 22);
        assert_eq!(config.limits.finished_retention_secs, 33);
        assert_eq!(config.limits.wedge_timeout_secs, 44);
    }

    #[test]
    fn every_limits_field_is_written_back() {
        // The index in `apply_limits_fields` is positional and hand-written, so
        // an inserted row shifts every arm below it. Round-tripping the form
        // through itself catches a gap or a duplicate without naming indices.
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = test_wizard(dir.path());
        wizard.enter(Step::Limits);
        let count = wizard.limits.len();

        let before = wizard.build_config();
        let seeded = limits_fields(&before);
        assert_eq!(seeded.len(), count, "the form is built from the config");

        // Flip every toggle and give every number a distinct non-default
        // value, then read the form back out of the config it produced: a
        // field that no arm writes comes back with its original value. The
        // limits form is toggles and numbers only, so the second arm is the
        // number case rather than an unexercised catch-all.
        for (i, field) in wizard.limits.iter_mut().enumerate() {
            field.value = match &field.value {
                FieldValue::Bool(b) => FieldValue::Bool(!b),
                _ => FieldValue::Number(Some(i as u64 + 11)),
            };
        }
        let expected: Vec<FieldValue> = wizard.limits.iter().map(|f| f.value.clone()).collect();
        let after = limits_fields(&wizard.build_config());

        for (i, (got, want)) in after.iter().zip(&expected).enumerate() {
            assert_eq!(
                &got.value, want,
                "field {i} ({}) did not survive the round trip",
                got.label
            );
        }
    }

    /// The four timing limits share one rule: an explicit number is stored,
    /// including `0` (which means "never" for each of them), while leaving a
    /// field blank keeps the shipped default rather than disabling anything.
    #[test]
    fn the_watchdog_limits_store_zero_and_keep_the_default_when_blank() {
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = test_wizard(dir.path());
        wizard.enter(Step::Limits);
        wizard.limits[6].value = FieldValue::Number(Some(0));
        wizard.limits[7].value = FieldValue::Number(Some(0));
        wizard.limits[8].value = FieldValue::Number(Some(0));
        wizard.limits[9].value = FieldValue::Number(Some(300));

        let config = wizard.build_config();

        assert_eq!(config.limits.stall_timeout_secs, 0);
        assert_eq!(config.limits.dead_cycles_before_relief, 0);
        assert_eq!(config.limits.finished_retention_secs, 0);
        assert_eq!(config.limits.wedge_timeout_secs, 300);

        let mut wizard = test_wizard(dir.path());
        wizard.enter(Step::Limits);
        wizard.limits[6].value = FieldValue::Number(None);
        wizard.limits[7].value = FieldValue::Number(None);
        wizard.limits[8].value = FieldValue::Number(None);
        wizard.limits[9].value = FieldValue::Number(None);

        let config = wizard.build_config();

        let default = Config::default();
        assert_eq!(
            config.limits.stall_timeout_secs,
            default.limits.stall_timeout_secs
        );
        assert_eq!(
            config.limits.dead_cycles_before_relief,
            default.limits.dead_cycles_before_relief
        );
        assert_eq!(
            config.limits.finished_retention_secs,
            default.limits.finished_retention_secs
        );
        assert_eq!(
            config.limits.wedge_timeout_secs,
            default.limits.wedge_timeout_secs
        );
    }

    #[test]
    fn a_field_of_the_wrong_kind_is_ignored_when_writing_limits() {
        // Defensive: nothing builds this shape today, but a future edit that
        // reorders the form must not silently write a boolean into a count.
        let mut config = Config::default();
        apply_limits_fields(
            &mut config,
            &[Field {
                label: "Max concurrent inferences",
                help: "",
                value: FieldValue::Bool(true),
            }],
        );

        assert_eq!(
            config.limits.max_concurrent_inferences,
            Config::default().limits.max_concurrent_inferences
        );
    }

    #[test]
    fn the_plan_carries_only_the_selected_agents() {
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = test_wizard(dir.path());
        for row in wizard.agents.iter_mut().skip(1) {
            row.selected = false;
        }

        let plan = wizard.build_plan();

        assert_eq!(plan.agents.len(), 1);
        assert_eq!(plan.agents[0].name, BUNDLED_AGENTS[0].name);
    }

    #[test]
    fn the_review_says_so_when_nothing_would_change() {
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = test_wizard(dir.path());
        for row in wizard.agents.iter_mut() {
            row.selected = false;
        }

        assert_eq!(wizard.review_lines(), vec!["Nothing would change."]);
    }

    #[test]
    fn the_review_lists_real_changes() {
        let dir = tempfile::tempdir().unwrap();
        let mut wizard = test_wizard(dir.path());
        wizard.providers[0].selected = true;
        wizard.providers[0].value = "sk-ant-x".to_string();

        let lines = wizard.review_lines();

        assert!(lines.iter().any(|l| l.contains("credential set")));
        assert!(lines.iter().any(|l| l.contains("to install")));
    }

    // ─── scan merging ───────────────────────────────────────────────────────

    #[test]
    fn scans_flatten_into_candidates_and_labelled_errors() {
        let scans = vec![
            import::Scan {
                source: import::Source {
                    id: "a",
                    display: "Harness A",
                    path: std::path::PathBuf::from("/a"),
                    layout: import::Layout::ClaudeCode,
                    allows_comments: false,
                },
                result: Ok(vec![candidate("fs")]),
            },
            import::Scan {
                source: import::Source {
                    id: "b",
                    display: "Harness B",
                    path: std::path::PathBuf::from("/b"),
                    layout: import::Layout::CodexToml,
                    allows_comments: false,
                },
                result: Err("unreadable".to_string()),
            },
        ];

        let (candidates, errors) = candidates_from_scans(scans);

        assert_eq!(candidates.len(), 1);
        assert_eq!(candidates[0].0, "Harness A");
        assert_eq!(errors, vec!["Harness B: unreadable"]);
    }
}