eclipse-core 0.13.1

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

use crate::error::{Error, Result};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::fmt;
use std::path::{Path, PathBuf};

pub const APP_DIR: &str = "eclipse";

/// The shape of `config.toml` this build writes, stamped into the file as `config_version`.
///
/// A file with no stamp was written before the stamp existed (`0`), which is what makes the
/// migration in [`config::migrate`] able to run against every install that ever shipped rather
/// than only the ones made after this line was added. Bump it when the *shape* changes — a key
/// added, renamed or given a different shipped default — not for every release.
pub const CONFIG_VERSION: u32 = 1;

/// Environment lookup, injectable so tests never touch the process environment.
pub type EnvFn<'a> = &'a dyn Fn(&str) -> Option<String>;

pub fn process_env(key: &str) -> Option<String> {
    std::env::var(key).ok().filter(|v| !v.is_empty())
}

pub(crate) fn home_dir(env: EnvFn) -> Option<PathBuf> {
    env("HOME").map(PathBuf::from)
}

/// The one directory everything lives in: `$ECLIPSE_HOME`, or `~/.eclipse`.
///
/// Deliberately not XDG. The XDG split is right for a desktop application whose data belongs to
/// the machine's other applications; an agent is one thing a person owns, moves between hosts,
/// backs up and deletes, and "one directory you can `tar` up" is the property that matters more.
/// It is also the shape `~/.hermes` already has, which is what most people using this will have
/// seen first.
///
/// Everything below is derived from this and nothing else: `config.toml`, `.env` and `memory/`
/// sit at the top, machine-written files go in `state/`, a profile gets its own subtree, and the
/// checkout `eclipse upgrade` rebuilds from is recorded in `state/install.json` because it may
/// live anywhere.
pub fn home_root(env: EnvFn) -> Option<PathBuf> {
    if let Some(p) = env("ECLIPSE_HOME") {
        if !p.is_empty() {
            return Some(expand_tilde(Path::new(&p), env));
        }
    }
    home_dir(env).map(|h| h.join(".eclipse"))
}

/// Where `config.toml`, `.env` and the shared `plugins/`, `skills/` and `scripts/` live: the root
/// itself. A `--config` elsewhere moves the file without moving the directory it is read from,
/// which is what [`config_path`] is for.
pub fn config_dir(env: EnvFn) -> Option<PathBuf> {
    home_root(env)
}

/// Machine-written files: sessions, REPL history, locks, `install.json`, `update.json`. Inside the
/// root so that a backup, a move or a delete is one operation, and named for what it is rather
/// than for who wrote it.
pub fn state_dir(env: EnvFn) -> Option<PathBuf> {
    home_root(env).map(|r| r.join("state"))
}

/// Create the directories the layout names, so that `ls ~/.eclipse` answers "where does the
/// agent's stuff go?" without reading a document. Idempotent, and it never touches a file.
///
/// Nothing is created that Eclipse does not use: `memory/` is where the context files go,
/// `skills/` and `plugins/` are the user's own, `profiles/` holds named subtrees, `workspace/` is
/// the default place to point `[tools] workspace_root` when you do not want the current
/// directory, and `state/` is written from the first run.
pub fn ensure_layout(root: &Path) -> std::io::Result<()> {
    for dir in [
        "",
        "bin",
        "memory",
        "skills",
        "plugins",
        "profiles",
        "workspace",
        "state",
    ] {
        let p = if dir.is_empty() {
            root.to_path_buf()
        } else {
            root.join(dir)
        };
        std::fs::create_dir_all(&p)?;
    }
    Ok(())
}

/// The starter `AGENT.md`, written on first install. The user is expected to edit it; the
/// content is a shape and a set of instructions, not facts about the machine.
pub const STARTER_AGENT_MD: &str = "# How to work here
# This file is injected into the system prompt on every run, along with USER.md and MEMORY.md.
# Edit the lines below to describe this project: conventions, commands, gotchas.

You are a direct, practical assistant. Read before acting, say what you are doing,
and keep a reply short unless it needs to be long. Use the workspace and tools to verify
what you are about to do, rather than describing it.

MEMORY.md is for facts about the user and their machines. A procedure — the steps, commands and
pitfalls for a kind of task — belongs in a skill: `skill_manage` writes one, and only its name and
description sit in the prompt until the task calls for it.
";

/// The starter `USER.md`: who the operator is. Edit it; it is the agent's standing picture of
/// the user, injected on every run.
pub const STARTER_USER_MD: &str = "# Who the operator is
# This file is injected into the system prompt on every run. Describe the person who owns
# this install — who they are, what they do, and the preferences you should follow.

The operator is the person who owns this install. Edit this file with their name,
what they do, and standing preferences. Keep it short: this is who they are,
not a data dump.
";

/// Seed the three context files in the memory directory, creating any that are missing.
///
/// **A starter is written only where a file is absent, and its content is never revisited.** Two of
/// these three hold the operator's own words — `AGENT.md` how to work in this project, `USER.md`
/// who they are — and `MEMORY.md` is the agent's record. None of them can be regenerated from the
/// config the way `config.toml` can be regenerated from the wizard, which is why there is no merge,
/// no marker block inside them and no `--force` here: the only writer of a file that exists is
/// whoever the operator asked to write it (an editor, the `memory` tool, the dashboard).
///
/// Starter text is versioned in this binary and may change freely between releases; the change
/// reaches the next *install* — a fresh prefix, or a profile whose `memory/` has no such file —
/// and never an existing one. So this is safe on every path that runs it: repeating it over a
/// directory that has the files does nothing at all.
///
/// Returns the paths created, in the order AGENT, USER, MEMORY.
pub fn seed_context_files(memory_dir: &Path) -> Result<Vec<PathBuf>> {
    std::fs::create_dir_all(memory_dir).map_err(|e| Error::io(memory_dir, e))?;
    let mut created = Vec::new();
    for (name, body) in [
        ("AGENT.md", STARTER_AGENT_MD),
        ("USER.md", STARTER_USER_MD),
        // MEMORY.md starts empty: it is the agent's running record, and the `memory` tool
        // is what fills it. An empty file is valid and is not injected.
        ("MEMORY.md", ""),
    ] {
        let path = memory_dir.join(name);
        if path.exists() {
            continue;
        }
        std::fs::write(&path, body).map_err(|e| Error::io(&path, e))?;
        created.push(path);
    }
    Ok(created)
}

mod check;
pub mod migrate;
mod settings;

pub use check::{unknown_keys_in_file, UnknownKey};
pub use migrate::{baseline_path, plan as migration_plan, Change, Plan};
pub use settings::{
    about, choices, parse_value, set_in_text, set_list_in_text, unset_in_text, Applies, Kind,
    Setting,
};

/// `$ECLIPSE_CONFIG` or `<config_dir>/config.toml`.
pub fn config_path(env: EnvFn) -> Option<PathBuf> {
    if let Some(p) = env("ECLIPSE_CONFIG") {
        return Some(PathBuf::from(p));
    }
    config_dir(env).map(|d| d.join("config.toml"))
}

/// Profile names become directory names, so they are held to the same alphabet as session
/// ids: `[A-Za-z0-9_-]`, 1-64 characters.
pub fn validate_profile_name(name: &str) -> Result<()> {
    let ok = !name.is_empty()
        && name.len() <= 64
        && name
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
    if ok {
        Ok(())
    } else {
        Err(Error::Config(format!("invalid profile name {name:?}")))
    }
}

/// `<root>/profiles/<name>`: a profile's own config overlay, `memory/`, `skills/`, `plugins/` and
/// `state/`.
pub fn profile_dir(env: EnvFn, name: &str) -> Option<PathBuf> {
    home_root(env).map(|d| d.join("profiles").join(name))
}

/// State directory for a profile: the root's own `state/` for the default profile, otherwise
/// `profiles/<name>/state` — beside that profile's config, not inside the root's state, so a
/// profile is a subtree you can move or delete in one piece.
pub fn state_dir_for(env: EnvFn, profile: Option<&str>) -> Option<PathBuf> {
    match profile {
        None | Some("default") => state_dir(env),
        Some(name) => profile_dir(env, name).map(|d| d.join("state")),
    }
}

fn expand_tilde(p: &Path, env: EnvFn) -> PathBuf {
    if let Ok(rest) = p.strip_prefix("~") {
        if let Some(h) = home_dir(env) {
            return h.join(rest);
        }
    }
    p.to_path_buf()
}

/// What happens when the model asks for a tool.
/// How `fetch` returns an HTML response by default.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum FetchHtml {
    /// Convert to approximate plain text (see `eclipse_core::html`).
    Text,
    /// Return the HTML source unchanged.
    Raw,
}

/// What a `shell` command can reach once it runs. The mechanics are in `eclipse_core::sandbox`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ShellIsolate {
    /// A plain process: your files, your network, and anything it starts outlives the call.
    Off,
    /// A private PID namespace, through bubblewrap. The filesystem is unchanged; a daemon the
    /// command leaves behind dies with the run.
    Process,
    /// A private PID namespace and a read-only filesystem, with the workspace writable. Costs a
    /// build that writes outside the workspace (cargo into `~/.cargo`) a `shell_isolate_writable`
    /// line.
    Fs,
}

impl std::fmt::Display for ShellIsolate {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            Self::Off => "off",
            Self::Process => "process",
            Self::Fs => "fs",
        })
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Policy {
    /// Never run.
    Deny,
    /// Run only if the front-end approver says yes. What "yes" gates depends on the tool: the
    /// shell asks only about commands that cannot be undone, and the file tools never ask, because
    /// they refuse anything outside the workspace themselves.
    Ask,
    /// Run without asking.
    Allow,
}

/// What the shell puts to a person when its policy is [`Policy::Ask`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum ShellAsk {
    /// Only a command that can destroy something: `rm`, `sudo`, `dd`, a forced push.
    #[default]
    Dangerous,
    /// Every command, as the interface did before 0.5.1. Kept for a machine where a prompt per
    /// call is the point — a shared box, a demonstration, a first week with an agent.
    Always,
}

/// The `.env` files read for this profile, and what they set.
///
/// Read order is shared `.env` then the profile's, so a profile overrides the shared file
/// key by key. The real process environment still beats both: a `.env` is a fallback for
/// what the shell did not set, never an override of it — otherwise exporting a variable to
/// test something would appear not to work.
///
/// Only the file *names* are ever printed (`config show`); values are secrets by
/// assumption, since that is what this file is for.
#[derive(Clone, Default, PartialEq, Eq)]
pub struct Dotenv {
    /// Files that existed and were read, in read order.
    pub files: Vec<PathBuf>,
    pub values: BTreeMap<String, String>,
}

impl fmt::Debug for Dotenv {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // The file names, and the *names* of what they set — never the values. This file exists
        // to hold secrets, `Config` derives `Debug`, and `Config` holds this: one `{cfg:?}` in a
        // panic message or a failing `assert_eq!` would otherwise print the whole secrets file.
        // The key names stay, because "which variables came from where" is the useful half.
        f.debug_struct("Dotenv")
            .field("files", &self.files)
            .field("keys", &self.values.keys().collect::<Vec<_>>())
            .finish()
    }
}

impl Dotenv {
    /// Load the `.env` chain for `profile` (if any) from the config directory.
    pub fn load(env: EnvFn<'_>, profile: Option<&str>) -> Result<Dotenv> {
        let Some(dir) = config_dir(env) else {
            return Ok(Dotenv::default());
        };
        let mut candidates = vec![dir.join(".env")];
        if let Some(p) = profile {
            validate_profile_name(p)?;
            candidates.push(dir.join("profiles").join(p).join(".env"));
        }
        let mut values = BTreeMap::new();
        let mut files = Vec::new();
        for path in candidates {
            if !path.exists() {
                continue;
            }
            // Later files win, so a profile can override one key without restating the rest.
            // An empty value is *not* a value: the shipped file names every variable and sets
            // none of them, so `NAME=` has to mean "absent" everywhere, not just where a call
            // site remembered to filter it. `config init` used to write one line for exactly
            // that reason, and `setup` still filtered emptiness by hand at two call sites.
            for assignment in crate::dotenv::load(&path)? {
                if assignment.value.is_empty() {
                    values.remove(&assignment.key);
                    continue;
                }
                values.insert(assignment.key, assignment.value);
            }
            files.push(path);
        }
        Ok(Dotenv { files, values })
    }
}

/// `Some("")` is `None` — an empty value is how a shipped config says "not in use".
///
/// The shipped file is complete: every key is live, and the ones that name a secret, an address,
/// a route or a schema are live with `${VAR:-}` or `""`. Without this, `api_key = "${X:-}"` with no
/// `X` would arrive as `Some("")` and be sent as `Authorization: Bearer *** ` — a failure that shows
/// up at the far end of a request instead of in the file that caused it. It applies to the
/// `Option<String>` keys only: `model = ""` and `base_url = ""` are not options but addresses, and
/// "" already means "not configured" there.
fn empty_is_none<'de, D>(d: D) -> std::result::Result<Option<String>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    use serde::Deserialize;
    Ok(Option::<String>::deserialize(d)?.filter(|v| !v.is_empty()))
}

#[derive(Clone, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct ProviderConfig {
    /// Base URL of an OpenAI-compatible API, e.g. a local server. No default.
    pub base_url: String,
    /// Prefer `api_key_env` or `ECLIPSE_API_KEY` over storing a key here.
    #[serde(deserialize_with = "empty_is_none")]
    pub api_key: Option<String>,
    /// Name of an environment variable holding the key.
    #[serde(deserialize_with = "empty_is_none")]
    pub api_key_env: Option<String>,
    pub model: String,
    pub temperature: Option<f64>,
    pub timeout_secs: u64,
    /// Ask the endpoint for a token-by-token (SSE) reply. Endpoints that ignore the
    /// request and answer with plain JSON still work; set `false` to never ask.
    pub stream: bool,
    /// Extra attempts after a request fails with HTTP 408, 429 or 5xx, or could not be sent at all —
    /// refused, DNS, TLS (0 = never retry).
    ///
    /// Waits `retry_base_delay_ms`, then double, then double again: 2 s, 4 s, 8 s with the defaults.
    /// Other 4xx statuses are never retried: a wrong key or a rejected option fails the same way
    /// every time. A failure that happened *after* the request went out — a reset mid-generation, a
    /// silent connection — is only repeated when [`retry_after_send`](Self::retry_after_send) says
    /// so, because repeating a billed request can pay for it twice.
    pub max_retries: u32,
    /// Repeat a request that failed **after** it went out — the connection dropped mid-generation, or
    /// nothing came back for `timeout_secs`. Off by default: `/chat/completions` is billed and not
    /// idempotent, so a repeat can pay for the same work twice, up to `max_retries + 1` times a turn.
    /// A connect-stage failure (refused, DNS, TLS) never reached the server and is always repeated.
    pub retry_after_send: bool,
    pub retry_base_delay_ms: u64,
    /// Soft cap on the conversation sent to the model, in estimated tokens (characters
    /// / 4, a rough heuristic). When exceeded, the oldest turns are dropped and replaced
    /// by a marker note. 0 = disabled.
    pub context_budget_tokens: usize,
    /// Cap on the reply, in tokens. Sent under the field name the profile asks for.
    /// `None` = do not send a cap.
    pub max_tokens: Option<u32>,
    /// Wire profile: `openai` (default), `llamacpp`, or one a plugin declares. Profiles
    /// change how the request is shaped, never what the model is asked.
    #[serde(deserialize_with = "empty_is_none")]
    pub profile: Option<String>,
    /// Nucleus sampling. Unset = do not send. Most local servers default to 1.0 anyway; set
    /// this when a model rambles.
    pub top_p: Option<f64>,
    /// Ask for a reproducible sample where the backend supports it. Unset = do not send.
    pub seed: Option<i64>,
    /// Up to four sequences the reply must stop at. Unset = do not send.
    pub stop: Option<Vec<String>>,
    /// `low`, `medium` or `high` on backends that have a reasoning knob. Unset = the route's own
    /// declared default, which is `medium` on both shipped profiles, and nothing at all on a
    /// backend that declares no default (`#276`); a spelling this backend does not know comes back
    /// as a 400 naming the field.
    #[serde(deserialize_with = "empty_is_none")]
    pub reasoning_effort: Option<String>,
    /// Ask for several tool calls in one reply. Unset = do not send.
    pub parallel_tool_calls: Option<bool>,
    /// Whether this route's model can see images. Overrides the wire profile's declaration:
    /// `Some(true)` enables vision on a profile that says nothing (such as `llamacpp`),
    /// `Some(false)` forces vision off even if a profile says `true`, and `None` inherits
    /// the profile.
    pub vision: Option<bool>,
    /// `auto`, `none`, `required`, or a tool name. Overrides the profile's default; unset
    /// leaves the profile's own value (`auto` where the backend understands the field).
    pub tool_choice: Option<crate::hooks::ToolChoice>,
    /// JSON merged into every request body, after the config's own fields and before a
    /// per-turn patch. The escape hatch for `chat_template_kwargs` and backend quirks this
    /// build does not model.
    pub extra_body: Option<serde_json::Value>,
    /// The order routes are tried in when a request fails for a transient reason. Only
    /// meaningful directly under `[provider]`; a route that carries one is a config error.
    /// Unset means "just the `default` route", which is what a config without routes does.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub fallback: Option<Vec<String>>,
    /// The route that does the agent's own housekeeping — the summary of trimmed turns — and
    /// never the user's work. Only meaningful directly under `[provider]`; a route that carries
    /// one is a config error. Unset means "the route this run is on".
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(deserialize_with = "empty_is_none")]
    pub aux: Option<String>,
    /// The route a `delegate` call's child agent runs on unless the call names one. Only
    /// meaningful directly under `[provider]`; a route that carries one is a config error.
    /// Unset means "the route this run is on".
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(deserialize_with = "empty_is_none")]
    pub delegate: Option<String>,
    /// `[[provider.route]]`: named, complete provider configurations. Only meaningful
    /// directly under `[provider]`.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub route: Vec<RouteConfig>,
}

/// One `[[provider.route]]`: a name and a *complete* [`ProviderConfig`].
///
/// Not a delta over `[provider]`. A chain whose entries inherit half their settings from the
/// one before is a debugging hazard — "which `timeout_secs` did the third hop use?" should
/// have the answer "the one written under it".
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct RouteConfig {
    /// What `--route`, `fallback` and the readout call this route.
    pub name: String,
    /// How many flares this route may run at once (`#171`). Unset takes the profile's default:
    /// one for a local server, which serves one model and swaps rather than multiplying, and four
    /// for an OpenAI-compatible API, where the limit is money and rate, not hardware. `0` reads
    /// as `1`, the same rule [`ToolsConfig::concurrency`] keeps, because a route with no slot is
    /// a route flares cannot use and silently starving them is worse than a slow run.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_parallel: Option<usize>,
    /// Routes that share one server share its bound (`#171`): two local routes pointed at the same
    /// llama-swap are one slot, not two, because it swaps by stopping one model to start another.
    /// A group takes its **lowest** member's bound, the conservative reading of "these are the
    /// same box".
    #[serde(skip_serializing_if = "Option::is_none")]
    pub group: Option<String>,
    #[serde(flatten)]
    pub config: ProviderConfig,
}

/// Written by hand because `#[serde(flatten)]` buffers the table and then reports a wrong-typed
/// value as "invalid type ... in `provider.route`", dropping the key. A route is exactly where a
/// misread setting is hardest to spot, so the error says which route and which key.
impl<'de> Deserialize<'de> for RouteConfig {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
        use serde::de::Error as _;
        let mut table = toml::Table::deserialize(d)?;
        let name = match table.remove("name") {
            None => String::new(),
            Some(toml::Value::String(name)) => name,
            Some(other) => {
                return Err(D::Error::custom(format!(
                    "provider.route `name` must be a string, got {}",
                    other.type_str()
                )))
            }
        };
        let label = if name.is_empty() {
            "an unnamed route".to_string()
        } else {
            format!("route `{name}`")
        };
        // Two keys on a route are not provider settings: they shape how many flares may run on
        // it (`#171`). Removed here so `ProviderConfig` cannot read one as an unknown key and so
        // a wrong type is reported against the route that wrote it.
        let max_parallel = match table.remove("max_parallel") {
            None => None,
            Some(toml::Value::Integer(n)) if n >= 0 => Some(n as usize),
            Some(other) => {
                return Err(D::Error::custom(format!(
                    "{label}: `max_parallel` must be a positive integer, got {}",
                    other.type_str()
                )))
            }
        };
        let group = match table.remove("group") {
            None => None,
            Some(toml::Value::String(g)) if !g.trim().is_empty() => Some(g),
            Some(_) => {
                return Err(D::Error::custom(format!(
                    "{label}: `group` must be a non-empty string"
                )))
            }
        };
        let config = ProviderConfig::deserialize(toml::Value::Table(table))
            .map_err(|e| D::Error::custom(format!("{label}: {e}")))?;
        Ok(Self {
            name,
            max_parallel,
            group,
            config,
        })
    }
}

/// The name `[provider]` itself goes by once routes exist.
pub const DEFAULT_ROUTE: &str = "default";

impl ProviderConfig {
    /// Whether anything but the route table says something about the connection. An empty
    /// `[provider]` (or none at all) is how a config that only uses routes looks, and it must
    /// not be mistaken for a `default` route that forgot its `base_url`.
    ///
    /// Identity only — where it points, what it serves, which key it uses. A `[provider]` that
    /// carries nothing but tuning keys (`max_retries`, `temperature`, `context_budget_tokens`)
    /// is not a route: it names no server, so listing it as one would offer the user a route
    /// that cannot be used.
    fn declares_connection(&self) -> bool {
        !self.base_url.trim().is_empty()
            || !self.model.trim().is_empty()
            || self.api_key.is_some()
            || self.api_key_env.is_some()
    }
}

/// A route with its name attached and the route table itself stripped off, so what is left
/// is exactly one provider's settings.
#[derive(Debug, Clone, PartialEq)]
pub struct NamedRoute {
    pub name: String,
    /// `[[provider.route]] max_parallel` (`#171`); `None` takes the profile's default.
    pub max_parallel: Option<usize>,
    /// `[[provider.route]] group` (`#171`): routes that are one server's worth of slots.
    pub group: Option<String>,
    pub config: ProviderConfig,
}

impl NamedRoute {
    /// What a flare run may assume about this route when the config says nothing: a local server
    /// serves one model at a time (llama-swap swaps rather than multiplying), and an API's limit
    /// is rate and spend. The profile name is the only signal the config gives, so it is the one
    /// used — guessing from a port would be a rule nobody could read out of the file.
    pub fn default_parallel(&self) -> usize {
        let profile = self.config.profile.as_deref().unwrap_or("openai");
        if profile.eq_ignore_ascii_case("openai") {
            4
        } else {
            1
        }
    }

    /// How many flares this route may run at once, with `0` read as `1`.
    pub fn parallel(&self) -> usize {
        self.max_parallel
            .unwrap_or_else(|| self.default_parallel())
            .max(1)
    }

    /// The two route keys that are about flares rather than the wire (`#171`), attached after
    /// construction because the default route has neither.
    pub fn with_flare_shape(mut self, max_parallel: Option<usize>, group: Option<String>) -> Self {
        self.max_parallel = max_parallel;
        self.group = group;
        self
    }

    fn new(name: &str, config: &ProviderConfig) -> Self {
        let mut config = config.clone();
        config.route.clear();
        config.fallback = None;
        config.aux = None;
        config.delegate = None;
        Self {
            name: name.to_string(),
            max_parallel: None,
            group: None,
            config,
        }
    }

    /// `[provider]` keeps the messages it has always had; a named route says which one.
    fn require_endpoint(&self, source: ChainSource) -> Result<()> {
        let plain = self.name == DEFAULT_ROUTE && source == ChainSource::Default;
        let missing = |key: &str, hint: &str| {
            Error::Config(if plain {
                format!("provider.{key} is not set {hint}")
            } else {
                format!("route `{}` has no {key}", self.name)
            })
        };
        if self.config.base_url.trim().is_empty() {
            return Err(missing(
                "base_url",
                "(config file or ECLIPSE_BASE_URL); run `eclipse config init`",
            ));
        }
        if self.config.model.trim().is_empty() {
            return Err(missing("model", "(config file or ECLIPSE_MODEL)"));
        }
        Ok(())
    }
}

/// Where a run's chain of routes came from.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChainSource {
    /// No `fallback`, no pin: `[provider]` alone, exactly as before routes existed.
    Default,
    /// `[provider] fallback`: tried in order on a transient failure.
    Fallback,
    /// `--route` or `ECLIPSE_ROUTE`: one route, and no falling back from it.
    Pinned,
}

/// The routes one run will use, in order.
#[derive(Debug, Clone, PartialEq)]
pub struct Chain {
    pub routes: Vec<NamedRoute>,
    pub source: ChainSource,
    /// The route `[provider] aux` names; `None` when unset, which means the first of `routes`.
    pub aux: Option<NamedRoute>,
    /// The route `[provider] delegate` names; `None` when unset, which means the first of `routes`.
    pub delegate: Option<NamedRoute>,
}

impl Chain {
    /// Which route each role uses: the one answer `config show`, `/status` and the panel share.
    pub fn roles(&self) -> Vec<crate::router::RoleRoute> {
        crate::router::role_table(
            self.aux.as_ref().map(|r| r.name.as_str()),
            self.delegate.as_ref().map(|r| r.name.as_str()),
            self.routes.first().map_or("", |r| r.name.as_str()),
            self.source == ChainSource::Pinned,
        )
    }
}

/// `api_key_env` (and an explicit override) resolved against `env`. Kept as one function so
/// `[provider]` and every route follow the same rule: the named variable beats a literal key.
fn apply_key_env(cfg: &mut ProviderConfig, env: EnvFn, explicit: Option<String>) {
    if let Some(v) = explicit {
        cfg.api_key = Some(v);
    } else if let Some(name) = cfg.api_key_env.clone() {
        if let Some(v) = env(&name) {
            cfg.api_key = Some(v);
        }
    }
}

impl Default for ProviderConfig {
    fn default() -> Self {
        Self {
            base_url: String::new(),
            api_key: None,
            api_key_env: None,
            model: String::new(),
            temperature: None,
            timeout_secs: 120,
            stream: true,
            max_retries: 3,
            retry_after_send: false,
            retry_base_delay_ms: 2000,
            context_budget_tokens: 0,
            max_tokens: None,
            profile: None,
            top_p: None,
            seed: None,
            stop: None,
            reasoning_effort: None,
            parallel_tool_calls: None,
            vision: None,
            tool_choice: None,
            extra_body: None,
            fallback: None,
            aux: None,
            delegate: None,
            route: Vec::new(),
        }
    }
}

impl fmt::Debug for ProviderConfig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ProviderConfig")
            // The same URL the redacted TOML scrubs: a `{cfg:?}` in a panic message must not be
            // the one place a gateway password survives.
            .field(
                "base_url",
                &redact_url(&self.base_url).unwrap_or_else(|| self.base_url.clone()),
            )
            .field("api_key", &self.api_key.as_ref().map(|_| "<redacted>"))
            .field("api_key_env", &self.api_key_env)
            .field("model", &self.model)
            .field("temperature", &self.temperature)
            .field("timeout_secs", &self.timeout_secs)
            .field("stream", &self.stream)
            .field("max_retries", &self.max_retries)
            .field("retry_after_send", &self.retry_after_send)
            .field("retry_base_delay_ms", &self.retry_base_delay_ms)
            .field("context_budget_tokens", &self.context_budget_tokens)
            .field("vision", &self.vision)
            .field("fallback", &self.fallback)
            .field("aux", &self.aux)
            .field("delegate", &self.delegate)
            .field("route", &self.route)
            .finish()
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct AgentConfig {
    /// Stop the run after this many consecutive tool calls that could not be used (an unknown
    /// tool, or arguments that are not JSON). 0 disables it, which is the default: a model that
    /// slips once should get another chance, and only a repeat is a pattern.
    pub max_consecutive_malformed_tool_calls: usize,
    pub system_prompt: String,
    /// How many model <-> tool round trips one turn may take. No cap by default: the same
    /// default Hermes' engine uses, and the honest one, because the number that is right for a
    /// one-line answer is not the number that is right for a file-plus-tests-plus-a-retry. A cap
    /// is a policy for the box it runs on, so it is set there, not imposed here.
    #[serde(
        default = "unlimited_turns",
        deserialize_with = "de_turn_limit",
        serialize_with = "ser_turn_limit"
    )]
    pub max_iterations: usize,
    /// A JSON Schema every reply must satisfy, as a path (relative to the working directory, like
    /// `workspace_root`) or an inline JSON document. A default for `eclipse run`; a schema is a
    /// contract, not a chat setting, so the interactive surfaces ignore it.
    #[serde(deserialize_with = "empty_is_none")]
    pub output_schema: Option<String>,
    /// Truncate a single context file past this many characters (head and tail kept, with a
    /// visible marker). 0 = no per-file cap.
    pub context_file_max_chars: usize,
    /// Ceiling across every context file; whole files are dropped past it, broadest first,
    /// and `eclipse context show` says which. 0 = no cap.
    pub context_files_budget_chars: usize,
    /// Include prompts, arguments and results in tracing spans. Off by default: the
    /// transcript is already readable; the spans exist for timing and routing.
    pub trace_content: bool,
    /// Which standing prompt blocks ride after `system_prompt` (`#244`): `auto` (the default) takes
    /// every block whose gate matches the model, a list names them, `off` sends none. The library is
    /// [`crate::prompt_blocks`]; `config check` prints what this model is actually being told.
    pub prompt_blocks: crate::prompt_blocks::Choice,
}

/// No cap. `usize::MAX` rather than an `Option` so every caller that multiplies, counts or
/// compares a budget keeps working: `for turn in 0..budget` simply never reaches the end.
fn unlimited_turns() -> usize {
    usize::MAX
}

/// A turn budget is written as a number when someone wants a cap and as a word when they do not.
/// `0` and `-1` mean no cap too — they are what people type when they mean "off", and answering
/// "your run gets one request" would be a trap.
fn de_turn_limit<'de, D>(d: D) -> std::result::Result<usize, D::Error>
where
    D: serde::Deserializer<'de>,
{
    #[derive(serde::Deserialize)]
    #[serde(untagged)]
    enum Raw {
        Number(i64),
        Word(String),
    }
    let n = match Raw::deserialize(d)? {
        Raw::Number(n) => n,
        Raw::Word(word) => match word.trim().to_ascii_lowercase().as_str() {
            "unlimited" | "none" | "null" | "inf" | "infinite" | "infinity" | "∞" => 0,
            other => other.parse::<i64>().map_err(|_| {
                serde::de::Error::custom(format!(
                    "`max_iterations` takes a whole number or `unlimited`, not `{other}`"
                ))
            })?,
        },
    };
    Ok(if n <= 0 {
        unlimited_turns()
    } else {
        n as usize
    })
}

/// Printed as the word, so `config show` and the starter file both say what they mean instead of
/// `18446744073709551615`.
fn ser_turn_limit<S>(value: &usize, s: S) -> std::result::Result<S::Ok, S::Error>
where
    S: serde::Serializer,
{
    if *value == usize::MAX {
        s.serialize_str("unlimited")
    } else {
        s.serialize_u64(*value as u64)
    }
}

impl Default for AgentConfig {
    fn default() -> Self {
        Self {
            system_prompt:
                "You are a helpful personal assistant running locally on the user's machine. \
Use tools only when they are needed, and explain briefly what you did."
                    .into(),
            max_iterations: unlimited_turns(),
            output_schema: None,
            max_consecutive_malformed_tool_calls: 0,
            context_file_max_chars: crate::context_files::DEFAULT_MAX_FILE_CHARS,
            context_files_budget_chars: crate::context_files::DEFAULT_BUDGET_CHARS,
            trace_content: false,
            prompt_blocks: crate::prompt_blocks::Choice::Auto,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct ToolsConfig {
    /// File tools are confined to this directory. Defaults to the current directory.
    pub workspace_root: Option<PathBuf>,
    pub read_file: Policy,
    /// The `search_files` tool: a read-only walk of the workspace. `allow` for the same reason as
    /// `read_file` — the tree it walks is confined, and a prompt per search is the noise that
    /// teaches people to approve without reading.
    pub search_files: Policy,
    pub write_file: Policy,
    /// Above this many bytes, clobbering an existing file with `write_file` needs `force`.
    /// A rewrite carries the whole file as a tool-call argument, and that argument stays in the
    /// conversation for the rest of the session — the single most expensive way to change a line.
    /// `0` switches the guard off.
    #[serde(default = "default_rewrite_guard")]
    pub rewrite_guard_bytes: usize,
    /// The `patch` tool: a targeted edit of a file that already exists. Same default as
    /// `write_file`, because it is the same side effect, more carefully aimed.
    pub patch: Policy,
    /// The `memory` tool: write a durable fact to `MEMORY.md`, which is loaded into every later
    /// system prompt of the session. `ask` by default: clean writes still run silently, and only
    /// writes carrying a verbatim run from a tool result in the same turn prompt (`#482`).
    /// `allow` skips the taint check; `deny` disables the tool.
    pub memory: Policy,
    pub shell: Policy,
    pub fetch: Policy,
    /// The `script` tool, which runs a file from the scripts directory. `ask` by default: a
    /// script is arbitrary code, and one the agent wrote itself is no more trustworthy for it.
    /// A bare `{"list": true}` is a read of a directory the user owns and is not asked about.
    pub script: Policy,
    /// The `execute_code` tool: a short program written for one job, run from a temporary file
    /// that is deleted afterwards, with a bridge back to the registry so the program can call
    /// tools. `ask` by default: it is arbitrary code, and a bridge makes it more useful, not
    /// more trustworthy.
    pub execute_code: Policy,
    /// The `delegate` tool, which hands a job to a child agent. `ask` by default: a child
    /// spends tokens, possibly on a bigger model than the one you are talking to, and may run
    /// tools of its own.
    pub delegate: Policy,
    /// Timeout for `shell` and for `script`: they are the same kind of thing, a process the
    /// agent started, and one number keeps them honest with each other.
    /// Whether the shell asks about every command or only about the dangerous ones.
    pub shell_ask: ShellAsk,
    pub shell_timeout_secs: u64,
    /// If non-empty, `shell` only runs these program names, without a shell.
    pub shell_allowlist: Vec<String>,
    /// What a `shell` command can reach: `off` (a plain process), `process` (a private PID
    /// namespace, filesystem unchanged) or `fs` (also a read-only filesystem). `process` by
    /// default. Any mode but `off` needs bubblewrap, and refuses to run without it rather
    /// than quietly running unsandboxed.
    pub shell_isolate: ShellIsolate,
    /// Paths bound read-write in `fs` mode, beyond the workspace and the scripts directory.
    /// `~` is the home directory. A cargo build needs `~/.cargo` here.
    pub shell_isolate_writable: Vec<PathBuf>,
    /// Paths replaced by an empty directory in `fs` mode, so their contents cannot be read.
    /// `~` is the home directory.
    pub shell_isolate_hide: Vec<PathBuf>,
    /// Whether `fs` mode keeps the network. `true` by default: a build needs it, and a task
    /// that only edits files can turn it off.
    pub shell_isolate_network: bool,
    pub fetch_timeout_secs: u64,
    /// `text` (default) converts HTML responses to plain text; `raw` returns the source.
    /// The model can override per call with `{"raw": true|false}`.
    pub fetch_html: FetchHtml,
    /// Tool output is truncated to this many bytes before reaching the model.
    pub max_output_bytes: usize,
    /// How many of one turn's tool calls may run at the same time. 1 (the default) runs them
    /// one after another; 0 is treated as 1. Results are committed in the order the model
    /// emitted the calls, whatever this is set to.
    pub concurrency: usize,
    /// Tools to remove entirely, whatever their policy says. Not offered to the model, and a
    /// call that names one is refused — the point is that a hallucinated call cannot slip
    /// through. Stronger than `deny`: it also survives a plugin claiming the name.
    pub disabled: Vec<String>,
    /// Tools that stay registered and callable but are **not** described in the request, so they
    /// cost no tokens until they are needed. `tool_search` finds them by keyword,
    /// `tool_describe` gives their arguments, and `tool_call` runs them — all three through the
    /// same policy, approval and hook path as a direct call, so deferring a tool moves it out of
    /// the prompt and changes nothing else. `"*"` defers everything registered, and a trailing
    /// `*` is a prefix. A pattern is matched against a tool's **name** and against its **source**
    /// (`plugin:mcp:<server>`), because MCP tools keep the names their server published and so
    /// cannot be deferred by name (`#351`).
    ///
    /// The shipped default is `plugin:mcp:*`: an MCP server is where forty tools come from, and
    /// forty schemas in every request is four thousand tokens of promise. Plugins that declare a
    /// handful of tools stay visible; anything can be deferred or un-deferred explicitly.
    #[serde(default = "default_deferred")]
    pub deferred: Vec<String>,
    /// The three tools that reach the deferred ones. `allow` by default: none of them has a
    /// side effect of its own, and `tool_call` is a router — the tool it routes *to* is what
    /// the policy and the approval prompt are about, so asking twice would only train the user
    /// to hold down Enter.
    pub tool_search: Policy,
    pub tool_describe: Policy,
    pub tool_call: Policy,
}

/// The secrets under `$HOME` that `fs` mode empties by default: what an injected command would
/// look for first, and none of which a build needs.
///
/// The state directory is deliberately absent: it holds the scripts directory, which every run
/// writes into, so a hide over it would be dropped every time and the status line would carry a
/// warning that never means anything. A profile that keeps its own state elsewhere can add it.
fn default_hidden_paths() -> Vec<PathBuf> {
    ["~/.ssh", "~/.gnupg", "~/.aws", "~/.hermes"]
        .iter()
        .map(PathBuf::from)
        .collect()
}

/// 32 KB: large enough that no honest one-shot rewrite trips it (a README, a config file, a
/// script), small enough that the files worth patching — a single-file app, a long document —
/// are guarded. A rewrite of something bigger is a decision, not an accident.
/// MCP tools are deferred out of the box (`#351`): an MCP server is where forty tools come from,
/// and forty schemas in every request is four thousand tokens of promise. Matched against the
/// tool's source label (`plugin:mcp:<server>`), not its name — MCP tools keep the name the server
/// published (`#373`), so `mcp_*` would match nothing.
fn default_deferred() -> Vec<String> {
    vec!["plugin:mcp:*".to_string(), "config:mcp:*".to_string()]
}

fn default_rewrite_guard() -> usize {
    32 * 1024
}

impl Default for ToolsConfig {
    fn default() -> Self {
        Self {
            workspace_root: None,
            read_file: Policy::Allow,
            search_files: Policy::Allow,
            // The file tools confine every path to the workspace (and the scripts directory) and
            // refuse the rest, so the refusal — not a prompt — is what keeps them honest. Asking
            // on top of a boundary that already holds is the noise that teaches `y`.
            write_file: Policy::Allow,
            rewrite_guard_bytes: default_rewrite_guard(),
            patch: Policy::Allow,
            memory: Policy::Ask,
            shell: Policy::Ask,
            fetch: Policy::Ask,
            script: Policy::Ask,
            execute_code: Policy::Ask,
            delegate: Policy::Ask,
            shell_ask: ShellAsk::Dangerous,
            shell_timeout_secs: 30,
            shell_allowlist: Vec::new(),
            shell_isolate: ShellIsolate::Process,
            shell_isolate_writable: Vec::new(),
            shell_isolate_hide: default_hidden_paths(),
            shell_isolate_network: true,
            fetch_timeout_secs: 20,
            fetch_html: FetchHtml::Text,
            max_output_bytes: 32 * 1024,
            concurrency: 1,
            disabled: Vec::new(),
            deferred: default_deferred(),
            tool_search: Policy::Allow,
            tool_describe: Policy::Allow,
            tool_call: Policy::Allow,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct SessionsConfig {
    /// Defaults to `<state_dir>/sessions`.
    pub dir: Option<PathBuf>,
    /// Default for `sessions prune --keep-days`: delete sessions whose last activity is
    /// older than this many days. 0 = disabled. Applied unattended only if `auto_prune`.
    pub retention_keep_days: u64,
    /// Default for `sessions prune --keep-count`: keep only the newest N sessions.
    /// 0 = disabled. Applied unattended only if `auto_prune`.
    pub retention_keep_count: usize,
    /// Apply the retention limits when the CLI starts (`run` and the REPL), before the
    /// prompt. Off by default. It deletes only if at most 10 sessions would go; otherwise
    /// it warns and deletes nothing. With both limits 0 it does nothing. The web dashboard
    /// never prunes.
    pub auto_prune: bool,
    /// How long a run waits for another *process* to release the same session before it
    /// fails. 0 = do not wait at all (fail on the first refusal).
    pub lock_wait_secs: u64,
    /// Name sessions: a name derived from the opening message before the first request, and at
    /// most one small-model call per session to replace it with a better one. The call goes to
    /// `provider.aux` when there is one, so it costs the cheap route and never the turn's model.
    pub autotitle: bool,
}

impl Default for SessionsConfig {
    fn default() -> Self {
        Self {
            dir: None,
            retention_keep_days: 0,
            retention_keep_count: 0,
            auto_prune: false,
            lock_wait_secs: 30,
            autotitle: true,
        }
    }
}

#[derive(Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct WebConfig {
    pub host: String,
    pub port: u16,
    /// Dashboard login secret, generated by `config init`. The dashboard refuses to
    /// start without one.
    #[serde(deserialize_with = "empty_is_none")]
    pub auth_token: Option<String>,
    /// How long a browser stays signed in. `0` is read as the default rather than as
    /// "expire immediately", which would make the dashboard unusable.
    pub session_ttl_hours: u64,
    /// Which profile the dashboard serves when neither `--profile` nor `ECLIPSE_PROFILE`
    /// names one. `None` means the `default` profile.
    #[serde(deserialize_with = "empty_is_none")]
    pub default_profile: Option<String>,
}

impl Default for WebConfig {
    fn default() -> Self {
        Self {
            host: "127.0.0.1".into(),
            port: 8787,
            auth_token: None,
            session_ttl_hours: DEFAULT_SESSION_TTL_HOURS,
            default_profile: None,
        }
    }
}

/// `[gateway]`: the one long-lived process that keeps the whole thing running.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct GatewayConfig {
    /// How often the gateway runs the update check and logs what it found. Log-only: a version
    /// change is a decision, and the gateway is not the place to make it. `0` turns the check
    /// off.
    pub check_interval_hours: u64,
    /// How long a session created by `POST /v1/chat/completions` is kept. The loop stores every
    /// turn, so each API call leaves one behind; they are tagged `api` and swept after this many
    /// hours, so a script polling the endpoint cannot fill the store. `0` keeps them forever.
    #[serde(default = "default_api_session_ttl_hours")]
    pub api_session_ttl_hours: u64,
}

pub fn default_api_session_ttl_hours() -> u64 {
    24
}

impl Default for GatewayConfig {
    fn default() -> Self {
        Self {
            check_interval_hours: 6,
            api_session_ttl_hours: default_api_session_ttl_hours(),
        }
    }
}

/// How long a dashboard login lasts before the browser has to sign in again.
pub const DEFAULT_SESSION_TTL_HOURS: u64 = 12;

/// What the CLI does when a tool's policy is `ask`.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Approval {
    /// Prompt. The default, and the only setting that lets you see what a tool is about to do.
    #[default]
    Ask,
    /// Never prompt: behave as if `--yes` were always passed.
    Auto,
    /// Ask the aux route (`#340`). An `ask`-policy call is put to a cheap model as **allow**,
    /// **deny** or **escalate**; only the escalate costs a card. A `deny` policy is untouched —
    /// the judge may clear a call that was going to be asked about, never widen the registry —
    /// and every doubt (a dead route, a timeout, an answer in the wrong words) escalates, because
    /// a timeout that read as "carry on" would be a command nobody approved.
    Smart,
}

/// Terminal behaviour. Every field here is read by the CLI; a setting nothing reads is a lie
/// in the starter config.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct CliConfig {
    /// Colour. `None` means decide from the stream: a terminal, and `NO_COLOR` unset.
    pub color: Option<bool>,
    /// Markdown in replies. `None` means on when colour is on, off when piping.
    pub markdown: Option<bool>,
    /// What an `ask` policy does. `"ask"` prompts, `"auto"` never does, `"smart"` asks the aux
    /// route first and escalates to you when it is unsure.
    pub approval: Approval,
    /// How many commands the REPL remembers for arrow-up.
    pub history_size: usize,
    /// What an interactive exit does to the screen.
    pub clear_on_exit: ClearOnExit,
}

impl Default for CliConfig {
    fn default() -> Self {
        Self {
            color: None,
            markdown: None,
            approval: Approval::Ask,
            // Matches the constant the REPL used before this was configurable.
            history_size: 1000,
            clear_on_exit: ClearOnExit::Screen,
        }
    }
}

/// What an interactive exit does to the screen: `[cli] clear_on_exit`.
///
/// The interface draws in the terminal's ordinary buffer, so its last frame survives the process
/// and the shell prompt lands underneath it — which reads exactly like a crash. Clearing and
/// printing one line says which of the two happened.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ClearOnExit {
    /// Clear the visible screen and keep the scrollback. The default: what was scrolled past is
    /// the reader's own copy/paste history, and this program deliberately does not own it.
    #[default]
    Screen,
    /// Clear the visible screen and the scrollback behind it.
    All,
    /// Clear nothing; the goodbye line is simply printed where the frame ended.
    Off,
}

/// How often the update notice asks the public repository for its latest commit.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum UpdateCheck {
    /// At most once a day. The default: a notice that arrives a month late is not a notice.
    #[default]
    Daily,
    Weekly,
    /// Never. No request is made, and nothing is cached.
    Off,
}

impl UpdateCheck {
    /// Seconds that must pass between two checks, `None` for `Off`.
    pub fn period_secs(self) -> Option<u64> {
        match self {
            UpdateCheck::Daily => Some(86_400),
            UpdateCheck::Weekly => Some(7 * 86_400),
            UpdateCheck::Off => None,
        }
    }
}

/// Which branch a *source* install follows: `[update] track`.
///
/// Two names, because there are two long-lived branches and nothing else: `main` only ever takes
/// a release or a hotfix, `develop` is where work lands. `release` and `main` are one ref by
/// construction, so a second word for the branch would be the confusion the branch model exists
/// to end — the key names a track, and a track names a branch.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Track {
    /// `main`: the branch releases are cut from, and what every install did before the key
    /// existed. The default.
    #[default]
    Release,
    /// `develop`: the branch work lands on — tomorrow's commits, for a checkout that wants them.
    Develop,
}

impl Track {
    /// The word the setting takes and the surfaces print.
    pub fn label(self) -> &'static str {
        match self {
            Track::Release => "release",
            Track::Develop => "develop",
        }
    }

    /// The branch it follows. `release` is `main`; this is why the key names a track rather than
    /// making a person choose between two words for one branch.
    pub fn branch(self) -> &'static str {
        match self {
            Track::Release => "main",
            Track::Develop => "develop",
        }
    }
}

/// `[hooks]`: which in-process loop hooks run, and their settings.
///
/// `order` is the composition order, and the only list: a hook that is not named in it does
/// not run, and a settings table for a hook that is not named in it is refused at load rather
/// than quietly never used. Absent, it is `["redact-secrets"]`; `order = []` runs nothing.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct HooksConfig {
    pub order: Vec<String>,
    /// The `[hooks.<name>]` tables. Read as loose TOML so the parser drops nothing: every key
    /// here is checked by [`crate::hooks::validate`], which names the one that is wrong.
    #[serde(flatten)]
    pub settings: BTreeMap<String, toml::Value>,
}

impl Default for HooksConfig {
    fn default() -> Self {
        Self {
            order: crate::hooks::DEFAULT_ORDER
                .iter()
                .map(|n| n.to_string())
                .collect(),
            settings: BTreeMap::new(),
        }
    }
}

/// `[update]`: the notice that says a newer commit exists. It is the only request this tool
/// makes that is neither a model call nor something the user asked for, so it has a switch.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct UpdateConfig {
    pub check: UpdateCheck,
    /// Which branch a *source* install follows: `release` is `main`, `develop` is the branch work
    /// lands on. The ref comes from here rather than from the checkout's upstream, so a checkout
    /// parked on a feature branch is refused instead of quietly becoming an update channel
    /// nobody chose. A `release` install has no branch to follow at all: it compares tags, and
    /// `eclipse upgrade` refuses the develop track there rather than pretending.
    pub track: Track,
    /// Where the latest commit is asked for, instead of the public GitHub repository: an
    /// http(s) URL that answers with a commit id, either as the whole body or as a JSON
    /// object with a `sha` field. Because the user wrote it, it may be a host on a private
    /// network, which the `fetch` tool's public-hosts rule would refuse.
    #[serde(deserialize_with = "empty_is_none")]
    pub remote: Option<String>,
    /// Where the newest release is asked for, instead of the public GitHub repository: an
    /// http(s) URL answering with the same JSON shape (`tag_name`, `assets[].name` and
    /// `assets[].browser_download_url`). `eclipse upgrade` on a release install reads its
    /// download URLs from this answer, so a mirror is a mirror. May be a host on your network.
    #[serde(deserialize_with = "empty_is_none")]
    pub releases: Option<String>,
}

impl fmt::Debug for WebConfig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("WebConfig")
            .field("host", &self.host)
            .field("port", &self.port)
            .field(
                "auth_token",
                &self.auth_token.as_ref().map(|_| "<redacted>"),
            )
            .finish()
    }
}

/// `[attachments]`: where the pictures someone attaches are kept (`#499`).
///
/// A picture has two facts that used to conflict — the original file, and a small payload the wire
/// will carry — and keeping both means keeping files. These are the two decisions that follow: where
/// they go, and how much room they may take.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct AttachmentsConfig {
    /// Where pictures are stored. `None` means `<state_dir>/attachments` — not the workspace,
    /// which the agent writes to (a `write_file` could clobber a photo, and `git status` in a
    /// project should not list someone's holiday snap), and not a temp directory, which is pruned.
    pub dir: Option<PathBuf>,
    /// Ceiling for everything kept, in bytes. The oldest files are pruned when an attach would
    /// exceed it; only if pruning cannot free enough is the attach refused. 0 = no ceiling, which
    /// is the one setting here worth being deliberate about.
    pub max_total_bytes: u64,
}

impl Default for AttachmentsConfig {
    fn default() -> Self {
        Self {
            dir: None,
            max_total_bytes: 2 * 1024 * 1024 * 1024,
        }
    }
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct Config {
    /// The `config_version` the file was written with, and the one thing here that is metadata
    /// rather than a setting: it is not in the catalogue, `config set` refuses it, and the agent
    /// never reads it. `0` means "written before the stamp existed" and is the version every
    /// install older than this key reports.
    ///
    /// Top-level because it describes the file, and it must survive a section rename.
    pub config_version: u32,
    pub provider: ProviderConfig,
    pub agent: AgentConfig,
    pub tools: ToolsConfig,
    pub sessions: SessionsConfig,
    pub attachments: AttachmentsConfig,
    pub plugins: PluginsConfig,
    pub web: WebConfig,
    pub gateway: GatewayConfig,
    pub cli: CliConfig,
    pub update: UpdateConfig,
    pub hooks: HooksConfig,
    pub context: ContextPolicyConfig,
    pub user: UserConfig,
    pub skills: SkillsConfig,
    pub vision: VisionConfig,
    /// Which profile this was loaded as. Not part of the file: it comes from `--profile` /
    /// `ECLIPSE_PROFILE`, and only decides which overlay and which directories apply.
    #[serde(skip)]
    pub profile: Option<String>,
    /// The route a run is pinned to (`--route`, else `ECLIPSE_ROUTE`). Not part of the file:
    /// pinning is a decision about one invocation. Set through [`Config::pin_route`].
    #[serde(skip)]
    pub route_pin: Option<String>,
    /// Which `.env` files were read and what they held. Not part of the file, and never
    /// serialised: values are exactly what must not be printed.
    #[serde(skip)]
    pub dotenv: Dotenv,
    /// `[[mcp]]`: MCP servers declared in `config.toml` (`#352`). The same spec a plugin manifest
    /// carries — one loader, two providers — and the one a name clash with a manifest wins, because
    /// this file is somebody's decision about this machine while a manifest is what a plugin
    /// shipped. Tools they list are reported as `config:mcp:<server>`.
    #[serde(default)]
    pub mcp: Vec<crate::mcp::Spec>,
    /// `--no-mcp`: start no MCP server for this process. Not part of the file — it is a decision
    /// about one invocation, and it exists because a server that hangs at startup must not be
    /// able to lock someone out of their own agent.
    #[serde(skip)]
    pub no_mcp: bool,
    /// `[flares]`: the budget and cap defaults a flare run starts from (`#171`).
    #[serde(default)]
    pub flares: FlaresConfig,
    /// `[bots.<name>]`: named agent identities (`#509`). A bot is a declaration plus one session
    /// whose `origin` is `bot:<name>` — no second runtime and no second store. The gateway reads
    /// this table at startup, keeps an agent per bot, and the Bots tab lists what it found.
    #[serde(default)]
    pub bots: std::collections::BTreeMap<String, BotConfig>,
}

/// `[flares]`: what a run costs and how wide it may go (`#171`).
///
/// Every number here is a limit, not a promise: a run is N jobs the lead named, and these are
/// what stops an N from being expensive. `count` is only the default for `flares run -n` — the
/// model-facing tool never gets a count, it names its jobs.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct FlaresConfig {
    /// The default for `flares run -n`, and the number a local run starts from. An accidental
    /// fan-out on a server that serves one model at a time is ten minutes of serial turns.
    pub count: usize,
    /// The most flares one run may have in flight, whatever the routes would allow.
    pub max_concurrent: usize,
    /// Per flare, when the job does not say: the same budget `delegate` gives a child.
    pub max_iterations: usize,
    /// The run's own budget. Not `count x max_iterations` in disguise: this is what stops one
    /// wandering flare before it eats the budget of the three beside it.
    pub total_iterations: usize,
    /// Optional spend cap for the whole run, in tokens. Unset: no cap beyond iterations.
    pub total_tokens: Option<u64>,
}

impl Default for FlaresConfig {
    fn default() -> Self {
        Self {
            count: 3,
            max_concurrent: 4,
            max_iterations: 6,
            total_iterations: 24,
            total_tokens: None,
        }
    }
}

impl FlaresConfig {
    /// What this config can actually do: `max_concurrent`, floored by the slots the named routes
    /// bring, and never below one.
    pub fn concurrency(&self) -> usize {
        self.max_concurrent.max(1)
    }

    /// How many iterations one flare gets when its job does not say.
    pub fn per_flare(&self) -> usize {
        self.max_iterations.max(1)
    }

    /// The run's budget as written. Deliberately **not** floored at one flare's worth: a run set
    /// to two iterations with a per-flare default of six gives its first flare two and drops the
    /// rest, and saying so is more honest than quietly raising the number the operator typed.
    pub fn budget(&self) -> usize {
        self.total_iterations.max(1)
    }
}

/// `[bots.<name>]`: one named agent identity (`#509`).
///
/// Every key is optional, because a bot with no keys is still a bot: a session of its own, in
/// the list, with the agent's ordinary prompt. What each key overrides is *only* that bot's run —
/// the instructions are added to the system prompt rather than replacing it, and nothing here
/// changes what the human's own sessions see.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct BotConfig {
    /// The file this bot's instructions are read from, relative to this profile's directory
    /// unless absolute. **Added** to the assembled system prompt, never a replacement: the run is
    /// still the CLI/web agent with the bot's words in front of it.
    pub instructions: Option<String>,
    /// The skills this bot may see, by name. Absent leaves every root in force; an empty list is
    /// a bot that sees none — the difference exists because "I declared nothing" and "I declared
    /// nothing for it" are not the same sentence.
    pub skills: Option<Vec<String>>,
    /// Where this bot's `MEMORY.md` lives, relative to this profile's directory unless absolute.
    /// Unset means `<profile>/memory/bots/<name>/MEMORY.md`, so a bot's memory is its own file
    /// whether or not anyone said where.
    pub memory: Option<String>,
    /// The lane that reaches this bot. Unset means web only; `telegram` is slice 3 and is not
    /// wired yet, so naming it is refused at startup rather than silently ignored.
    pub adapter: Option<String>,
}

/// The adapters this build can actually drive (`#509`). Slice 3 adds `telegram`; a name that is
/// not here is reported by `problems` rather than refused, because the declaration is still
/// worth writing down today — the bot answers on the web and the lane arrives with slice 3.
pub const BOT_ADAPTERS: &[&str] = &[];

/// `[context]`: how a request that no longer fits is shortened. The head (first turn) and
/// the tail (newest turns) stay verbatim; what pays is the middle.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct ContextPolicyConfig {
    /// Share of the model's window at which a request is compacted, e.g. `0.85`. `0` turns the
    /// threshold off, which leaves only an explicit `provider.context_budget_tokens` as a rail.
    pub compact_at: f64,
    /// Turns kept verbatim at the tail. `0` is read as `1`: the newest turn is never dropped.
    pub protect_last_n: usize,
    /// Ask one model one bounded question about *why* the dropped turns went the way they did,
    /// and take its answer only if every name in it appears in the digest it was written from.
    /// Off by default: it is the one part of compaction that spends a provider request.
    pub judge: bool,
    /// How long that one call may take before the deterministic handoff ships without it.
    pub judge_timeout_secs: u64,
    /// The window to assume when the endpoint advertises none (`/props`, `/v1/models`). `0`
    /// means assume nothing: a request is never shortened on a guessed window.
    pub window_tokens: usize,
    /// Hard cap, in characters, on the compiled handoff that stands in for the dropped middle.
    /// A handoff that grows to fill the window would defeat the point of compacting it.
    pub handoff_chars: usize,
}

impl Default for ContextPolicyConfig {
    fn default() -> Self {
        Self {
            compact_at: 0.85,
            protect_last_n: crate::context::DEFAULT_PROTECT_LAST_N,
            judge: true,
            judge_timeout_secs: 20,
            window_tokens: 0,
            handoff_chars: 6_000,
        }
    }
}

impl ContextPolicyConfig {
    /// The budget this policy derives from a window, or 0 when the policy is off.
    pub fn budget_for(&self, window_tokens: usize) -> usize {
        if window_tokens == 0 || self.compact_at.is_nan() || self.compact_at <= 0.0 {
            return 0;
        }
        (window_tokens as f64 * self.compact_at) as usize
    }

    /// `compact_at` is a share of a window, so anything outside (0, 1] is a mistake worth
    /// naming rather than a silently useless rail.
    pub fn validate(&self) -> Result<()> {
        if !(0.0..=1.0).contains(&self.compact_at) {
            return Err(Error::Config(format!(
                "context.compact_at: {} is not a share of the window; use 0.85 for 85%, or 0 to \
                 turn the threshold off",
                self.compact_at
            )));
        }
        if self.handoff_chars < 200 {
            return Err(Error::Config(format!(
                "context.handoff_chars: {} is too small to compile a handoff; 200 is the floor \
                 and 6000 is the default",
                self.handoff_chars
            )));
        }
        Ok(())
    }
}

/// `[user]`: the user model and the agent's memory file.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct UserConfig {
    /// The user model, relative to this profile's config directory unless absolute.
    pub file: String,
    /// The agent's memory file, same resolution.
    pub memory_file: String,
    /// Ceiling for `MEMORY.md` in characters. The `memory` tool refuses past this rather than
    /// silently overwriting what is already there.
    pub memory_budget_chars: usize,
}

impl Default for UserConfig {
    fn default() -> Self {
        Self {
            file: "USER.md".into(),
            memory_file: "MEMORY.md".into(),
            memory_budget_chars: crate::memory::DEFAULT_BUDGET_CHARS,
        }
    }
}

/// `[skills]`: how much of the prompt the skills index may take.
///
/// One field, because one thing reads it. Where skills are searched is fixed by the layout
/// (shared, profile, workspace, plugins), and a skill is off by being absent; a `dirs` or
/// `enabled` key would be a setting nothing consumes.
/// `[vision]`: what happens to a picture on a turn (`#346`).
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct VisionConfig {
    /// `native`, `text` or `auto`. The default is `auto`: a model that declares vision gets the
    /// bytes, a model that does not gets a description instead.
    #[serde(default)]
    pub mode: VisionMode,
    /// The route that describes pictures, for `text` and for `auto`'s fallback. Empty means there
    /// is none, which makes `text` a refusal rather than a silent no-op.
    #[serde(default)]
    pub route: String,
    /// Let a description leave this machine. Off by default: a screenshot is the most private
    /// thing this agent touches, and "it went to an API once" cannot be undone by reading a log.
    #[serde(default)]
    pub allow_cloud: bool,
}

/// The three modes, spelled in the file the way a person would say them.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum VisionMode {
    /// The turn's own model sees the picture, or the attach is refused.
    Native,
    /// The picture is described by `[vision] route` and the turn model reads the description.
    Text,
    /// Native when the turn model declares vision, a description otherwise.
    #[default]
    Auto,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct SkillsConfig {
    /// Ceiling for the index in the system prompt, in characters. Entries that do not fit are
    /// left out and named in `eclipse context show`; 0 = no cap.
    pub index_budget_chars: usize,
}

impl Default for SkillsConfig {
    fn default() -> Self {
        Self {
            index_budget_chars: crate::skills::DEFAULT_INDEX_BUDGET_CHARS,
        }
    }
}

/// `[plugins]`: where plugins live and which ones may load.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct PluginsConfig {
    /// Root of the shared plugin directory (default `<config_dir>/plugins`). A profile's
    /// own `plugins/` directory is always searched first.
    pub dir: Option<PathBuf>,
    /// Allowlist. A plugin that is not listed is not loaded; an empty list loads none.
    pub enabled: Vec<String>,
    /// Default ceiling for one MCP server call, for `[[mcp]]` entries that state no
    /// `timeout_secs` of their own. Clamped to 1–600 s like any plugin timeout.
    pub mcp_timeout_secs: Option<u64>,
}

impl Config {
    /// Load from `explicit` (must exist) or the default path (optional), then apply
    /// environment overrides, using the real process environment.
    pub fn load(explicit: Option<&Path>) -> Result<Config> {
        Self::load_with(explicit, &process_env)
    }

    pub fn load_with(explicit: Option<&Path>, env: EnvFn) -> Result<Config> {
        Self::load_with_profile(explicit, None, env)
    }

    /// Load the base config, then the profile's overlay (`profiles/<name>/config.toml`, if it
    /// exists) on top of it, then environment overrides. Keys the overlay does not mention
    /// keep the base value; a key it does mention replaces it (tables are merged, so a
    /// profile can change one provider field without restating the rest).
    ///
    /// The profile also comes from `ECLIPSE_PROFILE`; an explicit argument wins. The name
    /// `default` is the default profile: it may still have an overlay and its own plugins,
    /// but its state lives in the plain state directory.
    pub fn load_with_profile(
        explicit: Option<&Path>,
        profile: Option<&str>,
        env: EnvFn,
    ) -> Result<Config> {
        let profile = profile
            .map(str::to_string)
            .or_else(|| env("ECLIPSE_PROFILE"))
            .filter(|p| !p.trim().is_empty());
        if let Some(name) = &profile {
            validate_profile_name(name)?;
        }
        // `.env` is read before the TOML is parsed, because the TOML can reference it:
        // `api_key = "${OPENAI_API_KEY}"` needs the value to exist by the time it is resolved.
        let dotenv = Dotenv::load(env, profile.as_deref())?;
        // One lookup for the whole load: the real environment wins, `.env` fills the gaps — and an
        // empty `.env` value is a gap, not an answer. `process_env`, `${VAR}` interpolation and
        // `pin_route` all treat empty as absent; a raw `.env` value was the one layer that did not,
        // so a half-typed `ECLIPSE_API_KEY=` blanked the key the file already had and requests went
        // out unauthenticated while looking like a server problem.
        let lookup = |k: &str| {
            env(k).or_else(|| {
                dotenv
                    .values
                    .get(k)
                    .filter(|v| !v.is_empty())
                    .map(String::as_str)
                    .map(str::to_string)
            })
        };
        let lookup: EnvFn<'_> = &lookup;

        let base_path = match explicit {
            Some(p) => Some(p.to_path_buf()),
            None => config_path(env).filter(|p| p.exists()),
        };
        // The file a `[hooks]` mistake is blamed on: the overlay when the profile has one.
        let mut hooks_path = base_path.clone();
        let mut value = match &base_path {
            Some(p) => {
                let mut parsed = read_toml(p)?;
                crate::interpolate::in_value(&mut parsed, p, lookup)?;
                parsed
            }
            None => toml::Value::try_from(Config::default())
                .map_err(|e| Error::Config(e.to_string()))?,
        };
        if let Some(name) = &profile {
            if let Some(dir) = profile_dir(env, name) {
                let overlay = dir.join("config.toml");
                if overlay.exists() {
                    let mut over = read_toml(&overlay)?;
                    // The profile's own `.env` is already in `lookup`, so a `${VAR}` here can
                    // refer to a secret only that profile has.
                    crate::interpolate::in_value(&mut over, &overlay, lookup)?;
                    if over.get("hooks").is_some() {
                        hooks_path = Some(overlay.clone());
                    }
                    merge_toml(&mut value, over);
                }
            }
        }
        let mut cfg: Config = value
            .try_into()
            .map_err(|e: toml::de::Error| Error::Parse {
                path: base_path.unwrap_or_else(|| PathBuf::from("<defaults>")),
                message: e.to_string(),
            })?;
        cfg.profile = profile;
        cfg.apply_env(lookup);
        cfg.dotenv = dotenv;
        // At load, so a typo in the route table is the first thing said and not the thing a
        // run trips over once it has already started talking to a server.
        cfg.validate_routes()?;
        cfg.context.validate()?;
        // `#509`: a bot name is parsed back out of `origin` and spelled into a URL, so a name
        // that cannot survive either is a startup error rather than a tab that never lists it.
        cfg.validate_bots()?;
        crate::hooks::validate(&cfg.hooks).map_err(|message| Error::Parse {
            path: hooks_path.unwrap_or_else(|| PathBuf::from("<defaults>")),
            message,
        })?;
        Ok(cfg)
    }

    /// The profile name in effect, `default` when none was selected.
    pub fn profile_name(&self) -> &str {
        self.profile.as_deref().unwrap_or("default")
    }

    /// This profile's state directory (sessions, REPL history).
    pub fn state_dir(&self, env: EnvFn) -> Result<PathBuf> {
        state_dir_for(env, self.profile.as_deref())
            .ok_or_else(|| Error::Config("cannot determine state dir: HOME is not set".into()))
    }

    /// Where plugins are looked for, in order: this profile's own `plugins/` directory
    /// first, then the shared one (`[plugins] dir`, else `<config_dir>/plugins`). A profile
    /// copy of a plugin shadows the shared copy.
    pub fn plugins_dirs(&self, env: EnvFn) -> Vec<PathBuf> {
        let mut out = Vec::new();
        if let Some(name) = &self.profile {
            if let Some(dir) = profile_dir(env, name) {
                out.push(dir.join("plugins"));
            }
        }
        let shared = match &self.plugins.dir {
            Some(p) => expand_tilde(p, env),
            None => match config_dir(env) {
                Some(d) => d.join("plugins"),
                None => return out,
            },
        };
        if !out.contains(&shared) {
            out.push(shared);
        }
        out
    }

    pub fn from_file(path: &Path) -> Result<Config> {
        let text = std::fs::read_to_string(path).map_err(|e| Error::io(path, e))?;
        Self::from_toml_str(&text).map_err(|message| Error::Parse {
            path: path.to_path_buf(),
            message,
        })
    }

    pub fn from_toml_str(text: &str) -> std::result::Result<Config, String> {
        toml::from_str(text).map_err(|e| e.to_string())
    }

    /// `ECLIPSE_BASE_URL`, `ECLIPSE_API_KEY`, `ECLIPSE_MODEL`.
    ///
    /// These describe `[provider]`, the `default` route, and nothing else: one variable cannot
    /// sensibly be the key for every route in a chain. A named route takes its key from its
    /// own `api_key_env`.
    pub fn apply_env(&mut self, env: EnvFn) {
        if let Some(v) = env("ECLIPSE_BASE_URL") {
            self.provider.base_url = v;
        }
        if let Some(v) = env("ECLIPSE_MODEL") {
            self.provider.model = v;
        }
        // Only when `[provider]` is in use: a config that is all routes must not grow a
        // phantom `default` route because the shell happened to export a key.
        if self.provider.declares_connection() {
            apply_key_env(&mut self.provider, env, env("ECLIPSE_API_KEY"));
        }
        for route in &mut self.provider.route {
            apply_key_env(&mut route.config, env, None);
        }
    }

    /// Serialise to TOML with every secret-looking value replaced, safe to print.
    ///
    /// Redaction follows the key name rather than a list of known fields, so a new setting
    /// called `api_token` is covered the day it is added instead of the day someone
    /// remembers to add it here.
    pub fn to_toml_redacted(&self) -> Result<String> {
        let mut value = toml::Value::try_from(self).map_err(|e| Error::Config(e.to_string()))?;
        redact(&mut value);
        toml::to_string_pretty(&value).map_err(|e| Error::Config(e.to_string()))
    }

    /// Fail early, with an actionable message, if the provider is not configured.
    pub fn require_provider(&self) -> Result<()> {
        self.chain().map(|_| ())
    }

    /// The routes the file declares, `default` first when `[provider]` is in use.
    ///
    /// With no routes at all `default` is always listed, so a bare config still has one
    /// route and says what is wrong with it rather than that it has none.
    pub fn declared_routes(&self) -> Vec<NamedRoute> {
        let mut out = Vec::new();
        if self.provider.route.is_empty() || self.provider.declares_connection() {
            out.push(NamedRoute::new(DEFAULT_ROUTE, &self.provider));
        }
        out.extend(self.provider.route.iter().map(|r| {
            NamedRoute::new(&r.name, &r.config).with_flare_shape(r.max_parallel, r.group.clone())
        }));
        out
    }

    /// The routes that exist, for a sentence that has to name them.
    pub fn route_names(&self) -> String {
        let names: Vec<String> = self.declared_routes().into_iter().map(|r| r.name).collect();
        if names.is_empty() {
            "none".to_string()
        } else {
            names.join(", ")
        }
    }

    /// Check the route table: every rule is something a run would otherwise find out halfway
    /// through, and each message names the route or the key at fault.
    ///
    /// `[provider]` itself is not checked here — whether `base_url` and `model` are set is
    /// asked when a run needs it ([`Config::chain`]), which is why `config show` and
    /// `config init` work on a half-written file.
    pub fn validate_routes(&self) -> Result<()> {
        let p = &self.provider;
        let mut seen: Vec<&str> = Vec::new();
        for (i, r) in p.route.iter().enumerate() {
            let name = r.name.trim();
            if name.is_empty() {
                return Err(Error::Config(format!(
                    "provider.route #{} has no name; every [[provider.route]] needs `name = \"...\"`",
                    i + 1
                )));
            }
            if seen.contains(&name) {
                return Err(Error::Config(format!(
                    "two routes are named `{name}`; route names must be unique"
                )));
            }
            seen.push(name);
            if name == DEFAULT_ROUTE && p.declares_connection() {
                return Err(Error::Config(format!(
                    "a route is named `{DEFAULT_ROUTE}`, but `[provider]` is also set and is the \
                     route of that name; rename the route, or move its settings out of [provider]"
                )));
            }
            if r.config.fallback.is_some()
                || r.config.aux.is_some()
                || r.config.delegate.is_some()
                || !r.config.route.is_empty()
            {
                return Err(Error::Config(format!(
                    "route `{name}` has its own `fallback`, `aux`, `delegate` or `route`; those \
                     belong directly under [provider], not inside a route"
                )));
            }
            if r.config.base_url.trim().is_empty() {
                return Err(Error::Config(format!(
                    "route `{name}` has no base_url; a route is a complete provider \
                     configuration and does not inherit from [provider]"
                )));
            }
            if r.config.model.trim().is_empty() {
                return Err(Error::Config(format!(
                    "route `{name}` has no model; a route is a complete provider \
                     configuration and does not inherit from [provider]"
                )));
            }
        }
        if let Some(fallback) = &p.fallback {
            if fallback.is_empty() {
                return Err(Error::Config(
                    "provider.fallback is empty; name the routes to try in order, or remove the \
                     key to use `default` alone"
                        .into(),
                ));
            }
            let known: Vec<String> = self.declared_routes().into_iter().map(|r| r.name).collect();
            let mut listed: Vec<&str> = Vec::new();
            for name in fallback {
                if !known.contains(name) {
                    return Err(Error::Config(format!(
                        "provider.fallback names `{name}`, which is not a route. Routes that \
                         exist: {}",
                        self.route_names()
                    )));
                }
                if listed.contains(&name.as_str()) {
                    return Err(Error::Config(format!(
                        "provider.fallback lists `{name}` twice; each route is tried at most \
                         once per run"
                    )));
                }
                listed.push(name);
            }
            // `[provider]` set a connection key, so it *is* the route `default` — and `fallback`
            // is the whole chain, without it. The endpoint the user wrote down would never be
            // called. Refused rather than run: both ways out are one word, and a chain that
            // quietly omits the primary is the kind of thing found months later from a bill.
            if p.declares_connection() && !listed.contains(&DEFAULT_ROUTE) {
                return Err(Error::Config(
                    "`[provider]` sets a connection, but provider.fallback is the whole chain \
                     and does not list `default`, so that endpoint would never be called. Put \
                     `default` first in `fallback`, or move the connection keys into a route \
                     and leave `[provider]` to `fallback` alone"
                        .into(),
                ));
            }
        }
        if let Some(aux) = &p.aux {
            if aux.trim().is_empty() {
                return Err(Error::Config(
                    "provider.aux is empty; name the route that does housekeeping, or remove \
                     the key to use the route the run is on"
                        .into(),
                ));
            }
            if !self.declared_routes().iter().any(|r| &r.name == aux) {
                return Err(Error::Config(format!(
                    "provider.aux names `{aux}`, which is not a route. Routes that exist: {}",
                    self.route_names()
                )));
            }
        }
        if let Some(delegate) = &p.delegate {
            if delegate.trim().is_empty() {
                return Err(Error::Config(
                    "provider.delegate is empty; name the route subagents run on, or remove \
                     the key to use the route the run is on"
                        .into(),
                ));
            }
            if !self.declared_routes().iter().any(|r| &r.name == delegate) {
                return Err(Error::Config(format!(
                    "provider.delegate names `{delegate}`, which is not a route. Routes that \
                     exist: {}",
                    self.route_names()
                )));
            }
        }
        // `[vision] route` is checked here for the same reason `aux` is: a name that matches no
        // route would otherwise be a picture described by the fallback route the run happens to be
        // on, which is a picture sent somewhere nobody chose (`#346`).
        let vision_route = self.vision.route.trim();
        if !vision_route.is_empty()
            && !self
                .declared_routes()
                .iter()
                .any(|r| r.name == vision_route)
        {
            return Err(Error::Config(format!(
                "vision.route names `{vision_route}`, which is not a route. Routes that exist: {}",
                self.route_names()
            )));
        }
        Ok(())
    }

    /// Pin this configuration to a route, or leave it unpinned.
    ///
    /// `flag` is `--route`; without it `ECLIPSE_ROUTE` is read from the environment and then
    /// from the `.env` chain, the same layering every other `ECLIPSE_*` setting has. An unknown
    /// name is an error that lists the routes that exist, here rather than after a run starts.
    pub fn pin_route(&mut self, flag: Option<&str>, env: EnvFn) -> Result<()> {
        let wanted = match flag {
            Some(name) if name.trim().is_empty() => {
                return Err(Error::Config(
                    "--route needs a route name; `eclipse config show` lists them".into(),
                ))
            }
            Some(name) => Some(name.trim().to_string()),
            None => env("ECLIPSE_ROUTE")
                .or_else(|| self.dotenv.values.get("ECLIPSE_ROUTE").cloned())
                .map(|v| v.trim().to_string())
                .filter(|v| !v.is_empty()),
        };
        if let Some(name) = &wanted {
            if !self.declared_routes().iter().any(|r| &r.name == name) {
                return Err(self.unknown_route(name));
            }
        }
        self.route_pin = wanted;
        Ok(())
    }

    fn unknown_route(&self, name: &str) -> Error {
        Error::Config(format!(
            "unknown route `{name}`. Routes that exist: {}",
            self.route_names()
        ))
    }

    /// The routes a run will use, in order, checked.
    ///
    /// A pinned run gets exactly one route and [`ChainSource::Pinned`]: pinning means pinned,
    /// and nothing downstream may fall back from it. Otherwise it is `[provider] fallback`, or
    /// `default` alone, which is every config that existed before routes did.
    pub fn chain(&self) -> Result<Chain> {
        self.validate_routes()?;
        let all = self.declared_routes();
        let find = |name: &str| all.iter().find(|r| r.name == name).cloned();
        let (routes, source) = if let Some(pin) = &self.route_pin {
            let route = find(pin).ok_or_else(|| self.unknown_route(pin))?;
            (vec![route], ChainSource::Pinned)
        } else if let Some(fallback) = &self.provider.fallback {
            // validate_routes proved every name is declared.
            let routes = fallback.iter().filter_map(|n| find(n)).collect();
            (routes, ChainSource::Fallback)
        } else if self.provider.declares_connection() || self.provider.route.is_empty() {
            (
                vec![NamedRoute::new(DEFAULT_ROUTE, &self.provider)],
                ChainSource::Default,
            )
        } else {
            return Err(Error::Config(format!(
                "routes are declared but nothing says which to use: set `[provider] fallback = \
                 [...]`, or pass --route NAME. Routes that exist: {}",
                self.route_names()
            )));
        };
        for route in &routes {
            route.require_endpoint(source)?;
        }
        // A pin wins over the role routes. `--route local` is what you say when the text must
        // not leave that server; a `[provider] aux = "cheap"` or `delegate = "big"` that ignored
        // it would be exactly the leak the pin was meant to close. Recorded as the role routes
        // being unset, with `ChainSource::Pinned` saying why.
        let pinned = source == ChainSource::Pinned;
        let only = routes.first().cloned();
        let (aux, delegate) = if pinned {
            (only.clone(), only)
        } else {
            (
                self.provider.aux.as_deref().and_then(find),
                self.provider.delegate.as_deref().and_then(find),
            )
        };
        if let Some(aux) = &aux {
            aux.require_endpoint(source)?;
        }
        if let Some(delegate) = &delegate {
            delegate.require_endpoint(source)?;
        }
        Ok(Chain {
            routes,
            source,
            aux,
            delegate,
        })
    }

    pub fn sessions_dir(&self, env: EnvFn) -> Result<PathBuf> {
        if let Some(d) = &self.sessions.dir {
            return Ok(expand_tilde(d, env));
        }
        Ok(self.state_dir(env)?.join("sessions"))
    }

    /// `[bots.<name>]`: a bot name is half of a session's `origin` (`bot:<name>`) and a segment of
    /// a dashboard URL, so it is checked once at load rather than at the first request that
    /// spells it — a name with a `:` in it would make its own sessions unparseable.
    ///
    /// Lowercase letters, digits, `-` and `_`, one to thirty-two of them: the same rule a profile
    /// name follows, because it is the same kind of thing (a word a person types, and a path).
    pub fn validate_bots(&self) -> Result<()> {
        for name in self.bots.keys() {
            let ok = !name.is_empty()
                && name.len() <= 32
                && name
                    .chars()
                    .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == '_');
            if !ok {
                return Err(Error::Config(format!(
                    "bots.{name}: a bot name is lowercase letters, digits, `-` and `_`, at most \
                     32 of them — it becomes part of a session's `origin` and a URL"
                )));
            }
        }
        Ok(())
    }

    /// A path from a bot's declaration (`instructions`, `memory`): `~` expanded, and a relative
    /// path taken from this profile's own directory, the same rule `[user] file` follows.
    pub fn bot_file(&self, env: EnvFn, path: &str) -> Option<PathBuf> {
        let path = expand_tilde(Path::new(path), env);
        if path.is_absolute() {
            Some(path)
        } else {
            self.context_dir(env).map(|dir| dir.join(path))
        }
    }

    /// Where a bot's `MEMORY.md` lives: its declaration, else `<profile>/memory/bots/<name>/` with
    /// the human's own file name. Always a file of its own — the one thing a bot must not share
    /// with the person it answers.
    pub fn bot_memory(&self, env: EnvFn, name: &str, bot: &BotConfig) -> Option<PathBuf> {
        match bot.memory.as_deref().filter(|m| !m.trim().is_empty()) {
            Some(m) => self.bot_file(env, m),
            None => self
                .memory_dir(env)
                .map(|dir| dir.join("bots").join(name).join(&self.user.memory_file)),
        }
    }

    /// Where attached pictures are kept (`#499`): the override, else `<state_dir>/attachments`.
    ///
    /// `None` when neither can be worked out — no `HOME`, no `ECLIPSE_HOME` and no override — which
    /// the caller reports rather than guessing a directory the agent would write to.
    pub fn attachments_dir(&self, env: EnvFn) -> Option<PathBuf> {
        if let Some(dir) = &self.attachments.dir {
            return Some(expand_tilde(dir, env));
        }
        self.state_dir(env).ok().map(|d| d.join("attachments"))
    }

    /// The four answers a person needs when a profile surprises them: which profile, from which
    /// file, under which home, writing sessions where.
    ///
    /// Every one of them comes from the function that already answers it — `home_root`,
    /// `config_path`, `sessions_dir` — so `/profile`, `/settings` and `eclipse doctor` cannot
    /// disagree the first time `[sessions] dir` or `ECLIPSE_HOME` moves. `loaded` is the file the
    /// caller actually read: `--config` may point outside the root, and naming the default path
    /// while running from another one is exactly the mistake this reports.
    pub fn where_am_i(&self, env: EnvFn, loaded: Option<&Path>) -> Where {
        let overlay = self
            .profile
            .as_deref()
            .filter(|name| *name != "default")
            .and_then(|name| profile_dir(env, name))
            .map(|dir| dir.join("config.toml"))
            .filter(|path| path.exists());
        Where {
            profile: self.profile.clone(),
            config: loaded.map(Path::to_path_buf).or_else(|| config_path(env)),
            overlay,
            home: home_root(env),
            sessions: self.sessions_dir(env).ok(),
        }
    }

    /// The directory this profile's own files live in: `<config>/profiles/<name>` for a named
    /// profile, the config directory itself for the default one.
    pub fn context_dir(&self, env: EnvFn) -> Option<PathBuf> {
        match &self.profile {
            Some(name) => profile_dir(env, name),
            None => config_path(env)
                .and_then(|p| p.parent().map(Path::to_path_buf))
                .or_else(|| config_dir(env)),
        }
    }

    /// Where this profile's scripts live: `scripts/` under [`Self::context_dir`], so the
    /// profile's own directory when a profile is in effect and the shared one otherwise.
    /// Nothing falls back from one to the other — a profile with no scripts has none, which is
    /// the same rule the profile's `MEMORY.md` follows.
    ///
    /// Always absolute: the path is handed to scripts in `ECLIPSE_SCRIPTS_DIR` and compared
    /// against the paths a model writes, and `--config some/relative/config.toml` would
    /// otherwise make it mean something different from one working directory to the next.
    pub fn scripts_dir(&self, env: EnvFn) -> Option<PathBuf> {
        let dir = self.context_dir(env)?.join("scripts");
        if dir.is_absolute() {
            return Some(dir);
        }
        std::env::current_dir().ok().map(|cwd| cwd.join(dir))
    }

    /// Where the agent's memory lives: `memory/` under this profile's directory. `AGENT.md`,
    /// `USER.md` and `MEMORY.md` all sit here, because "what the agent has been told" is one
    /// thing and answering "where is it?" with three directories is how you end up with a
    /// `SOUL.md` nobody remembers writing.
    ///
    /// `[user] file` and `[user] memory_file` may still be absolute, and an absolute path wins —
    /// `Path::join` refuses to descend into one.
    pub fn memory_dir(&self, env: EnvFn) -> Option<PathBuf> {
        self.context_dir(env).map(|d| d.join("memory"))
    }

    /// Where the global `AGENT.md` lives (the config directory, whatever `--config` says).
    pub fn global_context_dir(&self, env: EnvFn) -> Option<PathBuf> {
        config_path(env)
            .and_then(|p| p.parent().map(Path::to_path_buf))
            .or_else(|| config_dir(env))
    }

    pub fn home(&self, env: EnvFn) -> Option<PathBuf> {
        home_dir(env)
    }

    pub fn workspace_root(&self, env: EnvFn) -> PathBuf {
        match &self.tools.workspace_root {
            Some(p) => expand_tilde(p, env),
            None => std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
        }
    }
}

/// Where this process is running from — the four answers [`Config::where_am_i`] fills in.
///
/// One struct rather than four calls at each site, because four answers worked out in four places
/// is how `/profile` and `eclipse doctor` come to name different session directories the first
/// time `[sessions] dir` moves.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Where {
    /// `None` for the default profile: `default` is not a directory, it is the absence of one.
    pub profile: Option<String>,
    /// The base file this process read — `--config`, else the default path. `None` when it was
    /// started without one. A profile is an overlay *on top of* this, not a replacement.
    pub config: Option<PathBuf>,
    /// The profile's own `config.toml`, when it has one. Read after the base, so it wins.
    pub overlay: Option<PathBuf>,
    /// The root everything lives under: `~/.eclipse`, or `$ECLIPSE_HOME`.
    pub home: Option<PathBuf>,
    /// `[sessions] dir`, else `<state>/sessions`.
    pub sessions: Option<PathBuf>,
}

impl Where {
    /// The name to print: `default` when none was chosen.
    pub fn name(&self) -> &str {
        self.profile.as_deref().unwrap_or("default")
    }

    /// Whether this is the default profile — the one whose files sit in the root itself rather
    /// than under `profiles/<name>`.
    pub fn is_default(&self) -> bool {
        matches!(self.profile.as_deref(), None | Some("default"))
    }
}

/// Read and parse one TOML file, with an error that names it.
fn read_toml(path: &Path) -> Result<toml::Value> {
    let text = std::fs::read_to_string(path).map_err(|e| Error::io(path, e))?;
    toml::from_str::<toml::Value>(&text).map_err(|message| Error::Parse {
        path: path.to_path_buf(),
        message: message.to_string(),
    })
}

/// Deep-merge `over` into `base`: tables merge key by key, anything else replaces.
fn merge_toml(base: &mut toml::Value, over: toml::Value) {
    match (base, over) {
        (toml::Value::Table(base), toml::Value::Table(over)) => {
            for (key, value) in over {
                match base.get_mut(&key) {
                    Some(slot) => merge_toml(slot, value),
                    None => {
                        base.insert(key, value);
                    }
                }
            }
        }
        (slot, over) => *slot = over,
    }
}

/// Replace secret-looking values with `<redacted>`.
fn redact(value: &mut toml::Value) {
    match value {
        toml::Value::Table(table) => {
            for (key, slot) in table.iter_mut() {
                if is_secret_key(key) && matches!(slot, toml::Value::String(s) if !s.is_empty()) {
                    *slot = toml::Value::String("<redacted>".into());
                    continue;
                }
                if is_url_key(key) {
                    if let toml::Value::String(url) = slot {
                        if let Some(clean) = redact_url(url) {
                            *slot = toml::Value::String(clean);
                            continue;
                        }
                    }
                }
                redact(slot);
            }
        }
        toml::Value::Array(items) => items.iter_mut().for_each(redact),
        _ => {}
    }
}

/// A key that holds a secret. `_env` keys are the *name* of a variable, not its value, so
/// they are printed as they are — hiding `api_key_env = "MY_KEY"` would make the output
/// less useful without making it safer.
pub(crate) fn is_secret_key(key: &str) -> bool {
    let k = key.to_ascii_lowercase();
    if k.ends_with("_env") {
        return false;
    }
    // A unit suffix says "a count of these", not "one of these": `window_tokens` is how big the
    // context window is, and redacting it hid a number a person needs to set.
    const COUNTS: &[&str] = &[
        "_tokens",
        "_chars",
        "_secs",
        "_ms",
        "_count",
        "_size",
        "_hours",
        "_days",
        "_bytes",
        "_iterations",
        "_call",
    ];
    if COUNTS.iter().any(|suffix| k.ends_with(suffix)) {
        return false;
    }
    k == "api_key"
        || k.ends_with("_key")
        || k.contains("token")
        || k.contains("secret")
        || k.contains("password")
}

/// A key whose value is a URL the user wrote. Those are printed as they are — a base URL is how you
/// check what you configured — but a URL can carry a secret of its own, so its userinfo and its
/// secret-named query parameters are scrubbed first.
fn is_url_key(key: &str) -> bool {
    let k = key.to_ascii_lowercase();
    k.ends_with("_url") || k == "remote" || k == "releases"
}

/// A URL with its secrets taken out, or `None` when there was nothing to take out.
///
/// Two shapes, both legitimate and both printed verbatim before this existed: a basic-auth gateway
/// (`https://user:pw@gw.internal/v1`) and a token in the query
/// (`https://mirror/releases?access_token=…`). The URL keeps its shape — scheme, host, path and the
/// *names* of its parameters — because that is what makes the printout useful.
fn redact_url(text: &str) -> Option<String> {
    let (body, fragment) = match text.split_once('#') {
        Some((b, f)) => (b, Some(f)),
        None => (text, None),
    };
    let (before_query, query) = match body.split_once('?') {
        Some((b, q)) => (b, Some(q)),
        None => (body, None),
    };
    let mut changed = false;

    // `scheme://user:pass@host/path`: everything between `//` and the last `@` of the authority is
    // credentials. An `@` in the path is not one, which is why this stops at the first `/`.
    let head = match before_query.find("://") {
        Some(scheme_end) => {
            let start = scheme_end + 3;
            let rest = &before_query[start..];
            let authority_end = rest.find('/').unwrap_or(rest.len());
            match rest[..authority_end].rfind('@') {
                Some(at) => {
                    changed = true;
                    format!("{}{}<redacted>{}", &before_query[..start], "", &rest[at..])
                }
                None => before_query.to_string(),
            }
        }
        None => before_query.to_string(),
    };

    let query = query.map(|q| {
        let pairs: Vec<String> = q
            .split('&')
            .map(|pair| {
                let name = pair.split_once('=').map(|(n, _)| n).unwrap_or(pair);
                if !name.is_empty() && is_secret_key(name) {
                    changed = true;
                    format!("{name}=<redacted>")
                } else {
                    pair.to_string()
                }
            })
            .collect();
        pairs.join("&")
    });

    if !changed {
        return None;
    }
    let mut out = head;
    if let Some(q) = query {
        out.push('?');
        out.push_str(&q);
    }
    if let Some(f) = fragment {
        out.push('#');
        out.push_str(f);
    }
    Some(out)
}

/// The keys whose shipped spelling is not their Rust default.
///
/// The file is generated from [`Config::default()`], so everything a struct holds appears without
/// anyone maintaining a list — adding a field is enough. The exceptions are the `Option<String>`
/// keys, which serialise to nothing when unset and would then be the only settings a person could
/// not see. Each ships with the spelling the binary reads as "not in use":
///
/// - `""` for a path, a route, a profile name or an address nobody has chosen yet;
/// - `${VAR:-}` for the two that name a secret, so the value lives in `.env` and a missing
///   variable is "no secret" rather than a config that refuses to load. `${VAR}` without `:-`
///   is a load error naming the key, which is right for a value a config cannot work without and
///   wrong for one it can work without.
///
/// `reasoning_effort` is here for a different reason: its Rust default is `None` on purpose (an
/// undeclared backend must not be handed a field it may reject), while the level a fresh install
/// resolves is the shipped `medium`, and the file is where a person reads that.
const SHIPPED_SPELLING: &[(&str, &str, &str)] = &[
    ("provider", "api_key", "${OPENAI_API_KEY:-}"),
    ("provider", "api_key_env", ""),
    ("provider", "profile", ""),
    (
        "provider",
        "reasoning_effort",
        crate::reasoning::SHIPPED_DEFAULT,
    ),
    ("provider", "aux", ""),
    ("provider", "delegate", ""),
    ("agent", "output_schema", ""),
    ("web", "auth_token", "${ECLIPSE_WEB_AUTH_TOKEN:-}"),
    ("web", "default_profile", ""),
    ("update", "remote", ""),
    ("update", "releases", ""),
    // Not a placeholder: the struct default is `allow`, and the shipped file has asked since the
    // first install. A fresh install that writes files without a prompt would be a regression in
    // everything but the type system, so the stricter value is the one the file carries.
    ("tools", "write_file", "ask"),
    ("tools", "patch", "ask"),
];

/// One entry of [`SHIPPED_SPELLING`] as TOML: quoted, escaped, and identical to what
/// `toml::Value::String` writes, so a spelling that contains `"` or `\` cannot break the file.
fn shipped_text(spelling: &str) -> String {
    toml::Value::String(spelling.to_string()).to_string()
}

/// The order sections appear in the file: the ones a new install edits first, first.
const SECTION_ORDER: &[&str] = &[
    "provider",
    "agent",
    "tools",
    "flares",
    "sessions",
    "attachments",
    "context",
    "plugins",
    "cli",
    "web",
    "gateway",
    "update",
    "hooks",
    "user",
    "skills",
    "vision",
];

/// The shipped `config.toml`: every setting this build reads, and no prose.
///
/// The file is for reading and editing — one key per line, in the section named after the thing it
/// configures, with nothing between the lines to scroll past. The explanation for a key is not
/// here: it is in the manual `eclipse config docs` renders from [`settings::about`], the same
/// string the settings window and `config explain` show. One description per key in the whole
/// product, so it cannot drift from the code.
///
/// Two kinds of line, and the difference is the convention:
///
/// - `key = value` — the setting is in use at that value. `""` and `[]` are how a key whose "off"
///   state is empty is written, and `""` reads back as "not set" ([`empty_is_none`]). A secret is
///   `"${VAR:-}"` so its value lives in `.env` and a missing variable means no secret.
/// - `# key =` — the setting is not in use, and *no* value could express that: a temperature, a
///   cap, a colour, an explicit boolean. TOML has no empty number, so absence is the spelling, and
///   a commented line is how the file still shows the key and where it goes. `config set` turns it
///   into a real line ([`settings::set_in_text`]).
///
/// Generated from the schema, never written by hand: `Config::default()` serialised, plus
/// [`settings::ABSENT_BY_DEFAULT`] for the keys whose only default is absence, plus
/// [`SHIPPED_SPELLING`]. A field added to a struct is in the next `config init` with no second
/// edit, and `the_starter_config_carries_every_setting_the_build_reads` asserts the file's keys and
/// the catalogue agree exactly, so neither can silently miss one.
pub fn starter_config() -> Result<String> {
    let defaults = toml::Value::try_from(Config::default())
        .map_err(|e| Error::Config(format!("the default config does not serialise: {e}")))?;
    let mut out = String::with_capacity(8 * 1024);
    out.push_str("# Every setting this build reads, and nothing else.\n");
    out.push_str("# What one does, and what it accepts: `eclipse config docs`.\n");
    out.push_str("# A commented key is not in use; an empty value means the same.\n");
    out.push_str(&format!("config_version = {CONFIG_VERSION}\n"));
    for section in SECTION_ORDER {
        out.push_str(&format!("\n[{section}]\n"));
        let table = defaults.get(*section).and_then(toml::Value::as_table);
        let mut lines: Vec<(String, String)> = Vec::new();
        let mut nested: Vec<&str> = Vec::new();
        if let Some(table) = table {
            for (key, value) in table {
                match value {
                    toml::Value::Table(_) => nested.push(key.as_str()),
                    other => {
                        let shipped = SHIPPED_SPELLING
                            .iter()
                            .find(|(s, k, _)| s == section && k == key)
                            .map(|(_, _, spelling)| shipped_text(spelling));
                        lines.push((key.clone(), shipped.unwrap_or_else(|| other.to_string())));
                    }
                }
            }
        }
        // Keys whose default is absence: visible, and set to nothing. A key the struct *does*
        // write is never doubled — the schema and the hand-written list cannot disagree here.
        for (abs_section, key, _) in settings::ABSENT_BY_DEFAULT {
            if abs_section == section && !lines.iter().any(|(k, _)| k == key) {
                let shipped = SHIPPED_SPELLING
                    .iter()
                    .find(|(s, k, _)| s == section && k == key)
                    .map(|(_, _, spelling)| shipped_text(spelling));
                lines.push(((*key).to_string(), shipped.unwrap_or_default()));
            }
        }
        lines.sort();
        for (key, text) in lines {
            if text.is_empty() {
                out.push_str(&format!("# {key} =\n"));
            } else {
                out.push_str(&format!("{key} = {text}\n"));
            }
        }
        // A hook's own options are a table, not a setting, and are written as one so the block is
        // copy-pasteable. `[hooks.<name>]` for a hook that is not in `order` is a parse error, so
        // this follows the serialised default exactly rather than adding anything.
        nested.sort();
        for key in nested {
            let Some(sub) = table.and_then(|t| t.get(key)) else {
                continue;
            };
            let mut wrapped = toml::map::Map::new();
            wrapped.insert(key.to_string(), sub.clone());
            if let Ok(text) = toml::to_string(&toml::Value::Table(wrapped)) {
                out.push('\n');
                out.push_str(&text);
            }
        }
        // The hook that is on by default has no settings table in the default config (its options
        // are optional), and `order` has to name a hook this build has. Its block is written
        // empty, with each key it accepts named and commented: the one place a table's shape comes
        // from the hook's own declaration rather than from a hand-written section.
        if *section == "hooks" {
            let default_hooks = Config::default().hooks;
            for name in &default_hooks.order {
                if default_hooks.settings.contains_key(name) {
                    continue;
                }
                let Some(info) = crate::hooks::SHIPPED.iter().find(|h| h.name == name) else {
                    continue;
                };
                out.push_str(&format!("\n[hooks.{name}]\n"));
                let mut keys = info.settings.to_vec();
                keys.sort_unstable();
                for key in keys {
                    out.push_str(&format!("# {key} =\n"));
                }
            }
        }
    }
    Ok(out)
}

/// Every variable the shipped `.env` lists, in the order it lists them, with empty values.
///
/// Empty is the whole point: with [`Dotenv`] treating an empty assignment as absent — the same as
/// the line not being there — a file that names every variable and sets none of them behaves
/// exactly like a file with one line in it, and it is a directory of what can be set.
///
/// Only variables that are actually read from `.env` are here. `ECLIPSE_HOME`, `ECLIPSE_CONFIG` and
/// `ECLIPSE_PROFILE` are read to *find* the file, so a `.env` cannot set them ([`ENV_SHELL_ONLY`]),
/// and the rest are plumbing this tool puts in a child's environment ([`ENV_INTERNAL`]).
pub const ENV_TEMPLATE: &[&str] = &[
    "ECLIPSE_BASE_URL",
    "ECLIPSE_MODEL",
    "ECLIPSE_API_KEY",
    "ECLIPSE_REASONING_EFFORT",
    "ECLIPSE_ROUTE",
    "OPENAI_API_KEY",
    "ECLIPSE_WEB_AUTH_TOKEN",
    "ECLIPSE_WEB_USER",
    "ECLIPSE_WEB_PASSWORD_HASH",
];

/// One line per variable, for the manual: what it is for.
///
/// The `.env` is shipped as a list of names and nothing else — a name with no explanation is a
/// puzzle, and the explanation does not belong in a secrets file. This table is the other half,
/// and [`every_classified_variable_has_a_description`] keeps it level with the three lists above.
pub const ENV_ABOUT: &[(&str, &str)] = &[
    ("ECLIPSE_BASE_URL", "The provider's base URL, up to and including the version: it beats `[provider] base_url` for this process only"),
    ("ECLIPSE_MODEL", "The model name to ask for, beating `[provider] model`; the same as `--model`"),
    ("ECLIPSE_API_KEY", "The provider's key, resolved by `api_key = \"${ECLIPSE_API_KEY}\"`; never put the key itself in `config.toml`"),
    ("ECLIPSE_REASONING_EFFORT", "The reasoning level for this process: none, minimal, low, medium, high, xhigh, max"),
    ("ECLIPSE_ROUTE", "Pin one named route and never fall back from it, the same as `--route`"),
    ("OPENAI_API_KEY", "The variable the shipped `provider.api_key` line refers to; any name works, this one is the convention"),
    ("ECLIPSE_WEB_AUTH_TOKEN", "The dashboard's bearer token, generated by `config init`; the dashboard refuses to start without it"),
    ("ECLIPSE_WEB_USER", "The dashboard's sign-in name, when it asks for a name and a password instead of the token"),
    ("ECLIPSE_WEB_PASSWORD_HASH", "That password, as `eclipse web passwd` writes it: `pbkdf2-sha256$<iterations>$<salt>$<digest>`"),
    ("ECLIPSE_HOME", "The one directory everything lives in (`~/.eclipse` otherwise). Read from the shell, never from this file"),
    ("ECLIPSE_CONFIG", "The config file to read (`<home>/config.toml` otherwise). Read from the shell, never from this file"),
    ("ECLIPSE_PROFILE", "The profile to load, the same as `--profile`. Read from the shell, never from this file"),
    ("ECLIPSE_BIN", "The `eclipse` binary a spawned job should use; this tool sets it, and only a test overrides it"),
    ("ECLIPSE_ARGS", "The JSON arguments of the tool call a plugin or MCP server is being asked about; set by this tool"),
    ("ECLIPSE_ARGS_BYTES", "How big that JSON was, when it was too big to duplicate into `ECLIPSE_ARGS` (over 64 KiB); set by this tool"),
    ("ECLIPSE_TOOL", "The tool name a bridged call is for; set by this tool"),
    ("ECLIPSE_TOOL_SOCKET", "Where a script or plugin calls back into the running agent; set by this tool"),
    ("ECLIPSE_WORKSPACE", "The workspace root, given to a child process; set by this tool from `[tools] workspace_root`"),
    ("ECLIPSE_PLUGIN_DIR", "The plugin directory, given to a child process; set by this tool"),
    ("ECLIPSE_SCRIPTS_DIR", "The scripts directory, given to a child process; set by this tool"),
];

/// What one variable is for, or `""` — the same lookup shape as [`settings::about`].
pub fn env_about(name: &str) -> &'static str {
    ENV_ABOUT
        .iter()
        .find(|(n, _)| *n == name)
        .map(|(_, about)| *about)
        .unwrap_or("")
}

/// Variables read before a `.env` is opened, or from the process environment only. Setting one of
/// these *inside* `.env` would be inert, which is worse than absent: it looks like a setting.
pub const ENV_SHELL_ONLY: &[&str] = &["ECLIPSE_HOME", "ECLIPSE_CONFIG", "ECLIPSE_PROFILE"];

/// Variables this tool sets in a child's environment (a plugin, an MCP server, a spawned tool
/// call). Nobody sets these by hand, and a value in `.env` would be overwritten anyway.
pub const ENV_INTERNAL: &[&str] = &[
    "ECLIPSE_BIN",
    "ECLIPSE_ARGS",
    "ECLIPSE_ARGS_BYTES",
    "ECLIPSE_TOOL",
    "ECLIPSE_TOOL_SOCKET",
    "ECLIPSE_WORKSPACE",
    "ECLIPSE_PLUGIN_DIR",
    "ECLIPSE_SCRIPTS_DIR",
];

/// The shipped `.env`: every variable, nothing set, and the dashboard token already generated.
///
/// The token is the one value a first install cannot invent for you — the dashboard refuses to
/// start without it — so `config init` fills exactly that one line and leaves the rest empty.
pub fn starter_env(token: &str) -> String {
    let mut out = String::with_capacity(1024);
    out.push_str("# Secrets and per-host overrides. The shell beats this file. Mode 0600.\n");
    out.push_str("# Every variable this build reads; an empty value is not set. `eclipse config docs` explains each.\n");
    for name in ENV_TEMPLATE {
        if *name == "ECLIPSE_WEB_AUTH_TOKEN" {
            out.push_str(&format!("{name}={token}\n"));
        } else {
            out.push_str(&format!("{name}=\n"));
        }
    }
    out
}

/// The file a named profile starts from: an overlay, not a whole config. Only the keys a
/// profile usually changes are here, uncommented examples included — a profile that restated
/// every default would pin them, and then a change to the base config would stop reaching it.
pub const STARTER_PROFILE_CONFIG: &str = r#"# A profile overlay: keys here replace the base config's, and a key left out follows it.
# Examples are commented out on purpose — an empty value here *replaces* the base value.

[provider]
# base_url = "http://127.0.0.1:8080/v1"
# model = "qwen3-coder:30b"
# profile = "llamacpp"

[tools]
# shell = "ask"
"#;

/// What `config init` did, so the caller can report it without re-deriving paths.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InitReport {
    pub config: PathBuf,
    pub dotenv: PathBuf,
    /// False when a `.env` was already there: an existing file holds secrets and is never
    /// overwritten, not even by `--force`.
    pub dotenv_written: bool,
}

/// Write the starter config, and the `.env` **where the loader will read it**, with a freshly
/// generated dashboard token (the token is never returned or printed).
///
/// Refuses to overwrite the config unless `force`. The `.env` is *never* overwritten: it
/// holds the user's secrets, and consent to replace a config is not consent to lose those.
/// Both files are created `0600` on Unix.
///
/// The two files are not always neighbours: `[dotenv]` is read from the config *directory*
/// (`$ECLIPSE_HOME`, or `~/.eclipse`) whatever `--config` points at, so a `.env` written beside a
/// `--config /other/config.toml` would never be opened — `config init` would report a token that
/// the next start cannot see. Without a home directory there is no place the loader reads, and the
/// file goes beside the config as before.
pub fn write_starter_config(path: &Path, force: bool, env: EnvFn) -> Result<InitReport> {
    if path.exists() && !force {
        return Err(Error::Config(format!(
            "{} already exists (use --force to overwrite)",
            path.display()
        )));
    }
    let dir = path.parent().unwrap_or(Path::new("."));
    std::fs::create_dir_all(dir).map_err(|e| Error::io(dir, e))?;
    write_private(path, &starter_config()?)?;

    let secrets_dir = config_dir(env).unwrap_or_else(|| dir.to_path_buf());
    std::fs::create_dir_all(&secrets_dir).map_err(|e| Error::io(&secrets_dir, e))?;
    let dotenv = secrets_dir.join(".env");
    let mut dotenv_written = false;
    if !dotenv.exists() {
        let token = crate::token::generate()?;
        write_private(&dotenv, &starter_env(&token))?;
        dotenv_written = true;
    }
    // The template this file was generated from, kept so a later version can tell "the operator
    // chose this" from "we shipped this" (`config migrate`). Best effort: a config that was written
    // is a config that works, and a missing baseline costs nothing but a kept default.
    let _ = migrate::write_baseline(path);
    Ok(InitReport {
        config: path.to_path_buf(),
        dotenv,
        dotenv_written,
    })
}

/// The value `[section] key = ...` holds in this TOML text, unquoted, if the key is set.
/// Commented-out template lines do not count: they are documentation, not config.
pub fn toml_value(text: &str, section: &str, key: &str) -> Option<String> {
    let mut in_section = false;
    for line in text.lines() {
        let trimmed = line.trim();
        if let Some(name) = section_header(trimmed) {
            in_section = name == section;
            continue;
        }
        if !in_section || trimmed.starts_with('#') {
            continue;
        }
        if let Some((k, v)) = key_value(trimmed) {
            if k == key {
                return Some(v);
            }
        }
    }
    None
}

/// Set `[section] key = "value"` in this TOML text and return the whole text back.
///
/// Everything the wizard does not ask about survives untouched — comments, ordering, other
/// sections — because this rewrites one line rather than re-serialising the config. An
/// uncommented line is replaced in place; a commented template line (`# key = ...`) becomes
/// the real one; otherwise the key is added under the section header, and the section itself
/// is appended if it was missing.
pub fn toml_set_string(text: &str, section: &str, key: &str, value: &str) -> String {
    toml_set_value(text, section, key, &format!("\"{}\"", escape_toml(value)))
}

/// Set `[section] key = <value>` where `value` is already TOML — `9000`, `true`, `["a", "b"]`,
/// `"text"` with its quotes. The line-editing rules are [`toml_set_string`]'s.
pub fn toml_set_value(text: &str, section: &str, key: &str, value: &str) -> String {
    place_line(text, section, key, &format!("{key} = {value}"))
}

// ── `[[mcp]]` entries (`#352`) ────────────────────────────────────────────────────────────────
//
// An entry is an array-of-tables *block*, not a line, so `place_line` cannot reach it: it edits one
// key inside one section. These three writers therefore work on line ranges, and each touches only
// the block it names — a `mcp add` leaves every hand-written entry, and every comment around it,
// exactly as it was. Re-rendering the whole file from the parsed config would be far less code and
// would delete every comment a person wrote, which is the one thing `toml_set_value` exists to
// avoid.

/// One `[[mcp]]` block: its line range (`end` exclusive) and the name it declares, if the block
/// reads at all. A malformed block keeps its place and has no name, so no name-based verb can
/// silently match it.
struct McpSpan {
    name: Option<String>,
    start: usize,
    end: usize,
}

fn is_table_header(trimmed: &str) -> bool {
    trimmed.starts_with('[')
}

fn mcp_spans(lines: &[String]) -> Vec<McpSpan> {
    let mut spans: Vec<McpSpan> = Vec::new();
    let mut open: Option<usize> = None;
    let mut closed_by_header = true;
    for (i, line) in lines.iter().enumerate() {
        let trimmed = line.trim();
        if open.is_some() && is_table_header(trimmed) {
            if let Some(start) = open.take() {
                spans.push(McpSpan {
                    name: None,
                    start,
                    end: i,
                });
                closed_by_header = true;
            }
        }
        if trimmed == "[[mcp]]" {
            open = Some(i);
        }
    }
    if let Some(start) = open {
        spans.push(McpSpan {
            name: None,
            start,
            end: lines.len(),
        });
        closed_by_header = false;
    }
    // A block ends where the next one *starts being described*, not where its header sits: blank
    // lines and the comment directly above the next `[[mcp]]` are the next entry's. Trimming them
    // here is what keeps `disabled` out from under that comment, and what stops a removal from
    // taking the neighbour's note with it. The last block keeps its trailing lines — at the end of
    // the file there is nobody else they could belong to.
    let count = spans.len();
    for (i, span) in spans.iter_mut().enumerate() {
        let at_eof = i + 1 == count && !closed_by_header;
        while span.end > span.start + 1 {
            let tail = lines[span.end - 1].trim();
            let belongs_to_next = !at_eof && (tail.is_empty() || tail.starts_with('#'));
            if tail.is_empty() || belongs_to_next {
                span.end -= 1;
            } else {
                break;
            }
        }
    }
    for span in &mut spans {
        let body = lines[span.start + 1..span.end].join("\n");
        span.name = toml::from_str::<crate::mcp::Spec>(&body)
            .ok()
            .map(|spec| spec.name);
    }
    spans
}

/// Collapse runs of blank lines left behind by a removal. Comments are never touched: a file that
/// gains a double blank line is untidy, and a file that loses somebody's note is broken.
fn tidy_blanks(lines: Vec<String>) -> Vec<String> {
    let mut end = lines.len();
    while end > 0 && lines[end - 1].trim().is_empty() {
        end -= 1;
    }
    let mut out: Vec<String> = Vec::with_capacity(end);
    let mut blanks = 0;
    for line in &lines[..end] {
        if line.trim().is_empty() {
            blanks += 1;
            if blanks > 1 {
                continue;
            }
        } else {
            blanks = 0;
        }
        out.push(line.clone());
    }
    out
}

/// How one entry is written back out: only the keys it actually sets, in the order the docs list
/// them. Rendering the whole struct would emit `args = []`, `env = []`, `policies = {}` and every
/// default beside the two lines a person meant to write.
fn render_mcp_entry(entry: &crate::mcp::Spec) -> String {
    let quote = |s: &str| toml::Value::String(s.to_string()).to_string();
    let mut out = String::from("[[mcp]]\n");
    out.push_str(&format!("name = {}\n", quote(&entry.name)));
    if entry.transport == crate::mcp::Transport::Http {
        out.push_str("transport = \"http\"\n");
    }
    if !entry.command.is_empty() {
        out.push_str(&format!("command = {}\n", quote(&entry.command)));
    }
    if !entry.args.is_empty() {
        let args: Vec<String> = entry.args.iter().map(|a| quote(a)).collect();
        out.push_str(&format!("args = [{}]\n", args.join(", ")));
    }
    if let Some(url) = &entry.url {
        out.push_str(&format!("url = {}\n", quote(url)));
    }
    if let Some(var) = &entry.token_env {
        out.push_str(&format!("token_env = {}\n", quote(var)));
    }
    if entry.cwd != crate::plugins::Cwd::default() {
        let cwd = match entry.cwd {
            crate::plugins::Cwd::Workspace => "workspace",
            crate::plugins::Cwd::Plugin => "plugin",
        };
        out.push_str(&format!("cwd = \"{cwd}\"\n"));
    }
    if let Some(secs) = entry.timeout_secs {
        out.push_str(&format!("timeout_secs = {secs}\n"));
    }
    if entry.policy != Policy::Ask {
        let policy = match entry.policy {
            Policy::Deny => "deny",
            Policy::Ask => "ask",
            Policy::Allow => "allow",
        };
        out.push_str(&format!("policy = \"{policy}\"\n"));
    }
    if !entry.policies.is_empty() {
        let pairs: Vec<String> = entry
            .policies
            .iter()
            .map(|(tool, policy)| {
                let policy = match policy {
                    Policy::Deny => "deny",
                    Policy::Ask => "ask",
                    Policy::Allow => "allow",
                };
                format!("{tool} = \"{policy}\"")
            })
            .collect();
        out.push_str(&format!("policies = {{ {} }}\n", pairs.join(", ")));
    }
    if !entry.prefix.is_empty() {
        out.push_str(&format!("prefix = {}\n", quote(&entry.prefix)));
    }
    if !entry.env.is_empty() {
        let env: Vec<String> = entry.env.iter().map(|e| quote(e)).collect();
        out.push_str(&format!("env = [{}]\n", env.join(", ")));
    }
    if entry.override_builtin {
        out.push_str("override = true\n");
    }
    if entry.disabled {
        out.push_str("disabled = true\n");
    }
    out
}

/// Add `[[mcp]]` entry — to `config.toml`, which is the file this edits (`#352`).
pub fn mcp_add(text: &str, entry: &crate::mcp::Spec) -> std::result::Result<String, String> {
    entry
        .validate()
        .map_err(|why| format!("that entry is not usable, so nothing was saved: {why}"))?;
    let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
    let spans = mcp_spans(&lines);
    if let Some(existing) = spans
        .iter()
        .find(|s| s.name.as_deref() == Some(&entry.name))
    {
        return Err(format!(
            "`{}` is already declared at line {} — `eclipse mcp remove {}` first, or edit that entry",
            entry.name,
            existing.start + 1,
            entry.name
        ));
    }
    let rendered = render_mcp_entry(entry);
    match spans.last() {
        Some(last) => {
            let at = last.end;
            let mut fresh: Vec<String> = Vec::new();
            // One blank line between entries; a block that already ends with one does not get two.
            if at > 0 && !lines[at - 1].trim().is_empty() {
                fresh.push(String::new());
            }
            fresh.extend(rendered.lines().map(str::to_string));
            lines.splice(at..at, fresh);
        }
        None => {
            if lines.last().is_some_and(|l| !l.trim().is_empty()) {
                lines.push(String::new());
            }
            lines.extend(rendered.lines().map(str::to_string));
        }
    }
    let out = join_lines(tidy_blanks(lines));
    readback_mcp(&out, &entry.name, |spec| spec == entry)
}

/// Remove the `[[mcp]]` entry called `name`. Only that block goes.
pub fn mcp_remove(text: &str, name: &str) -> std::result::Result<String, String> {
    let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
    let spans = mcp_spans(&lines);
    let Some(span) = spans.iter().find(|s| s.name.as_deref() == Some(name)) else {
        let known: Vec<&str> = spans.iter().filter_map(|s| s.name.as_deref()).collect();
        return Err(if known.is_empty() {
            format!("no `[[mcp]]` entry for `{name}` in this file")
        } else {
            format!(
                "no `[[mcp]]` entry for `{name}`; this file declares {}",
                known.join(", ")
            )
        });
    };
    // A comment directly above the header describes this entry, so it goes with it — stopping at
    // the first blank line, which is where the previous entry's own trailing note lives.
    let mut start = span.start;
    while start > 0 && lines[start - 1].trim_start().starts_with('#') {
        start -= 1;
    }
    // Take the blank line *after* the block with it when there is one, so removing an entry does
    // not leave a hole where the next entry's separation used to be.
    let mut end = span.end;
    if end < lines.len() && lines[end].trim().is_empty() {
        end += 1;
    }
    lines.drain(start..end);
    readback_mcp_absent(&join_lines(tidy_blanks(lines)), name)
}

/// Switch an entry off (or back on) in place: `disabled = true` inside its own block.
pub fn mcp_set_disabled(
    text: &str,
    name: &str,
    disabled: bool,
) -> std::result::Result<String, String> {
    let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
    let spans = mcp_spans(&lines);
    let Some(span) = spans.iter().find(|s| s.name.as_deref() == Some(name)) else {
        return Err(format!("no `[[mcp]]` entry for `{name}` in this file"));
    };
    let line = if disabled {
        "disabled = true".to_string()
    } else {
        // Written rather than deleted: a person reading the file sees the server was switched off
        // deliberately, and the loader treats `false` exactly like absence.
        "disabled = false".to_string()
    };
    let body = span.start + 1..span.end;
    match lines[body.clone()].iter().position(|l| {
        l.trim_start()
            .strip_prefix("disabled")
            .is_some_and(|rest| rest.trim_start().starts_with('='))
    }) {
        Some(offset) => lines[span.start + 1 + offset] = line,
        None => lines.insert(span.end, line),
    }
    readback_mcp(&join_lines(lines), name, |spec| spec.disabled == disabled)
}

/// Change the `[[mcp]]` entry called `name` in place (`#517`).
///
/// `change` is handed **the entry the file declares**, not a shape from a form: a key the surface
/// does not show (`disabled`, `env`, `policies`, `override`, `cwd`) is not a key the person cleared.
/// The text that comes back differs only in the lines whose *value* changed, which is why both
/// renderings are compared: a hand-written entry keeps its own quoting, its own order and every
/// comment, and a field set back to its default loses its line rather than gaining a default one.
/// The rename is refused rather than done, because a rename is a remove and an add.
pub fn mcp_update(
    text: &str,
    name: &str,
    change: impl FnOnce(&mut crate::mcp::Spec),
) -> std::result::Result<String, String> {
    let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
    let spans = mcp_spans(&lines);
    let Some(span) = spans.iter().find(|s| s.name.as_deref() == Some(name)) else {
        let known: Vec<&str> = spans.iter().filter_map(|s| s.name.as_deref()).collect();
        return Err(if known.is_empty() {
            format!("no `[[mcp]]` entry for `{name}` in this file")
        } else {
            format!(
                "no `[[mcp]]` entry for `{name}`; this file declares {}",
                known.join(", ")
            )
        });
    };
    let body = lines[span.start + 1..span.end].join("\n");
    let before: crate::mcp::Spec = toml::from_str(&body).map_err(|e| {
        format!(
            "the entry for `{name}` at line {} does not read as it stands, so nothing was saved: {}",
            span.start + 1,
            crate::config::settings::one_line(&e.to_string())
        )
    })?;
    let mut after = before.clone();
    change(&mut after);
    if after.name != name {
        return Err(format!(
            "an edit does not rename: `{name}` stays `{name}` — remove the entry and add the new \
             name instead"
        ));
    }
    after
        .validate()
        .map_err(|why| format!("that entry is not usable, so nothing was saved: {why}"))?;
    let rendered = |spec: &crate::mcp::Spec| -> BTreeMap<String, String> {
        render_mcp_entry(spec)
            .lines()
            .skip(1) // the `[[mcp]]` header, which stays where it is
            .filter_map(|line| key_of(line).map(|key| (key, line.to_string())))
            .collect()
    };
    let (old, new) = (rendered(&before), rendered(&after));
    let (mut start, mut end) = (span.start + 1, span.end);
    // Walk the block one key (plus its continuation lines) at a time and keep everything the new
    // entry still says in the same place.
    let block: Vec<String> = lines[start..end].to_vec();
    let mut rebuilt: Vec<String> = Vec::new();
    let mut seen: Vec<String> = Vec::new();
    let mut i = 0;
    while i < block.len() {
        let line = &block[i];
        let trimmed = line.trim();
        if trimmed.is_empty() || trimmed.starts_with('#') {
            rebuilt.push(line.clone());
            i += 1;
            continue;
        }
        let first = i;
        let mut depth = bracket_depth(line);
        i += 1;
        while depth > 0 && i < block.len() {
            depth += bracket_depth(&block[i]);
            i += 1;
        }
        match key_of(&block[first]) {
            Some(key) => {
                seen.push(key.clone());
                match (old.get(&key), new.get(&key)) {
                    // Unchanged: the file's own line, byte for byte.
                    (Some(was), Some(is)) if was == is => {
                        rebuilt.extend(block[first..i].iter().cloned())
                    }
                    (_, Some(is)) => rebuilt.push(is.clone()),
                    // Cleared to its default: the line goes, and nothing else moves.
                    (_, None) => {}
                }
            }
            // A line that names no key is somebody's text; it is never dropped.
            None => rebuilt.extend(block[first..i].iter().cloned()),
        }
    }
    for (key, line) in &new {
        if !seen.contains(key) {
            rebuilt.push(line.clone());
        }
    }
    start = start.min(lines.len());
    end = end.min(lines.len());
    lines.splice(start..end, rebuilt);
    let out = join_lines(lines);
    readback_mcp(&out, name, |spec| spec == &after)
}

/// The `key` of a `key = value` line, or `None` for a comment, a blank line or a continuation.
fn key_of(line: &str) -> Option<String> {
    let trimmed = line.trim();
    if trimmed.starts_with('#') {
        return None;
    }
    let (key, _) = trimmed.split_once('=')?;
    let key = key.trim();
    let plain = !key.is_empty()
        && !key.contains(char::is_whitespace)
        && key
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-');
    plain.then(|| key.to_string())
}

/// How many brackets a line opens: a value that ends above zero continues on the next line.
/// Quotes are honoured, so an `args = ["a=b"]` is still one line.
fn bracket_depth(line: &str) -> i32 {
    let mut depth = 0;
    let mut quote: Option<char> = None;
    let mut escaped = false;
    for c in line.chars() {
        if let Some(q) = quote {
            if escaped {
                escaped = false;
            } else if c == '\\' {
                escaped = true;
            } else if c == q {
                quote = None;
            }
            continue;
        }
        match c {
            '"' | '\'' => quote = Some(c),
            '[' | '{' => depth += 1,
            ']' | '}' => depth -= 1,
            '#' => break, // a trailing comment is prose, not value
            _ => {}
        }
    }
    depth
}

/// The guard every writer here shares, in `set_in_text`'s voice: the text must load, and the entry
/// it names must read back as what was asked. Anything else means nothing is written.
fn readback_mcp(
    text: &str,
    name: &str,
    ok: impl Fn(&crate::mcp::Spec) -> bool,
) -> std::result::Result<String, String> {
    let cfg = parse_text(text).map_err(|e| {
        format!(
            "that would not load, so nothing was saved: {}",
            settings::one_line(&e.to_string())
        )
    })?;
    match cfg.mcp.iter().find(|s| s.name == name) {
        Some(spec) if ok(spec) => Ok(text.to_string()),
        Some(_) => {
            Err("the file would not read that entry back as written; nothing was saved".into())
        }
        None => Err(format!(
            "the edit lost `{name}` on the way back in; nothing was saved"
        )),
    }
}

fn readback_mcp_absent(text: &str, name: &str) -> std::result::Result<String, String> {
    let cfg = parse_text(text).map_err(|e| {
        format!(
            "that would not load, so nothing was saved: {}",
            settings::one_line(&e.to_string())
        )
    })?;
    if cfg.mcp.iter().any(|s| s.name == name) {
        return Err(format!("`{name}` survived the removal; nothing was saved"));
    }
    Ok(text.to_string())
}

/// Replace the line for `[section] key` with `replacement`, or insert one after the section header.
///
/// The one traversal both a value and a comment go through, so "where a key's line goes" is decided
/// once: a commented `# key = …` in that section is the line to replace, and a section with neither
/// gets the line directly under its header.
fn place_line(text: &str, section: &str, key: &str, replacement: &str) -> String {
    let quoted = replacement.to_string();
    let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
    let mut in_section = false;
    let mut header_at: Option<usize> = None;
    let mut commented_at: Option<usize> = None;
    for (i, line) in lines.iter().enumerate() {
        let trimmed = line.trim();
        if let Some(name) = section_header(trimmed) {
            in_section = name == section;
            if in_section && header_at.is_none() {
                header_at = Some(i);
            }
            continue;
        }
        if !in_section {
            continue;
        }
        if let Some((k, _)) = key_value(trimmed) {
            if k == key {
                lines[i] = quoted;
                return join_lines(lines);
            }
        } else if let Some(rest) = trimmed.strip_prefix('#') {
            // `# key = "default"` is how the starter documents an optional key.
            if let Some((k, _)) = key_value(rest.trim()) {
                if k == key && commented_at.is_none() {
                    commented_at = Some(i);
                }
            }
        }
    }
    match (header_at, commented_at) {
        (_, Some(i)) => lines[i] = quoted,
        (Some(i), None) => lines.insert(i + 1, quoted),
        (None, None) => {
            lines.push(String::new());
            lines.push(format!("[{section}]"));
            lines.push(quoted);
        }
    }
    join_lines(lines)
}

/// Insert `# key =` under `[section]`, which is how a shipped file says "this key exists and is not
/// in use" for a key whose off state has no spelling (a number, a colour, an explicit boolean).
///
/// The companion to [`toml_set_value`], and deliberately not a call to it with a `#` in the key:
/// this line is *inert*, and a migration that wrote it as a value would be imposing something.
pub fn comment_in_text(text: &str, section: &str, key: &str) -> String {
    place_line(text, section, key, &format!("# {key} ="))
}

/// Write `config_version = N` into this TOML text, at the top, where the generated file puts it.
///
/// Top-level because it describes the file and must survive a section being renamed, and replacing
/// the existing line rather than appending keeps it at the top of a file that already has one.
pub fn stamp_version(text: &str, version: u32) -> std::result::Result<String, String> {
    let line = format!("config_version = {version}");
    let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
    if let Some(at) = lines.iter().position(|l| {
        l.trim_start()
            .strip_prefix("config_version")
            .is_some_and(|rest| rest.trim_start().starts_with('='))
    }) {
        lines[at] = line;
    } else {
        // Under the header comments and above the first table: TOML wants top-level scalars before
        // the first `[section]`, and the header comment is the file's own front page. The spacing
        // is normalised to what `config init` writes — no blank line above the stamp, one below —
        // so a migrated file and a fresh one cannot be told apart by looking at them.
        let first_table = lines
            .iter()
            .position(|l| section_header(l.trim()).is_some())
            .unwrap_or(lines.len());
        let mut insert_at = 0;
        while insert_at < first_table
            && (lines[insert_at].trim_start().starts_with('#')
                || lines[insert_at].trim().is_empty())
        {
            insert_at += 1;
        }
        lines.insert(insert_at, String::new());
        lines.insert(insert_at, line);
        while insert_at > 0 && lines[insert_at - 1].trim().is_empty() {
            lines.remove(insert_at - 1);
            insert_at -= 1;
        }
    }
    let out = join_lines(lines);
    // Proved, like every other write here: a file that does not parse afterwards is not written.
    parse_text(&out).map_err(|e| format!("stamping the version would not load: {e}"))?;
    Ok(out)
}

/// Comment `[section] key = …` out of this TOML text, so the file falls back to the default.
///
/// Commented, not deleted: the neighbours of that line explain the key, and a person who unsets
/// `web.port` should still be able to see what it is called. A key that is not there at all is
/// left alone — unsetting what is already unset is not an error.
pub fn toml_comment_out(text: &str, section: &str, key: &str) -> String {
    let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
    let mut in_section = false;
    for line in lines.iter_mut() {
        let trimmed = line.trim();
        if let Some(name) = section_header(trimmed) {
            in_section = name == section;
            continue;
        }
        if !in_section || trimmed.starts_with('#') {
            continue;
        }
        if let Some((k, _)) = key_value(trimmed) {
            if k == key {
                let indent: String = line.chars().take_while(|c| c.is_whitespace()).collect();
                *line = format!("{indent}# {trimmed}");
                return join_lines(lines);
            }
        }
    }
    join_lines(lines)
}

/// `[section]` → `section`, and nothing else (a `[[table]]` array header is not a section we
/// edit, and `[a.b]` is its own name, not `a`).
pub(crate) fn section_header(trimmed: &str) -> Option<&str> {
    if trimmed.starts_with("[[") {
        return None;
    }
    let rest = trimmed.strip_prefix('[')?;
    let name = rest.strip_suffix(']')?;
    if name.contains(['[', ']']) || name.trim() != name || name.is_empty() {
        return None;
    }
    Some(name)
}

/// `key = value` → (`key`, unquoted value). Anything without an `=` or with an empty key is
/// not a key/value line.
pub(crate) fn key_value(trimmed: &str) -> Option<(&str, String)> {
    let (k, v) = trimmed.split_once('=')?;
    let k = k.trim();
    if k.is_empty() || k.contains([' ', '"', '\\']) {
        return None;
    }
    let v = v.trim();
    let unquoted = match v.strip_prefix('"').and_then(|r| r.strip_suffix('"')) {
        Some(inner) => inner.replace("\\\"", "\"").replace("\\\\", "\\"),
        None => v.to_string(),
    };
    Some((k, unquoted))
}

fn escape_toml(value: &str) -> String {
    value.replace('\\', "\\\\").replace('"', "\\\"")
}

fn join_lines(lines: Vec<String>) -> String {
    let mut out = lines.join("\n");
    if !out.ends_with('\n') {
        out.push('\n');
    }
    out
}

/// Write config text back with the same permissions as the starter (`0600`) — the file can
/// carry `api_key`, and a config people paste into bug reports should still be readable only
/// by them.
pub fn save_config_text(path: &Path, text: &str) -> Result<()> {
    write_private(path, text)
}

/// Parse config text exactly as the loader would. A writer uses this to prove what it is
/// about to save is loadable *before* it replaces the user's file.
pub fn parse_text(text: &str) -> Result<Config> {
    let cfg: Config =
        toml::from_str(text).map_err(|e| Error::Config(format!("invalid config: {e}")))?;
    crate::hooks::validate(&cfg.hooks)
        .map_err(|e| Error::Config(format!("invalid config: {e}")))?;
    Ok(cfg)
}

/// Set `KEY=value` in a `.env`, creating it `0600` if it does not exist. An existing line for
/// that key is replaced; every other line, comment included, is kept. Values are written raw:
/// a `.env` is not TOML and the loader takes the rest of the line as the value.
pub fn save_dotenv_var(path: &Path, key: &str, value: &str) -> Result<()> {
    let existing = std::fs::read_to_string(path).unwrap_or_default();
    let line = format!("{key}={value}");
    let mut out = String::new();
    let mut replaced = false;
    for l in existing.lines() {
        let is_key = l
            .trim_start()
            .strip_prefix(key)
            .map(|rest| rest.starts_with('='))
            .unwrap_or(false);
        if is_key {
            out.push_str(&line);
            out.push('\n');
            replaced = true;
        } else {
            out.push_str(l);
            out.push('\n');
        }
    }
    if !replaced {
        if !out.is_empty() && !out.ends_with('\n') {
            out.push('\n');
        }
        out.push_str(&line);
        out.push('\n');
    }
    write_private(path, &out)
}

/// The value of `KEY` in a `.env` file, if it has one.
pub fn dotenv_var(path: &Path, key: &str) -> Option<String> {
    std::fs::read_to_string(path).ok()?.lines().find_map(|l| {
        let rest = l.trim_start().strip_prefix(key)?;
        let value = rest.strip_prefix('=')?;
        Some(value.trim().to_string())
    })
}

/// Write a file that only its owner may read: created `0600` on Unix, and replaced in place
/// rather than appended to.
pub(crate) fn write_private(path: &Path, text: &str) -> Result<()> {
    // `#408`: this truncated the file before writing it, so a crash, a full disk or a `kill -9`
    // between the two left a zero-length `config.toml` — which loads as *defaults*, so every
    // `provider.*` value silently vanished. Write beside and rename instead; `0600` is set on the
    // temporary file, so there is no window where the secrets are readable by anyone else.
    crate::atomic::write_file_atomically(path, text).map_err(|e| Error::io(path, e))
}

#[test]
fn writing_the_empty_value_proves_itself_by_reading_back_as_unset() {
    // The rule from #295: an empty value *is* absence. So `key = ""` has to be writable, and it has
    // to verify — which it could not while `set_in_text` demanded the value come back as `""`. The
    // 0.9.0-shaped file (every key commented) exposed it: a migration adding 78 keys hit the first
    // empty-string key and refused the whole file.
    let text = starter_config().unwrap();
    let without = settings::unset_in_text(&text, "agent.output_schema").expect("known key");
    assert_eq!(
        Config::from_toml_str(&without).unwrap().agent.output_schema,
        None
    );
    let back = settings::set_in_text(
        &without,
        "agent.output_schema",
        &toml::Value::String(String::new()),
    )
    .expect("an empty value can be written");
    assert!(back.contains("output_schema = \"\""), "{back}");
    assert_eq!(
        Config::from_toml_str(&back).unwrap().agent.output_schema,
        None,
        "and it reads as unset, which is what it means"
    );
    assert_eq!(
        toml_value(&back, "agent", "output_schema"),
        Some(String::new()),
        "the line is there; what it holds is nothing"
    );
}

#[cfg(test)]
mod tests {
    // ---------------------------------------------------------------------------------------
    // `#171`: two route keys say how many flares a route holds, and `[flares]` says what a run
    // costs. The arithmetic that combines them lives in `flares::slots`, but the reading of the
    // keys is here.
    // ---------------------------------------------------------------------------------------

    #[test]
    fn a_route_can_say_how_many_flares_it_holds() {
        let cfg = Config::from_toml_str(
            r#"
[provider]
fallback = ["local", "cloud"]

[[provider.route]]
name = "local"
base_url = "http://127.0.0.1:8080/v1"
model = "qwen"
profile = "llamacpp"
group = "gpu0"
max_parallel = 2

[[provider.route]]
name = "cloud"
base_url = "https://api.example.com/v1"
model = "big"
"#,
        )
        .unwrap();
        let routes = cfg.declared_routes();
        let local = routes.iter().find(|r| r.name == "local").unwrap();
        assert_eq!(local.parallel(), 2, "the route said two slots");
        assert_eq!(local.group.as_deref(), Some("gpu0"));
        let cloud = routes.iter().find(|r| r.name == "cloud").unwrap();
        // An API states no shape, so the profile decides: openai is four, a local server one.
        assert_eq!(cloud.parallel(), 4, "an openai route defaults to four");
        assert!(cloud.group.is_none());
        assert_eq!(
            local.default_parallel(),
            1,
            "llamacpp serves one model at a time"
        );

        // `0` is read as `1`: a route with no slot is a route flares cannot use, and starving
        // them silently is worse than a slow run.
        let zero = Config::from_toml_str(
            r#"
[[provider.route]]
name = "local"
base_url = "http://127.0.0.1:8080/v1"
model = "qwen"
max_parallel = 0
"#,
        )
        .unwrap();
        assert_eq!(zero.declared_routes()[0].parallel(), 1);

        // A wrong type is the route's error, not a mysterious one about `provider.route`.
        let bad = Config::from_toml_str(
            r#"
[[provider.route]]
name = "local"
base_url = "http://127.0.0.1:8080/v1"
model = "qwen"
max_parallel = "two"
"#,
        )
        .unwrap_err()
        .to_string();
        assert!(bad.contains("route `local`"), "{bad}");
        assert!(bad.contains("max_parallel"), "{bad}");
    }

    #[test]
    fn flares_default_to_three_on_one_local_slot() {
        let cfg = Config::from_toml_str("").unwrap();
        assert_eq!(cfg.flares.count, 3, "the local default");
        assert_eq!(cfg.flares.concurrency(), 4);
        assert_eq!(cfg.flares.per_flare(), 6);
        assert_eq!(cfg.flares.budget(), 24);

        let cfg = Config::from_toml_str(
            r#"
[flares]
count = 5
max_concurrent = 0
max_iterations = 0
total_iterations = 2
"#,
        )
        .unwrap();
        assert_eq!(cfg.flares.count, 5);
        // Zero is never a usable cap: the same rule as `[tools] concurrency`, and a run allowed
        // fewer turns than one flare would fail before it began.
        assert_eq!(cfg.flares.concurrency(), 1);
        assert_eq!(cfg.flares.per_flare(), 1);
        assert_eq!(cfg.flares.budget(), 2);
    }

    use super::*;
    use std::collections::HashMap;

    /// The shipped config, generated — the fixture every test about the file itself starts from.
    fn starter() -> String {
        starter_config().expect("the starter config generates")
    }

    fn env_of(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> {
        let m: HashMap<String, String> = pairs
            .iter()
            .map(|(k, v)| (k.to_string(), v.to_string()))
            .collect();
        move |k| m.get(k).cloned()
    }

    /// Load `text` as a config file exactly as the binary would, and say what happened.
    fn load_hooks(text: &str) -> std::result::Result<Config, String> {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("config.toml");
        std::fs::write(&path, text).unwrap();
        let env = env_of(&[("HOME", tmp.path().to_str().unwrap())]);
        Config::load_with_profile(Some(&path), None, &env).map_err(|e| e.to_string())
    }

    #[test]
    fn the_memory_and_the_filter_are_on_by_default_when_there_is_no_hooks_section() {
        let want = crate::hooks::DEFAULT_ORDER;
        let c = load_hooks("[agent]\nmax_iterations = 3\n").unwrap();
        assert_eq!(c.hooks.order, want);
        assert_eq!(Config::default().hooks.order, want);
        let c = load_hooks("").unwrap();
        assert_eq!(c.hooks.order, want);
        assert!(
            !want.contains(&"recall-sessions"),
            "a new session is a new session: recall is opt-in, and `session_search` is how the \
             agent reaches the archive"
        );
    }

    #[test]
    fn an_empty_order_turns_every_hook_off() {
        let c = load_hooks("[hooks]\norder = []\n").unwrap();
        assert!(c.hooks.order.is_empty());
    }

    #[test]
    fn a_settings_table_alone_keeps_the_default_order() {
        let c = load_hooks("[hooks.redact-secrets]\nallow = [\"fixture-key\"]\n").unwrap();
        assert_eq!(c.hooks.order, crate::hooks::DEFAULT_ORDER);
    }

    #[test]
    fn a_hook_name_this_build_does_not_have_is_refused_and_the_real_ones_are_listed() {
        let err =
            load_hooks("[hooks]\norder = [\"redact-secrets\", \"redact-secret\"]\n").unwrap_err();
        assert!(err.contains("`redact-secret`"), "{err}");
        assert!(
            err.contains("Hooks that exist: recall-sessions, redact-secrets"),
            "{err}"
        );
        assert!(err.contains("config.toml"), "the file is named: {err}");
    }

    #[test]
    fn a_settings_table_for_a_hook_that_is_not_in_order_is_refused() {
        let err =
            load_hooks("[hooks]\norder = []\n[hooks.redact-secrets]\nallow = []\n").unwrap_err();
        assert!(err.contains("[hooks.redact-secrets]"), "{err}");
        assert!(err.contains("never run"), "{err}");
        assert!(err.contains("Add \"redact-secrets\" to order"), "{err}");
    }

    #[test]
    fn a_settings_table_for_a_hook_that_does_not_exist_is_refused() {
        let err = load_hooks("[hooks.nope]\nx = 1\n").unwrap_err();
        assert!(err.contains("[hooks.nope]"), "{err}");
        assert!(err.contains("Hooks that exist"), "{err}");
    }

    #[test]
    fn an_unknown_key_in_a_hooks_table_is_refused_and_the_known_ones_are_listed() {
        let err = load_hooks("[hooks.redact-secrets]\nalow = [\"x\"]\n").unwrap_err();
        assert!(err.contains("unknown key `alow`"), "{err}");
        assert!(err.contains("accepts: allow"), "{err}");
    }

    #[test]
    fn a_stray_key_directly_under_hooks_is_refused() {
        let err = load_hooks("[hooks]\nenabled = true\n").unwrap_err();
        assert!(err.contains("`enabled`"), "{err}");
        assert!(err.contains("`order`"), "{err}");
    }

    #[test]
    fn a_hook_listed_twice_and_a_malformed_allow_list_are_refused() {
        let err =
            load_hooks("[hooks]\norder = [\"redact-secrets\", \"redact-secrets\"]\n").unwrap_err();
        assert!(err.contains("twice"), "{err}");
        let err = load_hooks("[hooks.redact-secrets]\nallow = \"x\"\n").unwrap_err();
        assert!(err.contains("must be a list of strings"), "{err}");
        let err = load_hooks("[hooks.redact-secrets]\nallow = [\"\"]\n").unwrap_err();
        assert!(err.contains("empty string"), "{err}");
        let err = load_hooks("[hooks.redact-secrets]\nallow = [1]\n").unwrap_err();
        assert!(err.contains("only strings"), "{err}");
    }

    #[test]
    fn a_profile_overlay_that_breaks_the_hooks_section_is_blamed_on_the_overlay() {
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path().join("home");
        let dir = home.join(".eclipse");
        std::fs::create_dir_all(dir.join("profiles/work")).unwrap();
        std::fs::write(
            dir.join("config.toml"),
            "[hooks]\norder = [\"redact-secrets\"]\n",
        )
        .unwrap();
        std::fs::write(
            dir.join("profiles/work/config.toml"),
            "[hooks]\norder = [\"typo\"]\n",
        )
        .unwrap();
        let env = env_of(&[("HOME", home.to_str().unwrap())]);
        let err = Config::load_with_profile(None, Some("work"), &env)
            .unwrap_err()
            .to_string();
        assert!(err.contains("profiles/work/config.toml"), "{err}");
        assert!(err.contains("`typo`"), "{err}");
    }

    /// An empty value is "not in use", and it has to be true in one place: a shipped `.env` names
    /// every variable and sets none of them, so `NAME=` has to read as absent — in the loader that
    /// resolves `${VAR}`, in the token the dashboard needs, and not one call site at a time.
    #[test]
    fn an_empty_value_is_not_a_value_in_the_dotenv() {
        let dir = tempfile::tempdir().unwrap();
        let home = dir.path();
        std::fs::create_dir_all(home.join(".eclipse")).unwrap();
        let path = home.join(".eclipse/.env");
        std::fs::write(
            &path,
            "ECLIPSE_API_KEY=\nECLIPSE_MODEL=m\nECLIPSE_WEB_AUTH_TOKEN=\n",
        )
        .unwrap();
        let home_s = home.to_str().unwrap().to_string();
        let env = env_of(&[("HOME", &home_s)]);
        let loaded = Dotenv::load(&env, None).unwrap();
        assert_eq!(
            loaded.values.get("ECLIPSE_MODEL").map(String::as_str),
            Some("m")
        );
        assert!(
            !loaded.values.contains_key("ECLIPSE_API_KEY"),
            "an empty assignment is absent: {:?}",
            loaded.values.keys().collect::<Vec<_>>()
        );
        assert!(!loaded.values.contains_key("ECLIPSE_WEB_AUTH_TOKEN"));
    }

    /// A later line still wins even when it empties a key: "this host does not use it" is a thing
    /// a profile's `.env` has to be able to say about the shared one.
    #[test]
    fn a_later_empty_assignment_unsets_an_earlier_one() {
        let dir = tempfile::tempdir().unwrap();
        let home = dir.path();
        std::fs::create_dir_all(home.join(".eclipse").join("profiles/work")).unwrap();
        std::fs::write(home.join(".eclipse/.env"), "ECLIPSE_MODEL=big\n").unwrap();
        std::fs::write(home.join(".eclipse/profiles/work/.env"), "ECLIPSE_MODEL=\n").unwrap();
        let home_s = home.to_str().unwrap().to_string();
        let env = env_of(&[("HOME", &home_s)]);
        let loaded = Dotenv::load(&env, Some("work")).unwrap();
        assert_eq!(loaded.files.len(), 2);
        assert_eq!(loaded.values.get("ECLIPSE_MODEL"), None);
    }

    /// The shipped `.env` is a directory of what can be set: every variable the build reads from
    /// it, nothing set, and the token the dashboard cannot invent for you.
    #[test]
    fn the_starter_env_lists_every_variable_and_sets_none_of_them() {
        let text = starter_env("tok");
        for name in ENV_TEMPLATE {
            assert!(
                text.contains(&format!("\n{name}=")),
                "`{name}` is in the shipped .env"
            );
        }
        for line in text.lines().filter(|l| !l.starts_with('#')) {
            let (name, value) = line.split_once('=').expect("KEY=VALUE");
            if name == "ECLIPSE_WEB_AUTH_TOKEN" {
                assert_eq!(value, "tok", "the one value a first install cannot invent");
            } else {
                assert!(value.is_empty(), "`{name}` ships unset, found `{value}`");
            }
        }
    }

    /// The classification is exhaustive against the source, not against a list beside it: a new
    /// `ECLIPSE_*` variable has to be decided on — shipped, shell-only, or internal — before it
    /// compiles past this test. Without it the shipped `.env` silently stops being complete.
    #[test]
    fn every_environment_variable_the_build_reads_is_classified() {
        let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("..");
        let mut seen = Vec::new();
        let mut dirs = vec![
            root.join("eclipse-core/src"),
            root.join("eclipse-cli/src"),
            root.join("eclipse-web/src"),
        ];
        while let Some(dir) = dirs.pop() {
            let Ok(entries) = std::fs::read_dir(&dir) else {
                continue;
            };
            for entry in entries.flatten() {
                let path = entry.path();
                if path.is_dir() {
                    dirs.push(path);
                    continue;
                }
                if path.extension().and_then(|e| e.to_str()) != Some("rs") {
                    continue;
                }
                let text = std::fs::read_to_string(&path).unwrap_or_default();
                for name in env_names(&text) {
                    if !seen.contains(&name) {
                        seen.push(name);
                    }
                }
            }
        }
        assert!(seen.len() > 10, "the scan found the variables: {seen:?}");
        for name in &seen {
            let known = ENV_TEMPLATE.contains(&name.as_str())
                || ENV_SHELL_ONLY.contains(&name.as_str())
                || ENV_INTERNAL.contains(&name.as_str());
            assert!(
                known,
                "`{name}` is read by the build and is in none of ENV_TEMPLATE, ENV_SHELL_ONLY, ENV_INTERNAL"
            );
        }
        // And the other direction: a name in the template has to be one something acts on — read
        // by the build, or interpolated by the config the build ships. A variable nobody consumes
        // is a line in a secrets file that does nothing, which reads as a setting that is broken.
        let shipped = starter();
        for name in ENV_TEMPLATE {
            let read = seen.iter().any(|s| s == name);
            let interpolated = shipped.contains(&format!("${{{name}"));
            assert!(
                read || interpolated,
                "`{name}` is in the shipped .env and nothing reads or interpolates it"
            );
        }
    }

    /// The manual's environment table and the `.env` template describe the same set: a name in
    /// one and not the other is either a variable nobody can look up or a paragraph about a
    /// variable that does not exist.
    #[test]
    fn every_classified_variable_has_a_description() {
        let classified: Vec<&str> = ENV_TEMPLATE
            .iter()
            .chain(ENV_SHELL_ONLY)
            .chain(ENV_INTERNAL)
            .copied()
            .collect();
        for name in &classified {
            assert!(
                !env_about(name).is_empty(),
                "`{name}` is classified and has no line in ENV_ABOUT"
            );
        }
        for (name, about) in ENV_ABOUT {
            assert!(
                classified.contains(name),
                "ENV_ABOUT explains `{name}`, which the build does not read"
            );
            assert!(
                about.len() > 30 && !about.ends_with('.'),
                "one sentence, no full stop: {about}"
            );
        }
    }

    /// Every `"ECLIPSE_…"` literal in a source file, quoted form only (a doc comment naming one is
    /// prose, not a read).
    fn env_names(text: &str) -> Vec<String> {
        let mut out = Vec::new();
        let mut rest = text;
        while let Some(at) = rest.find("\"ECLIPSE_") {
            let after = &rest[at + 1..];
            let Some(end) = after.find('"') else {
                break;
            };
            let name = &after[..end];
            // A name, not a prefix: `"ECLIPSE_"` used to build one at run time ends in an
            // underscore, and this scanner's own search literal is in the tree it scans.
            let complete = name
                .chars()
                .last()
                .is_some_and(|c| c.is_ascii_uppercase() || c.is_ascii_digit());
            if complete
                && name
                    .chars()
                    .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')
            {
                out.push(name.to_string());
            }
            rest = &after[end + 1..];
        }
        out
    }

    #[test]
    fn an_empty_optional_string_loads_as_unset() {
        // The shipped spelling of a secret is `${VAR:-}`, which resolves to "" when the variable
        // is absent — and "" has to mean "no secret", not "an empty one".
        let c = Config::from_toml_str(
            "[provider]\napi_key = \"\"\napi_key_env = \"\"\nmodel = \"m\"\n[web]\nauth_token = \"\"\n",
        )
        .unwrap();
        assert_eq!(c.provider.api_key, None);
        assert_eq!(c.provider.api_key_env, None);
        assert_eq!(c.web.auth_token, None);
        // A path is not an option and "" is already its absent state.
        assert_eq!(c.provider.model, "m");
        // The shipped spelling is `${VAR:-}`, and that resolves through the *loader* — an absent
        // variable is no key, not the string with the braces left in it.
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.toml");
        std::fs::write(&path, "[provider]\napi_key = \"${NOT_SET_ANYWHERE:-}\"\n").unwrap();
        let from_var = Config::load_with(Some(&path), &env_of(&[])).unwrap();
        assert_eq!(
            from_var.provider.api_key, None,
            "an absent variable is no key"
        );
    }

    /// The file ships every setting and no prose, and it is the schema's own file: the assertion
    /// is against the catalogue, not against a list written here, so a field added to a struct
    /// cannot reach this build without reaching the next install's config.
    #[test]
    fn the_starter_config_carries_every_setting_the_build_reads() {
        let text = starter();
        let c = parse_text(&text).unwrap();
        let settings = Config::default().settings();
        assert!(
            settings.len() > 80,
            "the catalogue is the yardstick: {settings:?}"
        );
        for setting in &settings {
            let key = setting.key.clone();
            let present = text.lines().any(|l| {
                l.trim_start_matches("# ")
                    .trim_start()
                    .starts_with(&format!("{key} ="))
            });
            assert!(
                present,
                "[{}] `{key}` is missing from the shipped file:\n{text}",
                setting.section
            );
        }
        // No prose: the header is three lines, and every other comment is a `key =` that is not
        // in use. A paragraph in this file is the thing the manual exists to replace.
        for line in text.lines().filter(|l| l.starts_with('#')) {
            assert!(
                line.starts_with("# ") && line[2..].contains(" =") || line.len() < 120,
                "a comment in the settings file should be a key, not a sentence: {line}"
            );
        }
        let prose = text
            .lines()
            .filter(|l| l.starts_with('#') && !l[1..].trim_start().contains(" ="))
            .count();
        assert!(prose <= 3, "only the three header lines: {prose}");
        // It loads, and the hooks block it writes is the order this build actually defaults to.
        assert_eq!(c.hooks.order, crate::hooks::DEFAULT_ORDER);
        assert_eq!(c.hooks.order, Config::default().hooks.order);
        assert!(c.hooks.settings.contains_key("redact-secrets"));
        crate::hooks::validate(&c.hooks).expect("the starter config's hooks validate");
        assert!(
            !c.hooks.settings.contains_key("recall-sessions"),
            "a settings table for a hook that is not in `order` cannot run"
        );
        // And every key in it is one the build reads: a config that answers "nothing reads this"
        // about its own file is a config that teaches people to ignore the checker.
        let value: toml::Value = toml::from_str(&text).unwrap();
        let unknown = c.unknown_keys(&value);
        assert!(
            unknown.is_empty(),
            "unknown keys in the shipped file: {unknown:?}"
        );
        assert_eq!(
            c.config_version, CONFIG_VERSION,
            "the file stamps its shape"
        );
    }

    #[test]
    fn the_hooks_section_survives_a_round_trip_through_the_redacted_printout() {
        let c = load_hooks(
            "[hooks]\norder = [\"redact-secrets\"]\n[hooks.redact-secrets]\nallow = [\"fx\"]\n",
        )
        .unwrap();
        let shown = c.to_toml_redacted().unwrap();
        let again = Config::from_toml_str(&shown).unwrap();
        assert_eq!(again.hooks, c.hooks);
    }

    #[test]
    fn defaults_have_no_endpoint_or_key() {
        let c = Config::default();
        assert!(c.provider.base_url.is_empty());
        assert!(c.provider.api_key.is_none());
        assert!(c.require_provider().is_err());
        // The file tools confine every path themselves, so the default is not to ask; the shell
        // asks, but only about commands that cannot be undone.
        assert_eq!(c.tools.write_file, Policy::Allow);
        assert_eq!(c.tools.shell, Policy::Ask);
        assert_eq!(c.tools.shell_ask, ShellAsk::Dangerous);
    }

    #[test]
    fn cli_section_defaults_and_parses() {
        // Absent: the documented defaults, and `None` meaning "decide from the stream".
        let d = Config::from_toml_str("").unwrap().cli;
        assert_eq!(d.color, None);
        assert_eq!(d.markdown, None);
        assert_eq!(d.approval, Approval::Ask);
        assert_eq!(d.history_size, 1000);

        let c = Config::from_toml_str(
            "[cli]\ncolor = false\nmarkdown = true\napproval = \"auto\"\nhistory_size = 50\n",
        )
        .unwrap()
        .cli;
        assert_eq!(c.color, Some(false));
        assert_eq!(c.markdown, Some(true));
        assert_eq!(c.approval, Approval::Auto);
        assert_eq!(c.history_size, 50);
    }

    #[test]
    fn an_unknown_approval_is_an_error_rather_than_a_silent_ask() {
        // Guessing here would mean either prompting someone who asked not to be prompted, or
        // not prompting someone who asked to be. Refuse instead.
        let err = Config::from_toml_str("[cli]\napproval = \"sometimes\"\n").unwrap_err();
        assert!(err.contains("approval"), "{err}");
    }

    #[test]
    fn web_section_parses_its_ttl_and_default_profile() {
        let d = Config::from_toml_str("").unwrap().web;
        assert_eq!(d.session_ttl_hours, DEFAULT_SESSION_TTL_HOURS);
        assert_eq!(d.default_profile, None);

        let w = Config::from_toml_str("[web]\nsession_ttl_hours = 1\ndefault_profile = \"work\"\n")
            .unwrap()
            .web;
        assert_eq!(w.session_ttl_hours, 1);
        assert_eq!(w.default_profile.as_deref(), Some("work"));
    }

    /// A `config.toml` on its own has to load: copying the starter file to another host, or
    /// losing `.env`, must not take every command down behind a dashboard credential. The token
    /// loads empty and only the dashboard refuses it.
    #[test]
    fn the_starter_config_loads_without_a_dotenv_and_leaves_the_token_unset() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.toml");
        std::fs::write(&path, starter()).unwrap();
        // `|_| None` is the whole environment: nothing set, and no config dir to find a `.env`
        // in, which is exactly what a copied file sees on a new machine.
        let c = Config::load_with(Some(&path), &|_| None)
            .expect("the starter config loads with no .env at all");
        assert_eq!(
            c.web.auth_token, None,
            "an unset token loads as no token, not as a load error and not as an empty secret"
        );
        assert_eq!(c.provider.model, Config::default().provider.model);
    }

    #[test]
    fn starter_config_parses_and_matches_defaults() {
        let c = Config::from_toml_str(&starter()).unwrap();
        let d = Config::default();
        assert_eq!(c.tools.read_file, d.tools.read_file);
        assert_eq!(c.tools.fetch, d.tools.fetch);
        assert_eq!(c.web.port, d.web.port);
        assert!(c.provider.base_url.is_empty());
    }

    #[test]
    fn partial_file_fills_defaults() {
        let c = Config::from_toml_str(
            "[provider]\nbase_url=\"http://x/v1\"\nmodel=\"m\"\n[tools]\nshell=\"deny\"\n",
        )
        .unwrap();
        assert_eq!(c.provider.base_url, "http://x/v1");
        assert_eq!(c.tools.shell, Policy::Deny);
        assert_eq!(c.tools.write_file, Policy::Allow);
        assert_eq!(
            c.agent.max_iterations,
            usize::MAX,
            "no cap unless the box asks for one"
        );
        assert!(c.require_provider().is_ok());

        for word in ["unlimited", "none", "inf", "0", "-1"] {
            let raw = format!("[agent]\nmax_iterations = {word}\n");
            let raw = if word.parse::<i64>().is_ok() {
                raw
            } else {
                format!("[agent]\nmax_iterations = \"{word}\"\n")
            };
            let c = Config::from_toml_str(&raw).unwrap();
            assert_eq!(c.agent.max_iterations, usize::MAX, "`{word}` means no cap");
        }

        let c = Config::from_toml_str("[agent]\nmax_iterations = 12\n").unwrap();
        assert_eq!(c.agent.max_iterations, 12, "a number is a cap");

        let words = Config::from_toml_str("[agent]\nmax_iterations = \"unlimited\"\n").unwrap();
        let printed = toml::to_string(&words).unwrap();
        assert!(
            printed.contains("max_iterations = \"unlimited\""),
            "the schema says the word, not a length: {printed}"
        );

        let refused = Config::from_toml_str("[agent]\nmax_iterations = \"plenty\"\n");
        assert!(
            refused.is_err(),
            "a word that is not one of ours is an error"
        );
    }

    #[test]
    fn unknown_policy_is_rejected() {
        assert!(Config::from_toml_str("[tools]\nshell=\"yolo\"\n").is_err());
    }

    #[test]
    fn env_overrides_file() {
        let dir = tempfile::tempdir().unwrap();
        let p = dir.path().join("c.toml");
        std::fs::write(
            &p,
            "[provider]\nbase_url=\"http://file/v1\"\nmodel=\"file-model\"\napi_key=\"file-key\"\n",
        )
        .unwrap();
        let env = env_of(&[
            ("ECLIPSE_BASE_URL", "http://env/v1"),
            ("ECLIPSE_API_KEY", "env-key"),
        ]);
        let c = Config::load_with(Some(&p), &env).unwrap();
        assert_eq!(c.provider.base_url, "http://env/v1");
        assert_eq!(c.provider.model, "file-model");
        assert_eq!(c.provider.api_key.as_deref(), Some("env-key"));
    }

    #[test]
    fn api_key_env_indirection() {
        let env = env_of(&[("MY_KEY", "secret")]);
        let mut c = Config::from_toml_str("[provider]\napi_key_env=\"MY_KEY\"\n").unwrap();
        c.apply_env(&env);
        assert_eq!(c.provider.api_key.as_deref(), Some("secret"));
    }

    #[test]
    fn debug_redacts_api_key() {
        let mut c = Config::default();
        c.provider.api_key = Some("hunter2".into());
        assert!(!format!("{c:?}").contains("hunter2"));
    }

    #[test]
    fn debug_and_redacted_toml_hide_web_token() {
        let mut c = Config::default();
        c.web.auth_token = Some("s3cret-token-value".into());
        assert!(!format!("{c:?}").contains("s3cret"));
        assert!(!c.to_toml_redacted().unwrap().contains("s3cret"));
    }

    /// `Config` derives `Debug` and holds the loaded `.env`; the values in it are the whole point of
    /// the file. `config show` was safe, `{cfg:?}` was not — and a panic message or a failing
    /// `assert_eq!` is exactly where it would have gone out.
    #[test]
    fn debug_never_prints_a_dotenv_value() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("root");
        std::fs::create_dir_all(&root).unwrap();
        std::fs::write(
            root.join(".env"),
            "ECLIPSE_API_KEY=dotenvvalue123\nMY_PRIVATE_MIRROR=mirrorvalue456\n",
        )
        .unwrap();
        let cfg_path = root.join("config.toml");
        std::fs::write(
            &cfg_path,
            "[provider]\nbase_url = \"http://127.0.0.1:9/v1\"\nmodel = \"m\"\napi_key = \"${ECLIPSE_API_KEY}\"\n",
        )
        .unwrap();
        let env = env_of(&[
            ("ECLIPSE_HOME", root.to_str().unwrap()),
            ("HOME", dir.path().to_str().unwrap()),
        ]);

        let cfg = Config::load_with_profile(Some(&cfg_path), None, &env).unwrap();
        let debug = format!("{cfg:?}");
        assert!(
            !debug.contains("dotenvvalue123") && !debug.contains("mirrorvalue456"),
            "the .env values must never be printed: {debug}"
        );
        assert!(debug.contains("ECLIPSE_API_KEY"), "{debug}");
        assert!(debug.contains("Dotenv"), "{debug}");
        // And the token reached the provider, so this is a real loaded .env, not an empty one.
        assert_eq!(cfg.provider.api_key.as_deref(), Some("dotenvvalue123"));
    }

    #[test]
    fn redacted_toml_hides_key_and_round_trips() {
        let mut c = Config::default();
        c.provider.api_key = Some("hunter2".into());
        c.provider.model = "m".into();
        let t = c.to_toml_redacted().unwrap();
        assert!(!t.contains("hunter2"));
        assert_eq!(Config::from_toml_str(&t).unwrap().provider.model, "m");
    }

    /// The update track is a word in the file and a branch in the code: `release` and `main` are
    /// one ref, which is why the key names a track. A word this build does not know is a parse
    /// error, never a silent fall back to the release track.
    #[test]
    fn the_update_track_names_a_branch_and_takes_two_words() {
        assert_eq!(Config::default().update.track, Track::Release);
        assert_eq!(Track::Release.branch(), "main");
        assert_eq!(Track::Develop.branch(), "develop");
        let cfg = Config::from_toml_str("[update]\ntrack = \"develop\"\n").unwrap();
        assert_eq!(cfg.update.track, Track::Develop);
        assert_eq!(cfg.update.track.label(), "develop");
        let err = Config::from_toml_str("[update]\ntrack = \"main\"\n")
            .unwrap_err()
            .to_string();
        assert!(
            err.contains("main") && err.contains("develop"),
            "the refusal lists the words it takes: {err}"
        );
    }

    /// A URL is printed as it is, because that is how you check what you configured — but a URL can
    /// carry a secret, and both legitimate spellings were printed verbatim by `config show`.
    #[test]
    fn a_url_keeps_its_shape_and_loses_its_secrets() {
        let mut c = Config::default();
        c.provider.base_url = "https://user:hunter2@gw.internal/v1".into();
        c.update.remote =
            Some("https://mirror.internal/releases?access_token=abc123&page=2".into());
        c.update.releases = Some("https://mirror.internal/api#frag".into());

        let t = c.to_toml_redacted().unwrap();
        assert!(
            !t.contains("hunter2") && !t.contains("abc123"),
            "the secrets are gone: {t}"
        );
        // The shape survives: scheme, host, path, and the *names* of the parameters.
        assert!(
            t.contains("https://<redacted>@gw.internal/v1"),
            "the userinfo is replaced, not the URL: {t}"
        );
        assert!(
            t.contains("access_token=<redacted>&page=2"),
            "the secret parameter keeps its name and loses its value: {t}"
        );
        assert!(t.contains("https://mirror.internal/api#frag"), "{t}");

        // And the same URL is not the one place a secret survives: `{cfg:?}` scrubs it too.
        let debug = format!("{c:?}");
        assert!(!debug.contains("hunter2"), "{debug}");

        // A URL with nothing secret in it is left exactly as written.
        let plain = Config::default();
        assert!(plain
            .to_toml_redacted()
            .unwrap()
            .contains(&plain.provider.base_url));
    }

    #[test]
    fn one_root_layout() {
        // One directory, everything in it. Deliberately not XDG: the reason is in `home_root`.
        let env = env_of(&[("HOME", "/home/u")]);
        assert_eq!(
            config_path(&env).unwrap(),
            PathBuf::from("/home/u/.eclipse/config.toml")
        );
        assert_eq!(
            Config::default().sessions_dir(&env).unwrap(),
            PathBuf::from("/home/u/.eclipse/state/sessions")
        );
        assert_eq!(
            Config::default().memory_dir(&env).unwrap(),
            PathBuf::from("/home/u/.eclipse/memory")
        );
        // XDG is not consulted, even when it is set: two roots is the thing this layout exists
        // to prevent, and honouring XDG "sometimes" would be the worst of both.
        let env = env_of(&[
            ("HOME", "/home/u"),
            ("XDG_CONFIG_HOME", "/x/cfg"),
            ("XDG_STATE_HOME", "/x/state"),
        ]);
        assert_eq!(
            config_path(&env).unwrap(),
            PathBuf::from("/home/u/.eclipse/config.toml")
        );
        // ECLIPSE_HOME is the one way to move it.
        let env = env_of(&[("HOME", "/home/u"), ("ECLIPSE_HOME", "/opt/ecl")]);
        assert_eq!(
            config_path(&env).unwrap(),
            PathBuf::from("/opt/ecl/config.toml")
        );
    }

    #[test]
    fn missing_default_file_is_ok_but_explicit_missing_is_error() {
        let dir = tempfile::tempdir().unwrap();
        let env = env_of(&[("HOME", dir.path().to_str().unwrap())]);
        assert!(Config::load_with(None, &env).is_ok());
        assert!(Config::load_with(Some(&dir.path().join("nope.toml")), &env).is_err());
    }

    #[test]
    fn auto_prune_is_off_by_default_and_can_be_enabled() {
        assert!(!Config::default().sessions.auto_prune);
        let c = Config::from_toml_str("[sessions]\nauto_prune = true\nretention_keep_count = 5\n")
            .unwrap();
        assert!(c.sessions.auto_prune);
        assert_eq!(c.sessions.retention_keep_count, 5);
    }

    #[test]
    fn sessions_dir_expands_tilde() {
        let env = env_of(&[("HOME", "/home/u")]);
        let mut c = Config::default();
        c.sessions.dir = Some("~/s".into());
        assert_eq!(c.sessions_dir(&env).unwrap(), PathBuf::from("/home/u/s"));
    }

    #[test]
    fn config_init_writes_a_private_dotenv_and_the_config_refers_to_it() {
        let dir = tempfile::tempdir().unwrap();
        let p = dir.path().join("a/b/config.toml");
        let env = env_of(&[("ECLIPSE_HOME", dir.path().to_str().unwrap())]);
        let report = write_starter_config(&p, false, &env).unwrap();
        assert!(report.dotenv_written);
        assert_eq!(
            report.dotenv,
            dir.path().join(".env"),
            "the .env goes where the loader reads it, not beside a config elsewhere"
        );

        let dotenv = std::fs::read_to_string(&report.dotenv).unwrap();
        let token = dotenv
            .lines()
            .find_map(|l| l.strip_prefix("ECLIPSE_WEB_AUTH_TOKEN="))
            .expect("the token lives in .env");
        assert_eq!(token.len(), 64, "a generated token, not a placeholder");
        assert!(token.bytes().all(|b| b.is_ascii_hexdigit()));
        assert!(
            !std::fs::read_to_string(&p).unwrap().contains(token),
            "the config carries the reference, never the secret"
        );

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            for f in [&p, &report.dotenv] {
                assert_eq!(f.metadata().unwrap().permissions().mode() & 0o777, 0o600);
            }
        }

        // End to end: the value is resolvable through the chain the loader uses. The config
        // has to sit where the loader looks, or its `.env` is a different file's.
        let root = dir.path().join("root");
        let cfg_dir = root.clone();
        std::fs::create_dir_all(&cfg_dir).unwrap();
        let real = cfg_dir.join("config.toml");
        let env = env_of(&[
            ("ECLIPSE_HOME", root.to_str().unwrap()),
            ("HOME", dir.path().to_str().unwrap()),
        ]);
        let written = write_starter_config(&real, false, &env).unwrap();
        let cfg = Config::load_with_profile(Some(&real), None, &env).unwrap();
        let token = std::fs::read_to_string(&written.dotenv)
            .unwrap()
            .lines()
            .find_map(|l| {
                l.strip_prefix("ECLIPSE_WEB_AUTH_TOKEN=")
                    .map(str::to_string)
            })
            .unwrap();
        assert_eq!(cfg.web.auth_token.as_deref(), Some(token.as_str()));
        assert_eq!(cfg.dotenv.files, vec![written.dotenv]);
    }

    /// A `.env` line with no value is a half-typed line, not a setting: every other layer treats
    /// empty as absent, and the loader used to hand the raw empty string through — which blanked the
    /// key the config file already had and made requests go out unauthenticated.
    #[test]
    fn an_empty_dotenv_value_is_absent_not_an_empty_override() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("root");
        std::fs::create_dir_all(&root).unwrap();
        std::fs::write(
            root.join(".env"),
            "ECLIPSE_API_KEY=\nECLIPSE_MODEL=\nECLIPSE_BASE_URL=\n",
        )
        .unwrap();
        let cfg_path = root.join("config.toml");
        std::fs::write(
            &cfg_path,
            "[provider]\napi_key = \"sk-from-the-file\"\nmodel = \"keep-me\"\n\
             base_url = \"http://127.0.0.1:9999/v1\"\n",
        )
        .unwrap();
        let env = env_of(&[
            ("ECLIPSE_HOME", root.to_str().unwrap()),
            ("HOME", dir.path().to_str().unwrap()),
        ]);

        let cfg = Config::load_with_profile(Some(&cfg_path), None, &env).unwrap();
        assert_eq!(
            cfg.provider.api_key.as_deref(),
            Some("sk-from-the-file"),
            "an empty .env value must not blank the key"
        );
        assert_eq!(cfg.provider.model, "keep-me", "nor the model");
        assert_eq!(
            cfg.provider.base_url, "http://127.0.0.1:9999/v1",
            "nor the base URL"
        );
    }

    #[test]
    fn context_files_are_seeded_and_existing_ones_are_kept() {
        let tmp = tempfile::tempdir().unwrap();
        let memory = tmp.path().join("memory");
        let created = seed_context_files(&memory).unwrap();
        assert_eq!(created.len(), 3, "AGENT, USER, MEMORY: {created:?}");
        assert!(memory.join("AGENT.md").exists());
        assert!(memory.join("USER.md").exists());
        assert!(memory.join("MEMORY.md").exists());
        assert_eq!(
            std::fs::read_to_string(memory.join("MEMORY.md")).unwrap(),
            ""
        );

        // Re-run: nothing is overwritten.
        let created = seed_context_files(&memory).unwrap();
        assert!(
            created.is_empty(),
            "existing files are left alone: {created:?}"
        );

        // All three hold an operator's text, not just the one this test used to check: a rewrite
        // of a starter is the failure mode (#295), so the assertion has to be byte for byte on
        // every file that can carry a person's words.
        let written = [
            ("AGENT.md", "run make, no cargo test\n"),
            ("USER.md", "I am the operator; keep it short\n"),
            ("MEMORY.md", "- one durable fact\n"),
        ];
        for (name, body) in written {
            std::fs::write(memory.join(name), body).unwrap();
        }
        let created = seed_context_files(&memory).unwrap();
        assert!(created.is_empty(), "{created:?}");
        for (name, body) in written {
            assert_eq!(
                std::fs::read_to_string(memory.join(name)).unwrap(),
                body,
                "{name} was rewritten"
            );
        }
    }

    /// "Once" is a fact about a directory, not about a process or an install: a profile whose
    /// `memory/` has the files is left alone exactly as the base install is, and a profile that
    /// has never been used is a first install and gets the starters. Seeding one must not touch
    /// the other, which is what makes it safe for `setup` to run against any profile (#295).
    #[test]
    fn a_new_profile_is_a_first_install_and_an_existing_one_is_never_rewritten() {
        let tmp = tempfile::tempdir().unwrap();
        let base = tmp.path().join("memory");
        let lived_in = tmp.path().join("profiles/work/memory");
        let fresh = tmp.path().join("profiles/lab/memory");

        assert_eq!(seed_context_files(&base).unwrap().len(), 3);
        std::fs::write(base.join("USER.md"), "the operator\n").unwrap();

        std::fs::create_dir_all(&lived_in).unwrap();
        for name in ["AGENT.md", "USER.md", "MEMORY.md"] {
            std::fs::write(lived_in.join(name), format!("{name} as it was lived in\n")).unwrap();
        }

        assert!(
            seed_context_files(&lived_in).unwrap().is_empty(),
            "an existing profile's files are not rewritten"
        );
        assert_eq!(
            seed_context_files(&fresh).unwrap().len(),
            3,
            "a profile that has never been used is a first install"
        );

        assert_eq!(
            std::fs::read_to_string(base.join("USER.md")).unwrap(),
            "the operator\n"
        );
        for name in ["AGENT.md", "USER.md", "MEMORY.md"] {
            assert_eq!(
                std::fs::read_to_string(lived_in.join(name)).unwrap(),
                format!("{name} as it was lived in\n")
            );
        }
    }

    /// `--config /other/config.toml`: the config is there, the secrets are in the config
    /// directory. Writing the `.env` beside the config put it where no start would ever read it —
    /// `config init` reported a dashboard token that the next launch did not have.
    #[test]
    fn config_init_puts_the_dotenv_where_a_start_with_that_config_will_read_it() {
        let dir = tempfile::tempdir().unwrap();
        let home = dir.path().join("home");
        std::fs::create_dir_all(&home).unwrap();
        let elsewhere = dir.path().join("other");
        let path = elsewhere.join("config.toml");
        let env = env_of(&[
            ("ECLIPSE_HOME", home.to_str().unwrap()),
            ("HOME", dir.path().to_str().unwrap()),
        ]);

        let report = write_starter_config(&path, false, &env).unwrap();
        let token = std::fs::read_to_string(&report.dotenv)
            .unwrap()
            .lines()
            .find_map(|l| l.strip_prefix("ECLIPSE_WEB_AUTH_TOKEN="))
            .expect("the token lives in .env")
            .to_string();
        assert_eq!(report.dotenv, home.join(".env"));

        let cfg = Config::load_with_profile(Some(&path), None, &env).unwrap();
        assert_eq!(
            cfg.web.auth_token.as_deref(),
            Some(token.as_str()),
            "the token `config init` reported is the token the next start reads"
        );
    }

    #[test]
    fn config_init_refuses_to_overwrite_a_config_without_force() {
        let dir = tempfile::tempdir().unwrap();
        let p = dir.path().join("c/config.toml");
        let env = env_of(&[("ECLIPSE_HOME", dir.path().to_str().unwrap())]);
        write_starter_config(&p, false, &env).unwrap();
        assert!(write_starter_config(&p, false, &env).is_err());
    }

    #[test]
    fn config_init_never_overwrites_an_existing_dotenv() {
        let dir = tempfile::tempdir().unwrap();
        let p = dir.path().join("d/config.toml");
        let env = env_of(&[("ECLIPSE_HOME", dir.path().to_str().unwrap())]);
        let first = write_starter_config(&p, false, &env).unwrap();
        let before = std::fs::read_to_string(&first.dotenv).unwrap();

        // `--force` replaces the config. It is not consent to lose the user's secrets.
        let again = write_starter_config(&p, true, &env).unwrap();
        assert!(!again.dotenv_written);
        assert_eq!(std::fs::read_to_string(&again.dotenv).unwrap(), before);
    }

    #[test]
    fn a_profile_overlay_merges_over_the_base_config() {
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path().join("home");
        let cfg_dir = home.join(".eclipse");
        std::fs::create_dir_all(cfg_dir.join("profiles/work")).unwrap();
        std::fs::write(
            cfg_dir.join("config.toml"),
            "[provider]\nbase_url = \"http://base/v1\"\nmodel = \"base-model\"\n\
             temperature = 0.2\n[agent]\nmax_iterations = 7\n",
        )
        .unwrap();
        std::fs::write(
            cfg_dir.join("profiles/work/config.toml"),
            "[provider]\nmodel = \"work-model\"\n",
        )
        .unwrap();
        let env = env_of(&[("HOME", home.to_str().unwrap())]);

        let base = Config::load_with(None, &env).unwrap();
        assert_eq!(base.provider.model, "base-model");
        assert_eq!(base.profile_name(), "default");

        let work = Config::load_with_profile(None, Some("work"), &env).unwrap();
        // The overlay replaced one key and left its siblings alone.
        assert_eq!(work.provider.model, "work-model");
        assert_eq!(work.provider.base_url, "http://base/v1");
        assert_eq!(work.provider.temperature, Some(0.2));
        assert_eq!(work.agent.max_iterations, 7);
        assert_eq!(work.profile_name(), "work");
        // Same config file, different state.
        assert_eq!(
            work.sessions_dir(&env).unwrap(),
            home.join(".eclipse/profiles/work/state/sessions")
        );
        assert_eq!(
            base.sessions_dir(&env).unwrap(),
            home.join(".eclipse/state/sessions")
        );
        assert_eq!(
            work.state_dir(&env).unwrap(),
            home.join(".eclipse/profiles/work/state")
        );
    }

    #[test]
    fn the_profile_comes_from_the_environment_and_the_argument_wins() {
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path().join("home");
        std::fs::create_dir_all(home.join(".eclipse/profiles/env")).unwrap();
        std::fs::write(
            home.join(".eclipse/profiles/env/config.toml"),
            "[agent]\nmax_iterations = 3\n",
        )
        .unwrap();
        let env = env_of(&[("HOME", home.to_str().unwrap()), ("ECLIPSE_PROFILE", "env")]);
        let from_env = Config::load_with(None, &env).unwrap();
        assert_eq!(from_env.profile_name(), "env");
        assert_eq!(from_env.agent.max_iterations, 3);

        let explicit = Config::load_with_profile(None, Some("other"), &env).unwrap();
        assert_eq!(explicit.profile_name(), "other");
        // No overlay for "other": the base defaults apply, which is no cap at all.
        assert_eq!(explicit.agent.max_iterations, usize::MAX);
    }

    #[test]
    fn the_default_profile_keeps_the_plain_state_directory() {
        let env = env_of(&[("HOME", "/home/u")]);
        assert_eq!(
            state_dir_for(&env, Some("default")).unwrap(),
            PathBuf::from("/home/u/.eclipse/state")
        );
        assert_eq!(
            state_dir_for(&env, None).unwrap(),
            PathBuf::from("/home/u/.eclipse/state")
        );
        assert_eq!(
            state_dir_for(&env, Some("work")).unwrap(),
            PathBuf::from("/home/u/.eclipse/profiles/work/state")
        );
    }

    #[test]
    fn a_profile_name_must_be_a_safe_directory_name() {
        for bad in ["", "../etc", "a/b", "sp ace"] {
            assert!(
                validate_profile_name(bad).is_err(),
                "{bad:?} should be rejected"
            );
        }
        assert!(validate_profile_name("work-2026_x").is_ok());
        let env = env_of(&[("HOME", "/home/u")]);
        assert!(Config::load_with_profile(None, Some("../evil"), &env).is_err());
    }

    #[test]
    fn plugin_directories_put_the_profile_first() {
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path().join("home");
        std::fs::create_dir_all(home.join(".eclipse")).unwrap();
        let env = env_of(&[("HOME", home.to_str().unwrap())]);
        let mut cfg = Config::default();
        let default_dirs = cfg.plugins_dirs(&env);
        assert_eq!(
            default_dirs,
            vec![home.join(".eclipse/plugins")],
            "the default profile has no profile plugin dir"
        );

        cfg.profile = Some("work".into());
        let dirs = cfg.plugins_dirs(&env);
        assert_eq!(dirs.len(), 2);
        assert_eq!(dirs[0], home.join(".eclipse/profiles/work/plugins"));
        assert_eq!(dirs[1], home.join(".eclipse/plugins"));

        cfg.plugins.dir = Some("~/elsewhere/plugins".into());
        assert_eq!(cfg.plugins_dirs(&env)[1], home.join("elsewhere/plugins"));
    }

    #[test]
    fn plugins_are_off_until_named() {
        let cfg = Config::default();
        assert!(cfg.plugins.enabled.is_empty());
        assert!(cfg.plugins.dir.is_none());
        let parsed = Config::from_toml_str("[plugins]\nenabled = [\"a\", \"b\"]\n").unwrap();
        assert_eq!(parsed.plugins.enabled, ["a", "b"]);
    }

    // ---- editing a config file in place (what `eclipse setup` does) ----------------------

    #[test]
    fn setting_a_key_fills_the_empty_value_and_keeps_every_other_line() {
        let text = toml_set_string(&starter(), "provider", "base_url", "http://h:1/v1");
        let text = toml_set_string(&text, "provider", "model", "some-model");
        assert!(text.contains("base_url = \"http://h:1/v1\""), "{text}");
        assert!(text.contains("model = \"some-model\""), "{text}");
        // The shipped file is what a person reads and edits: nothing else may move.
        assert!(text.contains("# Every setting this build reads"));
        assert!(text.contains("[agent]"));
        assert!(
            !text.contains("base_url = \"\""),
            "the empty blank must be gone: {text}"
        );
        // And it is still a config the real loader accepts.
        let cfg: Config = toml::from_str(&text).expect("edited config must parse");
        assert_eq!(cfg.provider.base_url, "http://h:1/v1");
        assert_eq!(cfg.provider.model, "some-model");
    }

    #[test]
    fn setting_a_key_turns_a_commented_template_line_into_the_real_one() {
        let text = toml_set_string(&starter(), "provider", "profile", "llamacpp");
        assert!(text.contains("\nprofile = \"llamacpp\""), "{text}");
        assert_eq!(
            text.matches("\nprofile = ").count(),
            1,
            "no duplicate key (the commented [web] default_profile is a different key): {text}"
        );
        let cfg: Config = toml::from_str(&text).unwrap();
        assert_eq!(cfg.provider.profile.as_deref(), Some("llamacpp"));
    }

    #[test]
    fn setting_a_key_does_not_reach_into_another_section_with_the_same_name() {
        // `[sessions] dir` and `[plugins] dir` both exist; only the one asked for may change.
        let text = toml_set_string(&starter(), "sessions", "dir", "/tmp/sessions-here");
        let cfg: Config = toml::from_str(&text).unwrap();
        assert_eq!(
            cfg.sessions.dir.as_deref(),
            Some(std::path::Path::new("/tmp/sessions-here"))
        );
        assert_eq!(cfg.plugins.dir, None, "{text}");
    }

    #[test]
    fn setting_a_key_in_a_missing_section_adds_the_section() {
        let text = toml_set_string("[agent]\nmax_iterations = 5\n", "web", "host", "0.0.0.0");
        let cfg: Config = toml::from_str(&text).unwrap();
        assert_eq!(cfg.web.host, "0.0.0.0");
        assert_eq!(cfg.agent.max_iterations, 5);
    }

    #[test]
    fn reading_a_key_sees_the_live_line_and_not_the_commented_one() {
        let text = starter();
        assert_eq!(
            toml_value(&text, "provider", "base_url"),
            Some(String::new())
        );
        // An absent-by-default key is present in the file *as a comment*, and reads as unset:
        // nothing is imposed by shipping the key, which is the whole point of the two kinds of
        // line. `config set` is what turns one into a value.
        assert_eq!(toml_value(&text, "provider", "temperature"), None);
        assert!(text.contains("# temperature ="), "{text}");
        assert_eq!(
            toml_value(&text, "agent", "max_iterations"),
            Some("unlimited".to_string()),
            "the cap is written, and its off value is the word `unlimited`"
        );
    }

    #[test]
    fn a_config_written_by_setup_is_private_and_a_dotenv_keeps_its_other_lines() {
        let dir = tempfile::tempdir().unwrap();
        let cfg_path = dir.path().join("config.toml");
        let dotenv = dir.path().join(".env");
        save_config_text(&cfg_path, "[provider]\nbase_url = \"h\"\n").unwrap();
        save_dotenv_var(&dotenv, "ECLIPSE_WEB_AUTH_TOKEN", "tok").unwrap();
        save_dotenv_var(&dotenv, "ECLIPSE_API_KEY", "sk-1").unwrap();
        save_dotenv_var(&dotenv, "ECLIPSE_API_KEY", "sk-2").unwrap();
        let body = std::fs::read_to_string(&dotenv).unwrap();
        assert_eq!(body.matches("ECLIPSE_API_KEY").count(), 1, "{body}");
        assert_eq!(
            dotenv_var(&dotenv, "ECLIPSE_API_KEY").as_deref(),
            Some("sk-2")
        );
        assert_eq!(
            dotenv_var(&dotenv, "ECLIPSE_WEB_AUTH_TOKEN").as_deref(),
            Some("tok"),
            "an unrelated secret must survive"
        );
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            for f in [&cfg_path, &dotenv] {
                let mode = std::fs::metadata(f).unwrap().permissions().mode() & 0o777;
                assert_eq!(mode, 0o600, "{}", f.display());
            }
        }
    }

    #[test]
    fn trace_content_is_off_by_default_and_can_be_set() {
        assert!(!Config::default().agent.trace_content);
        let cfg = Config::from_toml_str(
            "[agent]
trace_content = true
",
        )
        .unwrap();
        assert!(cfg.agent.trace_content);
    }

    #[test]
    fn an_output_schema_is_absent_until_somebody_asks_for_one() {
        // A default schema would make every reply in a conversation have to be JSON, so there is
        // no default at all: it is opt-in, per install or per run.
        assert_eq!(Config::default().agent.output_schema, None);
        let cfg = Config::from_toml_str(
            "[agent]
output_schema = \"schemas/plan.json\"
",
        )
        .unwrap();
        assert_eq!(
            cfg.agent.output_schema.as_deref(),
            Some("schemas/plan.json")
        );
    }

    #[test]
    fn the_user_section_has_the_defaults_the_docs_promise() {
        let cfg = Config::default();
        assert_eq!(cfg.user.file, "USER.md");
        assert_eq!(cfg.user.memory_file, "MEMORY.md");
        assert_eq!(cfg.user.memory_budget_chars, 3000);
        assert_eq!(
            cfg.agent.context_file_max_chars,
            crate::context_files::DEFAULT_MAX_FILE_CHARS
        );
        assert_eq!(
            cfg.agent.context_files_budget_chars,
            crate::context_files::DEFAULT_BUDGET_CHARS
        );
    }

    #[test]
    fn the_context_and_memory_budgets_can_be_set_in_the_file() {
        let cfg = Config::from_toml_str(
            "[agent]\ncontext_file_max_chars = 100\ncontext_files_budget_chars = 200\n\
             [user]\nfile = \"WHO.md\"\nmemory_file = \"FACTS.md\"\nmemory_budget_chars = 50\n",
        )
        .unwrap();
        assert_eq!(cfg.agent.context_file_max_chars, 100);
        assert_eq!(cfg.agent.context_files_budget_chars, 200);
        assert_eq!(cfg.user.file, "WHO.md");
        assert_eq!(cfg.user.memory_file, "FACTS.md");
        assert_eq!(cfg.user.memory_budget_chars, 50);
    }

    #[test]
    fn the_default_profile_keeps_its_files_in_the_config_directory() {
        let env = |k: &str| match k {
            "HOME" => Some("/home/m".to_string()),
            _ => None,
        };
        let mut cfg = Config::default();
        assert_eq!(
            cfg.context_dir(&env),
            Some(PathBuf::from("/home/m/.eclipse"))
        );
        cfg.profile = Some("work".into());
        assert_eq!(
            cfg.context_dir(&env),
            Some(PathBuf::from("/home/m/.eclipse/profiles/work"))
        );
    }

    #[test]
    fn scripts_live_under_the_profile_when_there_is_one_and_the_config_directory_otherwise() {
        let env = |k: &str| match k {
            "HOME" => Some("/home/m".to_string()),
            _ => None,
        };
        let mut cfg = Config::default();
        assert_eq!(
            cfg.scripts_dir(&env),
            Some(PathBuf::from("/home/m/.eclipse/scripts"))
        );
        cfg.profile = Some("work".into());
        assert_eq!(
            cfg.scripts_dir(&env),
            Some(PathBuf::from("/home/m/.eclipse/profiles/work/scripts"))
        );
        let no_home = |_: &str| None;
        assert_eq!(Config::default().scripts_dir(&no_home), None);
    }

    #[test]
    fn a_relative_config_path_still_gives_an_absolute_scripts_directory() {
        let env = |k: &str| match k {
            "ECLIPSE_CONFIG" => Some("rel/config.toml".to_string()),
            _ => None,
        };
        let dir = Config::default().scripts_dir(&env).unwrap();
        assert!(dir.is_absolute(), "{}", dir.display());
        assert!(dir.ends_with("rel/scripts"), "{}", dir.display());
    }

    #[test]
    fn the_script_tool_is_asked_about_by_default_and_the_policy_can_be_set_in_the_file() {
        assert_eq!(Config::default().tools.script, Policy::Ask);
        let cfg = Config::from_toml_str("[tools]\nscript = \"deny\"\n").unwrap();
        assert_eq!(cfg.tools.script, Policy::Deny);
        let starter = Config::from_toml_str(&super::tests::starter()).unwrap();
        assert_eq!(starter.tools.script, Policy::Ask);
        assert!(Config::from_toml_str("[tools]\nscript = \"yolo\"\n").is_err());
    }

    #[test]
    fn sight_defaults_to_auto_with_no_route_and_no_cloud() {
        let cfg = Config::default();
        assert_eq!(cfg.vision.mode, VisionMode::Auto);
        assert_eq!(cfg.vision.route, "");
        assert!(!cfg.vision.allow_cloud);
    }

    #[test]
    fn the_three_vision_modes_are_spelled_in_the_file_the_way_a_person_says_them() {
        for (text, mode) in [
            ("native", VisionMode::Native),
            ("text", VisionMode::Text),
            ("auto", VisionMode::Auto),
        ] {
            let cfg = Config::from_toml_str(&format!("[vision]\nmode = \"{text}\"\n")).unwrap();
            assert_eq!(cfg.vision.mode, mode, "{text}");
        }
    }

    #[test]
    fn a_vision_mode_nobody_implements_is_a_load_error_that_lists_the_three() {
        let err = Config::from_toml_str("[vision]\nmode = \"telepathy\"\n").unwrap_err();
        let sentence = err.to_string();
        assert!(sentence.contains("telepathy"), "{sentence}");
        assert!(sentence.contains("native"), "{sentence}");
        assert!(sentence.contains("text"), "{sentence}");
        assert!(sentence.contains("auto"), "{sentence}");
    }

    #[test]
    fn a_vision_route_that_is_not_a_route_is_refused_by_name() {
        let cfg = Config::from_toml_str(
            "[provider]\nbase_url = \"http://127.0.0.1:1/v1\"\nmodel = \"m\"\n\
             [vision]\nroute = \"sight\"\n",
        )
        .unwrap();
        let err = cfg.validate_routes().unwrap_err().to_string();
        assert!(err.contains("vision.route"), "{err}");
        assert!(err.contains("sight"), "{err}");
        assert!(err.contains("default"), "{err}");
    }

    #[test]
    fn a_vision_route_that_exists_validates() {
        let cfg = Config::from_toml_str(
            "[provider]\nbase_url = \"http://127.0.0.1:1/v1\"\nmodel = \"m\"\n\
             [vision]\nroute = \"default\"\n",
        )
        .unwrap();
        cfg.validate_routes().unwrap();
        assert_eq!(cfg.vision.route, "default");
    }

    #[test]
    fn the_skills_budget_has_its_documented_default_and_can_be_set_in_the_file() {
        assert_eq!(Config::default().skills.index_budget_chars, 4000);
        let cfg = Config::from_toml_str("[skills]\nindex_budget_chars = 250\n").unwrap();
        assert_eq!(cfg.skills.index_budget_chars, 250);
        assert!(starter().contains("[skills]"));
        let starter = Config::from_toml_str(&super::tests::starter()).unwrap();
        assert_eq!(starter.skills.index_budget_chars, 4000);
    }

    #[test]
    fn the_redacted_config_shows_the_skills_section() {
        let mut cfg = Config::default();
        cfg.skills.index_budget_chars = 123;
        let shown = cfg.to_toml_redacted().unwrap();
        assert!(shown.contains("[skills]"), "{shown}");
        assert!(shown.contains("index_budget_chars = 123"), "{shown}");
    }

    #[test]
    fn the_starter_writes_the_context_file_settings() {
        let text = starter();
        let cfg = Config::from_toml_str(&text).unwrap();
        assert_eq!(cfg.user.memory_file, "MEMORY.md");
        for key in ["context_files_budget_chars", "[user]", "USER.md"] {
            assert!(text.contains(key), "the shipped file names `{key}`");
        }
    }

    // ---- routes (M12, slice 1) ----

    const TWO_ROUTES: &str = "\
[provider]
fallback = [\"local\", \"big\"]
[[provider.route]]
name = \"local\"
base_url = \"http://127.0.0.1:8081/v1\"
model = \"small\"
[[provider.route]]
name = \"big\"
base_url = \"http://10.0.0.2:8000/v1\"
model = \"large\"
api_key = \"hunter2\"
timeout_secs = 30
";

    fn parse(text: &str) -> Config {
        Config::from_toml_str(text).unwrap()
    }

    fn refusal(text: &str) -> String {
        let c = parse(text);
        c.validate_routes()
            .and_then(|_| c.chain().map(|_| ()))
            .unwrap_err()
            .to_string()
    }

    #[test]
    fn a_route_is_a_full_provider_config_and_inherits_nothing_from_provider() {
        let c = parse(
            "[provider]\nbase_url=\"http://d/v1\"\nmodel=\"dm\"\ntimeout_secs=7\n\
             [[provider.route]]\nname=\"r\"\nbase_url=\"http://r/v1\"\nmodel=\"rm\"\n",
        );
        let r = c.declared_routes();
        assert_eq!(
            r.iter().map(|r| r.name.as_str()).collect::<Vec<_>>(),
            ["default", "r"],
            "[provider] is the route called default"
        );
        assert_eq!(r[0].config.timeout_secs, 7);
        assert_eq!(
            r[1].config.timeout_secs, 120,
            "the route got the built-in default, not [provider]'s 7"
        );
    }

    #[test]
    fn provider_may_be_omitted_when_fallback_names_a_route() {
        let c = parse(TWO_ROUTES);
        c.validate_routes().unwrap();
        let chain = c.chain().unwrap();
        assert_eq!(chain.source, ChainSource::Fallback);
        let names: Vec<_> = chain.routes.iter().map(|r| r.name.as_str()).collect();
        assert_eq!(names, ["local", "big"]);
        assert_eq!(chain.routes[1].config.timeout_secs, 30);
        assert!(
            c.declared_routes().iter().all(|r| r.name != "default"),
            "no phantom default route appears"
        );
    }

    #[test]
    fn a_provider_endpoint_left_out_of_the_chain_is_refused_not_ignored() {
        // `fallback` is the whole chain. Writing a base_url into `[provider]` and then a
        // fallback that does not list `default` is a config where the endpoint the user typed
        // is never called — the sort of thing discovered later from a bill.
        let text = r#"
[provider]
base_url = "https://api.example.com/v1"
model = "gpt"
fallback = ["local"]

[[provider.route]]
name = "local"
base_url = "http://127.0.0.1:8080/v1"
model = "qwen3-coder"
"#;
        let err = parse(text).validate_routes().unwrap_err().to_string();
        assert!(err.contains("would never be called"), "{err}");
        assert!(
            err.contains("Put `default` first"),
            "it says what to type: {err}"
        );
    }

    #[test]
    fn listing_default_first_puts_the_provider_endpoint_back_in_front() {
        let text = r#"
[provider]
base_url = "https://api.example.com/v1"
model = "gpt"
fallback = ["default", "local"]

[[provider.route]]
name = "local"
base_url = "http://127.0.0.1:8080/v1"
model = "qwen3-coder"
"#;
        let c = parse(text);
        c.validate_routes().unwrap();
        let chain = c.chain().unwrap();
        let names: Vec<_> = chain.routes.iter().map(|r| r.name.as_str()).collect();
        assert_eq!(names, ["default", "local"]);
        assert_eq!(chain.routes[0].config.model, "gpt");
    }

    #[test]
    fn a_provider_block_of_tuning_keys_alone_does_not_become_a_route() {
        // `max_retries = 0` at provider level is a tuning key, not a server: a config that
        // uses only routes must not grow a `default` route with no endpoint, or every error
        // that lists the routes offers one that cannot be used.
        let text = "\
[provider]
max_retries = 0
fallback = [\"local\", \"big\"]
[[provider.route]]
name = \"local\"
base_url = \"http://127.0.0.1:8081/v1\"
model = \"small\"
[[provider.route]]
name = \"big\"
base_url = \"http://127.0.0.1:8082/v1\"
model = \"large\"
";
        let c = parse(text);
        c.validate_routes().unwrap();
        let names: Vec<String> = c.declared_routes().into_iter().map(|r| r.name).collect();
        assert_eq!(names, ["local", "big"], "no phantom default route");

        let mut pinned = parse(text);
        let e = pinned.pin_route(Some("default"), &|_| None).unwrap_err();
        let e = e.to_string();
        assert!(
            e.contains("unknown route `default`") && e.contains("local, big"),
            "{e}"
        );
        assert!(!e.contains("provider.base_url"), "{e}");
    }

    #[test]
    fn two_routes_with_the_same_name_are_refused_naming_it() {
        let e = refusal(
            "[[provider.route]]\nname=\"a\"\nbase_url=\"u\"\nmodel=\"m\"\n\
             [[provider.route]]\nname=\"a\"\nbase_url=\"u\"\nmodel=\"m\"\n",
        );
        assert!(e.contains("`a`") && e.contains("unique"), "{e}");
    }

    #[test]
    fn a_route_with_an_empty_or_missing_name_is_refused_by_position() {
        let e = refusal("[[provider.route]]\nname=\"  \"\nbase_url=\"u\"\nmodel=\"m\"\n");
        assert!(
            e.contains("provider.route #1") && e.contains("no name"),
            "{e}"
        );
        let e = refusal("[[provider.route]]\nbase_url=\"u\"\nmodel=\"m\"\n");
        assert!(e.contains("provider.route #1"), "{e}");
    }

    #[test]
    fn a_route_named_default_is_refused_only_when_provider_is_also_set() {
        let route = "[[provider.route]]\nname=\"default\"\nbase_url=\"u\"\nmodel=\"m\"\n";
        let e = refusal(&format!("[provider]\nbase_url=\"x\"\nmodel=\"y\"\n{route}"));
        assert!(e.contains("`default`") && e.contains("[provider]"), "{e}");
        let c = parse(&format!("[provider]\nfallback=[\"default\"]\n{route}"));
        assert_eq!(c.chain().unwrap().routes[0].name, "default");
    }

    #[test]
    fn a_route_without_base_url_or_model_is_refused_naming_the_route() {
        let e = refusal("[[provider.route]]\nname=\"nourl\"\nmodel=\"m\"\n");
        assert!(e.contains("`nourl`") && e.contains("base_url"), "{e}");
        let e = refusal("[[provider.route]]\nname=\"nomodel\"\nbase_url=\"u\"\n");
        assert!(e.contains("`nomodel`") && e.contains("model"), "{e}");
    }

    #[test]
    fn a_route_does_not_inherit_a_missing_base_url_from_provider() {
        let e = refusal(
            "[provider]\nbase_url=\"http://d/v1\"\nmodel=\"dm\"\n\
             [[provider.route]]\nname=\"r\"\nmodel=\"m\"\n",
        );
        assert!(e.contains("`r`") && e.contains("does not inherit"), "{e}");
    }

    #[test]
    fn fallback_naming_a_route_that_does_not_exist_lists_the_ones_that_do() {
        let e = refusal(&TWO_ROUTES.replace("\"big\"]", "\"cloud\"]"));
        assert!(e.contains("`cloud`"), "{e}");
        assert!(e.contains("local, big"), "{e}");
    }

    #[test]
    fn an_empty_fallback_is_a_typo_not_a_policy() {
        let e = refusal("[provider]\nfallback = []\n");
        assert!(e.contains("provider.fallback is empty"), "{e}");
    }

    #[test]
    fn a_fallback_that_lists_a_route_twice_is_refused() {
        let e = refusal(&TWO_ROUTES.replace("[\"local\", \"big\"]", "[\"local\", \"local\"]"));
        assert!(e.contains("`local` twice"), "{e}");
    }

    #[test]
    fn a_fallback_or_route_table_inside_a_route_is_refused() {
        let e = refusal(
            "[[provider.route]]\nname=\"r\"\nbase_url=\"u\"\nmodel=\"m\"\nfallback=[\"r\"]\n",
        );
        assert!(e.contains("`r`") && e.contains("directly"), "{e}");
    }

    const WITH_AUX: &str = "\
[provider]
base_url = \"http://d/v1\"
model = \"dm\"
aux = \"cheap\"
[[provider.route]]
name = \"cheap\"
base_url = \"http://c/v1\"
model = \"cm\"
";

    #[test]
    fn aux_names_a_route_and_the_role_table_says_so() {
        let chain = parse(WITH_AUX).chain().unwrap();
        assert_eq!(chain.aux.as_ref().map(|r| r.name.as_str()), Some("cheap"));
        assert_eq!(chain.aux.unwrap().config.model, "cm");
        let roles = parse(WITH_AUX).chain().unwrap().roles();
        assert_eq!(roles.len(), 2, "only roles that exist get a row");
        assert_eq!(roles[0].to_string(), "judgement \u{2192} cheap");
        assert_eq!(
            roles[1].to_string(),
            "delegate \u{2192} default (no delegate route set)"
        );
    }

    #[test]
    fn delegate_names_a_route_and_the_role_table_says_so() {
        let c = parse(&WITH_AUX.replace("aux = \"cheap\"", "delegate = \"cheap\""));
        let chain = c.chain().unwrap();
        assert_eq!(
            chain.delegate.as_ref().map(|r| r.name.as_str()),
            Some("cheap")
        );
        assert!(chain.aux.is_none());
        let roles = chain.roles();
        assert_eq!(
            roles[0].to_string(),
            "judgement \u{2192} default (no aux route set)"
        );
        assert_eq!(roles[1].to_string(), "delegate \u{2192} cheap");
    }

    #[test]
    fn a_pin_overrules_the_aux_and_delegate_routes_and_the_role_table_says_pinned() {
        // Both keys set, and `--route cheap`: every role is on `cheap`, because a pin bounds
        // where this run's text may go.
        let mut c =
            parse(&WITH_AUX.replace("aux = \"cheap\"", "aux = \"cheap\"\ndelegate = \"cheap\""));
        c.pin_route(Some("cheap"), &|_| None).unwrap();
        let chain = c.chain().unwrap();
        assert_eq!(chain.source, ChainSource::Pinned);
        assert_eq!(
            chain.aux.as_ref().map(|r| r.name.as_str()),
            Some("cheap"),
            "the pinned route, not the key's own value"
        );
        assert_eq!(
            chain.delegate.as_ref().map(|r| r.name.as_str()),
            Some("cheap")
        );
        for role in chain.roles() {
            assert!(role.pinned, "{role} should be pinned");
            assert!(!role.set, "{role} should not claim the key decided it");
            assert_eq!(role.route, "cheap");
            assert!(role.to_string().ends_with("(pinned)"), "{role}");
        }

        // The same config without a pin keeps both keys.
        let c =
            parse(&WITH_AUX.replace("aux = \"cheap\"", "aux = \"cheap\"\ndelegate = \"cheap\""));
        let chain = c.chain().unwrap();
        assert!(chain.roles().iter().all(|r| r.set && !r.pinned));
    }

    #[test]
    fn an_unknown_empty_or_nested_delegate_route_is_refused_with_the_routes_that_exist() {
        let e = refusal(&WITH_AUX.replace("aux = \"cheap\"", "delegate = \"ghost\""));
        assert!(
            e.contains("provider.delegate names `ghost`") && e.contains("default, cheap"),
            "{e}"
        );
        // Empty means unset, the same as an absent line — the shipped config writes it that way.
        let c = parse(&WITH_AUX.replace("aux = \"cheap\"", "delegate = \"\""));
        c.validate_routes()
            .expect("an empty delegate is a config that loads");
        let e = refusal(
            "[[provider.route]]\nname=\"r\"\nbase_url=\"u\"\nmodel=\"m\"\ndelegate=\"r\"\n\
             [provider]\nfallback=[\"r\"]\n",
        );
        assert!(
            e.contains("`r`") && e.contains("`delegate`") && e.contains("directly"),
            "{e}"
        );
        let e = Config::from_toml_str("[provider]\ndelegate = 3\n").unwrap_err();
        assert!(e.contains("delegate"), "{e}");
    }

    #[test]
    fn the_delegate_tool_is_asked_about_by_default_and_the_policy_can_be_set_in_the_file() {
        assert_eq!(Config::default().tools.delegate, Policy::Ask);
        let cfg = Config::from_toml_str("[tools]\ndelegate = \"deny\"\n").unwrap();
        assert_eq!(cfg.tools.delegate, Policy::Deny);
        let starter = Config::from_toml_str(&super::tests::starter()).unwrap();
        assert_eq!(starter.tools.delegate, Policy::Ask);
        assert!(Config::from_toml_str("[tools]\ndelegate = \"yolo\"\n").is_err());
    }

    #[test]
    fn with_no_aux_the_summary_role_uses_the_selected_route_and_says_it_was_not_set() {
        let chain = parse(TWO_ROUTES).chain().unwrap();
        assert!(chain.aux.is_none());
        assert_eq!(
            chain.roles()[0].to_string(),
            "judgement \u{2192} local (no aux route set)"
        );
        let bare = parse("[provider]\nbase_url=\"u\"\nmodel=\"m\"\n");
        assert_eq!(
            bare.chain().unwrap().roles()[0].to_string(),
            "judgement \u{2192} default (no aux route set)"
        );
    }

    #[test]
    fn an_unknown_aux_route_is_refused_listing_the_routes_that_exist() {
        let e = refusal(&WITH_AUX.replace("aux = \"cheap\"", "aux = \"ghost\""));
        assert!(
            e.contains("provider.aux names `ghost`") && e.contains("default, cheap"),
            "{e}"
        );
        // Empty is not a misspelling to refuse any more: it is the shipped spelling of "no aux
        // route", and the file a first install writes has it in it (`empty_is_none`). A name that
        // is *set* and unknown is still refused, above.
        let c = parse(&WITH_AUX.replace("aux = \"cheap\"", "aux = \"\""));
        c.validate_routes()
            .expect("an empty aux route is a config that loads");
        assert!(c.chain().unwrap().aux.is_none());
    }

    #[test]
    fn aux_inside_a_route_is_refused_like_fallback_and_route() {
        let e = refusal(
            "[[provider.route]]\nname=\"r\"\nbase_url=\"u\"\nmodel=\"m\"\naux=\"r\"\n\
             [provider]\nfallback=[\"r\"]\n",
        );
        assert!(
            e.contains("`r`") && e.contains("`aux`") && e.contains("directly"),
            "{e}"
        );
    }

    #[test]
    fn a_wrong_typed_aux_is_an_error_naming_the_key() {
        let e = Config::from_toml_str("[provider]\naux = 3\n").unwrap_err();
        assert!(e.contains("aux"), "{e}");
    }

    #[test]
    fn aux_may_name_the_default_route_when_provider_is_one() {
        let c = parse(&WITH_AUX.replace("aux = \"cheap\"", "aux = \"default\""));
        assert_eq!(c.chain().unwrap().aux.unwrap().name, "default");
        let tuning_only = "[provider]\naux = \"default\"\nmax_retries = 1\n\
             [[provider.route]]\nname=\"r\"\nbase_url=\"u\"\nmodel=\"m\"\n";
        assert!(refusal(tuning_only).contains("Routes that exist: r"));
    }

    #[test]
    fn a_wrong_typed_route_value_is_an_error_and_not_a_default() {
        let bad =
            "[[provider.route]]\nname=\"r\"\nbase_url=\"u\"\nmodel=\"m\"\ntimeout_secs=\"soon\"\n";
        let e = Config::from_toml_str(bad).unwrap_err();
        assert!(e.contains("timeout_secs") || e.contains("soon"), "{e}");
        let e = Config::from_toml_str("[provider]\nfallback = \"local\"\n").unwrap_err();
        assert!(e.contains("fallback") || e.contains("sequence"), "{e}");
    }

    #[test]
    fn routes_with_no_fallback_and_no_pin_say_what_to_set() {
        let e = refusal("[[provider.route]]\nname=\"r\"\nbase_url=\"u\"\nmodel=\"m\"\n");
        assert!(
            e.contains("fallback") && e.contains("--route") && e.contains("r"),
            "{e}"
        );
    }

    #[test]
    fn with_no_fallback_and_no_pin_the_chain_is_the_default_route_alone() {
        let c = parse(
            "[provider]\nbase_url=\"http://d/v1\"\nmodel=\"dm\"\n\
             [[provider.route]]\nname=\"r\"\nbase_url=\"u\"\nmodel=\"m\"\n",
        );
        let chain = c.chain().unwrap();
        assert_eq!(chain.source, ChainSource::Default);
        assert_eq!(chain.routes.len(), 1);
        assert_eq!(chain.routes[0].name, "default");
        let bare = parse("[provider]\nbase_url=\"http://d/v1\"\nmodel=\"dm\"\n");
        assert_eq!(bare.chain().unwrap().source, ChainSource::Default);
    }

    #[test]
    fn a_bare_config_still_says_what_is_wrong_with_provider() {
        let e = Config::default()
            .require_provider()
            .unwrap_err()
            .to_string();
        assert!(e.contains("provider.base_url is not set"), "{e}");
        assert!(e.contains("eclipse config init"), "{e}");
        let c = parse("[provider]\nbase_url=\"u\"\n");
        assert!(c
            .require_provider()
            .unwrap_err()
            .to_string()
            .contains("provider.model is not set"));
    }

    #[test]
    fn a_pin_selects_one_route_and_marks_the_chain_pinned() {
        let mut c = parse(TWO_ROUTES);
        c.pin_route(Some("big"), &env_of(&[])).unwrap();
        let chain = c.chain().unwrap();
        assert_eq!(chain.source, ChainSource::Pinned);
        assert_eq!(chain.routes.len(), 1);
        assert_eq!(chain.routes[0].name, "big");
    }

    #[test]
    fn an_unknown_pin_lists_the_routes_that_exist() {
        let mut c = parse(TWO_ROUTES);
        let e = c
            .pin_route(Some("nope"), &env_of(&[]))
            .unwrap_err()
            .to_string();
        assert!(e.contains("`nope`") && e.contains("local, big"), "{e}");
        let e = c
            .pin_route(Some(" "), &env_of(&[]))
            .unwrap_err()
            .to_string();
        assert!(e.contains("--route needs a route name"), "{e}");
    }

    #[test]
    fn eclipse_route_is_honoured_when_the_flag_is_absent_and_the_flag_wins() {
        let mut c = parse(TWO_ROUTES);
        c.pin_route(None, &env_of(&[("ECLIPSE_ROUTE", "big")]))
            .unwrap();
        assert_eq!(c.route_pin.as_deref(), Some("big"));
        c.pin_route(Some("local"), &env_of(&[("ECLIPSE_ROUTE", "big")]))
            .unwrap();
        assert_eq!(c.route_pin.as_deref(), Some("local"));
        let mut c = parse(TWO_ROUTES);
        c.dotenv
            .values
            .insert("ECLIPSE_ROUTE".into(), "local".into());
        c.pin_route(None, &env_of(&[])).unwrap();
        assert_eq!(
            c.route_pin.as_deref(),
            Some("local"),
            "the .env chain counts too"
        );
        let mut c = parse(TWO_ROUTES);
        c.pin_route(None, &env_of(&[])).unwrap();
        assert_eq!(c.route_pin, None);
    }

    #[test]
    fn a_route_takes_its_key_from_its_own_api_key_env_and_eclipse_api_key_is_default_only() {
        let mut c = parse(
            "[provider]\nbase_url=\"http://d/v1\"\nmodel=\"dm\"\n\
             [[provider.route]]\nname=\"r\"\nbase_url=\"u\"\nmodel=\"m\"\napi_key_env=\"R_KEY\"\n",
        );
        c.apply_env(&env_of(&[
            ("R_KEY", "from-r"),
            ("ECLIPSE_API_KEY", "for-default"),
        ]));
        assert_eq!(c.provider.api_key.as_deref(), Some("for-default"));
        assert_eq!(
            c.provider.route[0].config.api_key.as_deref(),
            Some("from-r")
        );

        let mut only_routes = parse(TWO_ROUTES);
        only_routes.apply_env(&env_of(&[("ECLIPSE_API_KEY", "stray")]));
        assert_eq!(
            only_routes.provider.api_key, None,
            "no phantom default route"
        );
        assert_eq!(only_routes.provider.route[0].config.api_key, None);
    }

    #[test]
    fn the_redacted_config_hides_every_routes_key_and_round_trips() {
        let c = parse(TWO_ROUTES);
        let t = c.to_toml_redacted().unwrap();
        assert!(!t.contains("hunter2"), "{t}");
        assert!(
            t.contains("[[provider.route]]") && t.contains("<redacted>"),
            "{t}"
        );
        let back = parse(&t);
        assert_eq!(back.provider.fallback, c.provider.fallback);
        assert_eq!(back.provider.route.len(), 2);
        assert_eq!(back.provider.route[1].config.timeout_secs, 30);
    }

    #[test]
    fn a_config_without_routes_prints_no_provider_route_keys() {
        // The table, not the letters: `[vision] route` is a key of its own, and a substring check
        // for the word would have made that a regression instead of a setting.
        let c = parse("[provider]\nbase_url=\"u\"\nmodel=\"m\"\n");
        let t = c.to_toml_redacted().unwrap();
        let parsed: toml::Value = toml::from_str(&t).unwrap();
        let provider = parsed.get("provider").expect("a provider table");
        for absent in ["route", "fallback", "aux", "delegate"] {
            assert!(
                provider.get(absent).is_none(),
                "`provider.{absent}` printed for a config with one route: {t}"
            );
        }
    }

    #[test]
    fn a_bad_route_table_is_refused_when_the_config_is_loaded() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("c.toml");
        std::fs::write(&path, "[provider]\nfallback = [\"ghost\"]\n").unwrap();
        let e = Config::load_with(Some(&path), &env_of(&[]))
            .unwrap_err()
            .to_string();
        assert!(e.contains("`ghost`"), "{e}");
    }

    #[test]
    fn context_policy_defaults_and_the_rail_it_derives() {
        let c = ContextPolicyConfig::default();
        assert!(
            c.judge,
            "the model half is the judgement pass, and it ships on: compile plus one bounded call"
        );
        assert_eq!(c.judge_timeout_secs, 20, "and it cannot hang the turn");
        assert_eq!(c.compact_at, 0.85);
        assert_eq!(c.protect_last_n, 20, "the tail keeps twenty turns");
        assert_eq!(c.window_tokens, 0, "no window is invented");
        assert_eq!(c.budget_for(0), 0, "no window, no rail");
        assert_eq!(c.budget_for(327_680), 278_528);
        let off = ContextPolicyConfig {
            compact_at: 0.0,
            ..c.clone()
        };
        assert_eq!(off.budget_for(327_680), 0, "compact_at = 0 is off");
        let half = ContextPolicyConfig {
            compact_at: 0.5,
            ..c
        };
        assert_eq!(half.budget_for(131_072), 65_536);
    }

    #[test]
    fn a_compact_at_outside_the_window_is_a_config_error_naming_the_key() {
        for bad in ["1.5", "-0.2"] {
            let c = parse(&format!("[context]\ncompact_at = {bad}\n"));
            let err = c.context.validate().unwrap_err().to_string();
            assert!(
                err.contains("context.compact_at"),
                "{bad} must be named in the error: {err}"
            );
        }
        assert!(parse("[context]\ncompact_at = 0.6\n")
            .context
            .validate()
            .is_ok());
        assert!(parse("[context]\ncompact_at = 0\n")
            .context
            .validate()
            .is_ok());
    }
}

#[cfg(test)]
mod mcp_editor_tests {
    use super::*;
    use crate::mcp::Spec;

    fn spec(text: &str) -> Spec {
        toml::from_str(text).unwrap()
    }

    fn add(spec: &Spec) -> String {
        let out = mcp_add(CONFIG, spec).unwrap();
        // Every writer proves itself the same way: the file it returns loads.
        parse_text(&out).unwrap();
        out
    }

    const CONFIG: &str = r#"# my config
[provider]
base_url = "http://127.0.0.1:8081/v1"
model = "m"

# this comment belongs to the first entry
[[mcp]]
name = "first"
command = "one"

# and this one to the second
[[mcp]]
name = "second"
command = "two"
policy = "allow"
"#;

    #[test]
    fn an_added_entry_reads_back_and_leaves_the_comments_alone() {
        let out = add(&spec(
            "name = \"third\"\ncommand = \"three\"\nargs = [\"--x\"]\nprefix = \"t_\"\n",
        ));
        let cfg = parse_text(&out).unwrap();
        assert_eq!(
            cfg.mcp.iter().map(|s| s.name.as_str()).collect::<Vec<_>>(),
            ["first", "second", "third"]
        );
        let third = cfg.mcp.iter().find(|s| s.name == "third").unwrap();
        assert_eq!(third.args, ["--x"]);
        assert_eq!(third.prefix, "t_");
        // The two hand-written entries and both comments are untouched, byte for byte.
        for line in [
            "# my config",
            "# this comment belongs to the first entry",
            "# and this one to the second",
        ] {
            assert!(out.contains(line), "lost {line:?}:\n{out}");
        }
        assert!(
            out.contains("[[mcp]]\nname = \"first\"\ncommand = \"one\""),
            "{out}"
        );
        assert!(
            !out.contains("args = []"),
            "only what was set is written:\n{out}"
        );
    }

    #[test]
    fn a_duplicate_name_is_refused_and_named_by_line() {
        let err = mcp_add(CONFIG, &spec("name = \"first\"\ncommand = \"again\"")).unwrap_err();
        assert!(err.contains("already declared at line 7"), "{err}");
    }

    #[test]
    fn an_unusable_entry_is_refused_before_anything_is_written() {
        // http with a command: `Spec::validate`'s own refusal, wrapped in the writer's voice.
        let err = mcp_add(
            CONFIG,
            &spec("name = \"bad\"\ntransport = \"http\"\ncommand = \"x\"\nurl = \"http://h/mcp\""),
        )
        .unwrap_err();
        assert!(err.starts_with("that entry is not usable"), "{err}");
        assert!(err.contains("belong to the stdio transport"), "{err}");
    }

    #[test]
    fn remove_takes_the_named_block_and_the_blank_line_after_it() {
        let out = mcp_remove(CONFIG, "first").unwrap();
        let cfg = parse_text(&out).unwrap();
        assert_eq!(
            cfg.mcp.iter().map(|s| s.name.as_str()).collect::<Vec<_>>(),
            ["second"]
        );
        // The second entry's comment stays with the second entry.
        assert!(out.contains("# and this one to the second"), "{out}");
        assert!(!out.contains("name = \"first\""), "{out}");
        assert!(!out.contains("\n\n\n"), "no hole left behind:\n{out}");
    }

    #[test]
    fn remove_says_what_the_file_does_declare() {
        let err = mcp_remove(CONFIG, "nope").unwrap_err();
        assert!(err.contains("declares first, second"), "{err}");
        let bare = "[provider]\nbase_url = \"http://d/v1\"\nmodel = \"m\"\n";
        let err = mcp_remove(bare, "nope").unwrap_err();
        assert!(err.contains("no `[[mcp]]` entry for `nope`"), "{err}");
    }

    #[test]
    fn disable_flips_the_line_inside_its_own_block() {
        let off = mcp_set_disabled(CONFIG, "second", true).unwrap();
        let cfg = parse_text(&off).unwrap();
        assert!(
            cfg.mcp
                .iter()
                .find(|s| s.name == "second")
                .unwrap()
                .disabled
        );
        assert!(!cfg.mcp.iter().find(|s| s.name == "first").unwrap().disabled);
        // Written into the block that already exists, not appended to the file.
        let second_at = off.find("name = \"second\"").unwrap();
        let tail = &off[second_at..];
        assert!(tail.contains("disabled = true"), "{off}");
        assert!(tail.find("disabled").unwrap() < tail.find("\n[[").unwrap_or(tail.len()));

        let on = mcp_set_disabled(&off, "second", false).unwrap();
        let cfg = parse_text(&on).unwrap();
        assert!(
            !cfg.mcp
                .iter()
                .find(|s| s.name == "second")
                .unwrap()
                .disabled
        );
        assert!(
            on.contains("disabled = false"),
            "said out loud, not deleted:\n{on}"
        );
    }

    #[test]
    fn disable_on_an_entry_without_the_key_inserts_one() {
        let off = mcp_set_disabled(CONFIG, "first", true).unwrap();
        assert!(off.contains("command = \"one\"\ndisabled = true"), "{off}");
        assert!(parse_text(&off).unwrap().mcp[0].disabled);
    }

    /// `#517`: an edit is a line-level splice inside one block. The neighbours — and this entry's
    /// own comments and ordering — round trip byte for byte; only the lines whose value changed
    /// move, which is the whole reason this is not a remove followed by an add.
    #[test]
    fn an_edit_changes_the_changed_line_and_leaves_every_other_byte_alone() {
        let out = mcp_update(CONFIG, "second", |entry| entry.prefix = "t_".into()).unwrap();
        parse_text(&out).unwrap();
        assert_eq!(
            out,
            CONFIG.replace(
                "command = \"two\"\npolicy = \"allow\"",
                "command = \"two\"\npolicy = \"allow\"\nprefix = \"t_\""
            ),
            "one added line, and not one other character moved:\n{out}"
        );
    }

    /// A field set back to its default loses its line rather than gaining a default one, and a
    /// new one is appended in the renderer's order — again, nothing else moves.
    #[test]
    fn an_edit_sets_and_clears_token_env_without_touching_the_rest() {
        let on = mcp_update(CONFIG, "second", |entry| {
            entry.token_env = Some("HA_TOKEN".into())
        })
        .unwrap();
        assert_eq!(
            on,
            CONFIG.replace(
                "command = \"two\"\npolicy = \"allow\"",
                "command = \"two\"\npolicy = \"allow\"\ntoken_env = \"HA_TOKEN\""
            ),
            "{on}"
        );
        let off = mcp_update(&on, "second", |entry| entry.token_env = None).unwrap();
        assert_eq!(
            off, CONFIG,
            "clearing a field removes its line and nothing else"
        );
    }

    /// A comment written *inside* a block belongs to that block, so it survives an edit to a
    /// neighbouring line of the same entry.
    #[test]
    fn an_edit_keeps_a_comment_written_inside_the_block() {
        let inner = "[[mcp]]\nname = \"a\"\n# the endpoint is on the box\ncommand = \"x\"\n";
        let out = mcp_update(inner, "a", |entry| {
            entry.args = vec!["--y".into()];
        })
        .unwrap();
        assert_eq!(
            out,
            "[[mcp]]\nname = \"a\"\n# the endpoint is on the box\ncommand = \"x\"\n\
             args = [\"--y\"]\n",
            "{out}"
        );
    }

    /// A rename is a remove and an add, and the writer says so rather than doing half of one.
    #[test]
    fn an_edit_refuses_a_rename_and_names_what_the_file_declares() {
        let err = mcp_update(CONFIG, "second", |entry| entry.name = "renamed".into()).unwrap_err();
        assert!(err.contains("an edit does not rename"), "{err}");

        let err = mcp_update(CONFIG, "nope", |_| {}).unwrap_err();
        assert!(err.contains("declares first, second"), "{err}");

        // And an unusable result is the validator's sentence, before anything is written.
        let err = mcp_update(CONFIG, "second", |entry| {
            entry.transport = crate::mcp::Transport::Http;
            entry.url = Some("http://h/mcp".into());
        })
        .unwrap_err();
        assert!(err.starts_with("that entry is not usable"), "{err}");
        assert!(err.contains("belong to the stdio transport"), "{err}");
    }

    #[test]
    fn an_empty_file_gets_its_first_entry_cleanly() {
        let out = mcp_add("", &spec("name = \"only\"\ncommand = \"x\"")).unwrap();
        assert!(out.starts_with("[[mcp]]\n"), "{out:?}");
        assert_eq!(parse_text(&out).unwrap().mcp[0].name, "only");
    }

    #[test]
    fn a_second_entry_is_separated_by_exactly_one_blank_line() {
        let out = add(&spec("name = \"third\"\ncommand = \"three\""));
        assert!(!out.contains("\n\n\n"), "{out}");
        assert!(
            out.contains("policy = \"allow\"\n\n[[mcp]]\nname = \"third\""),
            "{out}"
        );
    }
}