eclipse-cli 0.13.3

Command-line interface for eclipse
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
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
use std::io::{Read, Write};
use std::process::{Command, Output, Stdio};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{mpsc, Arc};
use std::time::Duration;

fn run(home: &std::path::Path, args: &[&str]) -> Output {
    Command::new(env!("CARGO_BIN_EXE_eclipse"))
        .args(args)
        .env_clear()
        .env("HOME", home)
        .env("NO_COLOR", "1")
        .output()
        .unwrap()
}

fn stdout(o: &Output) -> String {
    String::from_utf8_lossy(&o.stdout).into_owned()
}

#[test]
fn config_init_then_sessions_list_in_fresh_home() {
    let home = tempfile::tempdir().unwrap();
    let out = run(home.path(), &["config", "init"]);
    assert!(out.status.success(), "{out:?}");
    let cfg = home.path().join(".eclipse/config.toml");
    assert!(cfg.exists());

    let again = run(home.path(), &["config", "init"]);
    assert!(!again.status.success());
    assert!(run(home.path(), &["config", "init", "--force"])
        .status
        .success());

    let list = run(home.path(), &["sessions", "list"]);
    assert!(list.status.success());
    assert!(stdout(&list).contains("no sessions"));
}

#[test]
fn config_init_stores_a_random_dashboard_token_and_never_prints_it() {
    let home = tempfile::tempdir().unwrap();
    let cfg = home.path().join(".eclipse/config.toml");
    let dotenv = home.path().join(".eclipse/.env");
    // The token is a secret, so it lives in .env; the config only refers to it.
    let token_of = || {
        std::fs::read_to_string(&dotenv)
            .unwrap()
            .lines()
            .find_map(|l| {
                l.strip_prefix("ECLIPSE_WEB_AUTH_TOKEN=")
                    .map(str::to_string)
            })
            .expect("the token is written to .env")
    };

    let out = run(home.path(), &["config", "init"]);
    assert!(out.status.success(), "{out:?}");
    let first = token_of();
    assert_eq!(first.len(), 64);
    assert!(first.bytes().all(|b| b.is_ascii_hexdigit()));
    assert!(
        std::fs::read_to_string(&cfg)
            .unwrap()
            .contains("${ECLIPSE_WEB_AUTH_TOKEN:-}"),
        "the config refers to the variable rather than carrying the value, and gives it an \
         empty default so a missing .env is not a load error"
    );
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        for f in [&cfg, &dotenv] {
            assert_eq!(f.metadata().unwrap().permissions().mode() & 0o777, 0o600);
        }
    }

    let shown = run(home.path(), &["config", "show"]);
    assert!(shown.status.success(), "{shown:?}");
    for o in [&out, &shown] {
        for stream in [&o.stdout, &o.stderr] {
            assert!(!String::from_utf8_lossy(stream).contains(&first));
        }
    }

    let forced = run(home.path(), &["config", "init", "--force"]);
    assert!(forced.status.success());
    // `--force` replaces the config; it never touches .env, because that file holds the
    // user's secrets and consent to rewrite a config is not consent to lose them.
    assert_eq!(token_of(), first, "the secret survives --force");
    assert!(String::from_utf8_lossy(&forced.stdout).contains(".env"));
    for stream in [&forced.stdout, &forced.stderr] {
        assert!(!String::from_utf8_lossy(stream).contains(&first));
    }
}

#[test]
fn sessions_list_shows_stored_sessions() {
    let home = tempfile::tempdir().unwrap();
    let dir = home.path().join(".eclipse/state/sessions");
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(
        dir.join("abc.jsonl"),
        "{\"ts\":0,\"message\":{\"role\":\"user\",\"content\":\"hello there\"}}\n",
    )
    .unwrap();
    let out = stdout(&run(home.path(), &["sessions", "list"]));
    assert!(out.contains("abc") && out.contains("hello there"), "{out}");
    let shown = stdout(&run(home.path(), &["sessions", "show", "abc"]));
    assert!(shown.contains("user: hello there"), "{shown}");
}

#[test]
fn run_without_provider_config_fails_helpfully() {
    let home = tempfile::tempdir().unwrap();
    let out = run(home.path(), &["run", "hi"]);
    assert!(!out.status.success());
    assert!(String::from_utf8_lossy(&out.stderr).contains("base_url"));
}
/// `config check` exists because a key nothing reads is invisible: `api_key` under `[web]` loaded
/// cleanly, sent no key, and cost an afternoon. It reports, it does not refuse — a profile overlay
/// may carry a key this build does not know yet — and `--strict` is the exit code for a script.
#[test]
fn config_check_names_a_key_nothing_reads_and_strict_makes_it_fail() {
    let home = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(home.path().join(".eclipse")).unwrap();
    let cfg = home.path().join(".eclipse").join("config.toml");
    std::fs::write(
        &cfg,
        "[provider]\nbase_url = \"http://127.0.0.1:1/v1\"\nmodel = \"m\"\n\
         stream = false\n\n[tools]\nworkspace_root = \"/tmp\"\nbogus_setting = 5\n\n\
         [web]\napi_key = \"sk-not-a-real-key\"\n",
    )
    .unwrap();

    let out = run(home.path(), &["config", "check"]);
    assert!(out.status.success(), "a warning is not a failure: {out:?}");
    let text = stdout(&out);
    assert!(text.contains("[tools], `bogus_setting`"), "{text}");
    // The M1 shape: the key is real, it is just in the wrong table, and the report says where it
    // belongs rather than only that it does nothing.
    assert!(text.contains("[web], `api_key`"), "{text}");
    assert!(text.contains("read under [provider]"), "{text}");
    assert!(
        !text.contains("workspace_root"),
        "a real key was reported: {text}"
    );
    assert!(!text.contains("stream"), "a real key was reported: {text}");

    let strict = run(home.path(), &["config", "check", "--strict"]);
    assert_eq!(strict.status.code(), Some(1), "{strict:?}");

    let json = run(home.path(), &["config", "check", "--json"]);
    let rows: serde_json::Value = serde_json::from_str(&stdout(&json)).unwrap();
    let found: Vec<&str> = rows
        .as_array()
        .unwrap()
        .iter()
        .map(|r| r["key"].as_str().unwrap())
        .collect();
    assert_eq!(found, ["bogus_setting", "api_key"], "{rows}");

    // A config whose keys are all read says so, and `--strict` is quiet about it.
    std::fs::write(
        &cfg,
        "[provider]\nmodel = \"m\"\n[tools]\nworkspace_root = \"/tmp\"\n",
    )
    .unwrap();
    let clean = run(home.path(), &["config", "check", "--strict"]);
    assert!(clean.status.success(), "{clean:?}");
    assert!(
        stdout(&clean).contains("every key is read"),
        "{:?}",
        stdout(&clean)
    );
}

/// The overlay is a file too, and it is the file a profile's typo is in.
#[test]
fn config_check_reads_the_profile_overlay_as_well_as_the_base() {
    let home = tempfile::tempdir().unwrap();
    let overlay = home.path().join(".eclipse").join("profiles").join("work");
    std::fs::create_dir_all(&overlay).unwrap();
    std::fs::write(
        home.path().join(".eclipse").join("config.toml"),
        "[provider]\nmodel = \"m\"\n[agent]\nmax_iterations = 4\n",
    )
    .unwrap();
    std::fs::write(overlay.join("config.toml"), "[agent]\nmax_iteration = 9\n").unwrap();

    let out = run(home.path(), &["config", "check", "--profile", "work"]);
    let text = stdout(&out);
    assert!(text.contains("profiles/work/config.toml"), "{text}");
    assert!(text.contains("[agent], `max_iteration`"), "{text}");
    // The base file is clean, so it contributes nothing; the count is of what was found, not of
    // files read.
    assert!(
        text.contains("1 key(s) nothing reads in 2 file(s)"),
        "{text}"
    );
}

/// The CLI must print streamed text as it arrives, not after the reply is complete:
/// the mock server withholds the end of the stream until the first words showed up.
#[test]
fn run_prints_streamed_reply_incrementally() {
    let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
    let base = format!("http://{}/v1", listener.local_addr().unwrap());
    let (release, released) = mpsc::channel::<()>();
    let server = std::thread::spawn(move || {
        let (mut s, _) = listener.accept().unwrap();
        let mut req = Vec::new();
        let mut chunk = [0u8; 4096];
        // Read the whole request, not just up to the flag: a request larger than one read left
        // unread bytes behind, and closing over them resets the connection.
        loop {
            let text = String::from_utf8_lossy(&req).into_owned();
            if let Some((head, body)) = text.split_once("\r\n\r\n") {
                let want: usize = head
                    .to_ascii_lowercase()
                    .lines()
                    .find_map(|l| l.strip_prefix("content-length:").map(str::to_string))
                    .and_then(|v| v.trim().parse().ok())
                    .unwrap_or(0);
                if body.len() >= want && text.contains("\"stream\":true") {
                    break;
                }
            }
            let n = s.read(&mut chunk).unwrap();
            assert!(n > 0, "client closed before sending a streaming request");
            req.extend_from_slice(&chunk[..n]);
        }
        s.write_all(
            b"HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\nconnection: close\r\n\r\n",
        )
        .unwrap();
        s.write_all(b"data: {\"choices\":[{\"delta\":{\"content\":\"Hello\"}}]}\n\n")
            .unwrap();
        s.flush().unwrap();
        let _ = released.recv_timeout(Duration::from_secs(10));
        s.write_all(
            b"data: {\"choices\":[{\"delta\":{\"content\":\" world\"},\"finish_reason\":\"stop\"}]}\n\ndata: [DONE]\n\n",
        )
        .unwrap();
    });

    let home = tempfile::tempdir().unwrap();
    let mut child = Command::new(env!("CARGO_BIN_EXE_eclipse"))
        .args(["run", "hi"])
        .env_clear()
        .env("HOME", home.path())
        .env("NO_COLOR", "1")
        .env("ECLIPSE_BASE_URL", &base)
        .env("ECLIPSE_MODEL", "m")
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();
    let mut stdout = child.stdout.take().unwrap();
    let (tx, rx) = mpsc::channel::<Vec<u8>>();
    let reader = std::thread::spawn(move || {
        let mut buf = [0u8; 256];
        while let Ok(n) = stdout.read(&mut buf) {
            if n == 0 || tx.send(buf[..n].to_vec()).is_err() {
                break;
            }
        }
    });

    let mut seen = Vec::new();
    while !String::from_utf8_lossy(&seen).contains("Hello") {
        let part = rx
            .recv_timeout(Duration::from_secs(5))
            .expect("first streamed words were not printed while the reply was still running");
        seen.extend(part);
    }
    release.send(()).unwrap();
    let status = child.wait().unwrap();
    reader.join().unwrap();
    server.join().unwrap();
    for part in rx.try_iter() {
        seen.extend(part);
    }
    assert!(status.success());
    assert_eq!(String::from_utf8_lossy(&seen), "Hello world\n");
}

fn seed_session(home: &std::path::Path, id: &str) -> std::path::PathBuf {
    seed_session_at(home, id, 1709210096000)
}

/// The same four records, stamped from `base_ts`: a test that needs one session to be *older*
/// than another cannot rely on file mtimes, because the imported rows carry the record's own
/// timestamp and the fixed seed gives every session the same one.
fn seed_session_at(home: &std::path::Path, id: &str, base_ts: u64) -> std::path::PathBuf {
    let dir = home.join(".eclipse/state/sessions");
    std::fs::create_dir_all(&dir).unwrap();
    let lines = [
        format!(r#"{{"ts":{base_ts},"message":{{"role":"user","content":"what is in a.txt?"}}}}"#),
        format!(
            r#"{{"ts":{},"message":{{"role":"assistant","content":null,"tool_calls":[{{"id":"c1","type":"function","function":{{"name":"read_file","arguments":"{{\"path\":\"a.txt\"}}"}}}}]}}}}"#,
            base_ts + 1000
        ),
        format!(
            r#"{{"ts":{},"message":{{"role":"tool","content":"hello from a.txt","tool_call_id":"c1"}}}}"#,
            base_ts + 2000
        ),
        format!(
            r#"{{"ts":{},"message":{{"role":"assistant","content":"It says hello."}}}}"#,
            base_ts + 3000
        ),
    ];
    std::fs::write(dir.join(format!("{id}.jsonl")), lines.join("\n") + "\n").unwrap();
    dir
}

#[test]
fn sessions_rename_changes_the_listing_and_delete_removes_it() {
    let home = tempfile::tempdir().unwrap();
    let dir = seed_session(home.path(), "abc");
    seed_session(home.path(), "keep");

    let out = run(home.path(), &["sessions", "rename", "abc", "Reading files"]);
    assert!(out.status.success(), "{out:?}");
    let list = stdout(&run(home.path(), &["sessions", "list"]));
    assert!(list.contains("Reading files"), "{list}");
    assert!(
        list.contains("what is in a.txt?"),
        "the other session keeps its preview"
    );

    for bad in [
        &["sessions", "rename", "abc", "   "][..],
        &["sessions", "rename", "nope", "t"][..],
        &["sessions", "rename", "../abc", "t"][..],
    ] {
        let o = run(home.path(), bad);
        assert!(!o.status.success(), "{bad:?}");
    }

    let out = run(home.path(), &["sessions", "delete", "abc"]);
    assert!(out.status.success(), "{out:?}");
    assert!(!dir.join("abc.jsonl").exists() && !dir.join("abc.meta.json").exists());
    assert!(dir.join("keep.jsonl").exists());
    let again = run(home.path(), &["sessions", "delete", "abc"]);
    assert!(!again.status.success());
    assert!(String::from_utf8_lossy(&again.stderr).contains("no such session"));
    assert!(!run(home.path(), &["sessions", "delete", "../keep"])
        .status
        .success());
    assert!(dir.join("keep.jsonl").exists());
}

#[test]
fn sessions_pin_puts_a_session_first_and_out_of_a_prune_s_reach() {
    let home = tempfile::tempdir().unwrap();
    seed_session_at(home.path(), "old", 1_700_000_000_000);
    seed_session_at(home.path(), "new", 1_700_000_100_000);

    let out = run(home.path(), &["sessions", "pin", "old"]);
    assert!(out.status.success(), "{out:?}");
    let list = stdout(&run(home.path(), &["sessions", "list"]));
    let first = list.lines().next().unwrap_or_default();
    assert!(
        first.contains("old") && first.contains('\u{2605}'),
        "pinned first, and marked: {list}"
    );
    assert!(
        list.lines().nth(1).unwrap_or_default().contains("new"),
        "{list}"
    );

    // `keep the newest one` ranks by activity, and the pinned one is the older of the two: it
    // matches the policy, holds its slot, and is not deleted.
    let pruned = run(
        home.path(),
        &["sessions", "prune", "--keep-count", "1", "--force"],
    );
    assert!(pruned.status.success(), "{pruned:?}");
    let said = stdout(&pruned);
    assert!(said.contains("pruned 0 session(s)"), "{said}");
    assert!(
        said.contains("1 pinned session(s) were out of reach"),
        "{said}"
    );
    assert!(stdout(&run(home.path(), &["sessions", "list"])).contains("old"));

    // Unpinned, the same rule takes it.
    assert!(run(home.path(), &["sessions", "unpin", "old"])
        .status
        .success());
    let pruned = run(
        home.path(),
        &["sessions", "prune", "--keep-count", "1", "--force"],
    );
    assert!(pruned.status.success(), "{pruned:?}");
    let list = stdout(&run(home.path(), &["sessions", "list"]));
    assert!(!list.contains("old"), "{list}");
    assert!(list.contains("new"), "{list}");

    // A pin on a session that is not there is an error, not a new row.
    let bad = run(home.path(), &["sessions", "pin", "nope"]);
    assert!(!bad.status.success());
    assert!(String::from_utf8_lossy(&bad.stderr).contains("no such session"));
}

/// `#240` end to end: the archive verb, the listing that hides it, the flag that shows it, and a
/// prune that leaves it alone and names the flag that would not.
#[test]
fn sessions_archive_files_a_session_away_from_the_list_and_out_of_a_prune() {
    let home = tempfile::tempdir().unwrap();
    seed_session_at(home.path(), "old", 1_700_000_000_000);
    seed_session_at(home.path(), "new", 1_700_000_100_000);

    let out = run(home.path(), &["sessions", "archive", "old"]);
    assert!(out.status.success(), "{out:?}");
    let said = stdout(&out);
    assert!(said.contains("archived session old"), "{said}");
    assert!(said.contains("still in `sessions search`"), "{said}");

    // Out of the default listing...
    let list = stdout(&run(home.path(), &["sessions", "list"]));
    assert!(!list.contains("old"), "{list}");
    assert!(list.contains("new"), "{list}");

    // ...and back under the flag, marked.
    let list = stdout(&run(home.path(), &["sessions", "list", "--archived"]));
    assert!(
        list.lines()
            .any(|l| l.contains("old") && l.contains("archived")),
        "marked as filed away: {list}"
    );

    // Still found by name and by what was said, and the transcript still opens.
    assert!(stdout(&run(home.path(), &["sessions", "search", "old"])).contains("old"));
    let shown = run(home.path(), &["sessions", "show", "old"]);
    assert!(shown.status.success(), "{shown:?}");
    assert!(
        stdout(&shown).contains("hello from a.txt"),
        "an archived transcript is still readable"
    );

    // The count rule would take it on activity alone; the flag keeps it and names `--archived`.
    let pruned = run(
        home.path(),
        &["sessions", "prune", "--keep-count", "1", "--force"],
    );
    assert!(pruned.status.success(), "{pruned:?}");
    let said = stdout(&pruned);
    assert!(said.contains("pruned 0 session(s)"), "{said}");
    assert!(
        said.contains("1 archived session(s) were left alone") && said.contains("--archived"),
        "{said}"
    );

    // Asked for explicitly, the same prune takes it.
    let pruned = run(
        home.path(),
        &[
            "sessions",
            "prune",
            "--keep-count",
            "1",
            "--archived",
            "--force",
        ],
    );
    assert!(pruned.status.success(), "{pruned:?}");
    assert!(stdout(&pruned).contains("pruned 1 session(s)"));

    // And unarchive puts a row back where the list can see it.
    assert!(run(home.path(), &["sessions", "archive", "new"])
        .status
        .success());
    assert!(!stdout(&run(home.path(), &["sessions", "list"])).contains("new"));
    let out = run(home.path(), &["sessions", "unarchive", "new"]);
    assert!(out.status.success(), "{out:?}");
    assert!(stdout(&run(home.path(), &["sessions", "list"])).contains("new"));

    // A word that is not there is the store's refusal, not a new row.
    let bad = run(home.path(), &["sessions", "archive", "nope"]);
    assert!(!bad.status.success());
    assert!(String::from_utf8_lossy(&bad.stderr).contains("no such session"));
}

#[test]
fn sessions_export_writes_full_json_and_markdown_transcripts() {
    let home = tempfile::tempdir().unwrap();
    seed_session(home.path(), "abc");
    run(home.path(), &["sessions", "rename", "abc", "Reading files"]);
    let out_dir = tempfile::tempdir().unwrap();

    let json_path = out_dir.path().join("t.json");
    let out = run(
        home.path(),
        &["sessions", "export", "abc", json_path.to_str().unwrap()],
    );
    assert!(out.status.success(), "{out:?}");
    let v: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(&json_path).unwrap()).unwrap();
    assert_eq!(v["title"], "Reading files");
    let msgs = v["messages"].as_array().unwrap();
    assert_eq!(msgs.len(), 4);
    assert_eq!(
        msgs[1]["message"]["tool_calls"][0]["function"]["name"],
        "read_file"
    );
    assert_eq!(msgs[2]["message"]["content"], "hello from a.txt");
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        assert_eq!(
            json_path.metadata().unwrap().permissions().mode() & 0o777,
            0o600
        );
    }

    let md_path = out_dir.path().join("t.md");
    let out = run(
        home.path(),
        &[
            "sessions",
            "export",
            "abc",
            "--format",
            "markdown",
            md_path.to_str().unwrap(),
        ],
    );
    assert!(out.status.success(), "{out:?}");
    let md = std::fs::read_to_string(&md_path).unwrap();
    for needle in [
        "# Reading files",
        "what is in a.txt?",
        "**Tool call** `read_file` (id `c1`)",
        "\"path\": \"a.txt\"",
        "Tool result: read_file",
        "hello from a.txt",
        "It says hello.",
        "2024-02-29 12:34 UTC",
    ] {
        assert!(md.contains(needle), "missing {needle:?} in\n{md}");
    }

    // No silent overwrite; --force replaces; unknown ids and formats fail.
    let args = ["sessions", "export", "abc", md_path.to_str().unwrap()];
    let again = run(home.path(), &args);
    assert!(!again.status.success());
    assert!(String::from_utf8_lossy(&again.stderr).contains("--force"));
    assert!(std::fs::read_to_string(&md_path)
        .unwrap()
        .contains("# Reading files"));
    let forced = run(
        home.path(),
        &[
            "sessions",
            "export",
            "abc",
            "--force",
            md_path.to_str().unwrap(),
        ],
    );
    assert!(forced.status.success());
    assert!(std::fs::read_to_string(&md_path)
        .unwrap()
        .trim_start()
        .starts_with('{'));
    let missing = out_dir.path().join("m.json");
    assert!(!run(
        home.path(),
        &["sessions", "export", "nope", missing.to_str().unwrap()]
    )
    .status
    .success());
    assert!(!missing.exists(), "a failed export leaves no file");
    assert!(!run(
        home.path(),
        &[
            "sessions",
            "export",
            "abc",
            "--format",
            "xml",
            missing.to_str().unwrap()
        ]
    )
    .status
    .success());
}

fn seed_aged_session(dir: &std::path::Path, id: &str, ts: u64) {
    let line = format!(r#"{{"ts":{ts},"message":{{"role":"user","content":"q {id}"}}}}"#);
    std::fs::write(dir.join(format!("{id}.jsonl")), line + "\n").unwrap();
}

#[test]
fn sessions_show_labels_memory_and_delete_and_prune_remove_it() {
    let home = tempfile::tempdir().unwrap();
    let dir = seed_session(home.path(), "abc");
    seed_session(home.path(), "keep");
    let memory = r###"{"version":3,"handoff":{"text":"## Session Log\n[#0] user reads a.txt\u001b[2J","version":"2.0.0","covered_turns":2,"covered_messages":4,"generated_at_ms":1709210099000}}"###;
    std::fs::write(dir.join("abc.memory.json"), memory).unwrap();
    // Written before the store first opens, so it is part of the import: a record with nothing
    // in it is stored but must never be used.
    std::fs::write(dir.join("keep.memory.json"), r#"{"version":3}"#).unwrap();
    let shown = stdout(&run(home.path(), &["sessions", "show", "abc"]));
    assert!(
        shown.contains("user: what is in a.txt?")
            && shown.contains("compiled handoff (deterministic compile;")
            && shown.contains("2 turn(s), 4 message(s)")
            && shown.contains("user reads a.txt"),
        "{shown}"
    );
    assert!(!shown.contains('\x1b'), "memory text is escaped");
    assert!(stdout(&run(home.path(), &["sessions", "list"])).contains("abc"));

    let out = run(home.path(), &["sessions", "show", "keep"]);
    assert!(out.status.success());
    assert!(String::from_utf8_lossy(&out.stderr).contains("invalid and is ignored"));

    let out = run(home.path(), &["sessions", "delete", "abc"]);
    assert!(out.status.success(), "{out:?}");
    assert!(!dir.join("abc.jsonl").exists() && !dir.join("abc.memory.json").exists());
    assert!(dir.join("keep.memory.json").exists());
}

#[test]
fn sessions_prune_by_age_count_and_config_defaults() {
    let home = tempfile::tempdir().unwrap();
    let dir = home.path().join(".eclipse/state/sessions");
    std::fs::create_dir_all(&dir).unwrap();
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_millis() as u64;
    seed_aged_session(&dir, "recent", now);
    seed_aged_session(&dir, "recent2", now - 1000);
    seed_aged_session(&dir, "old", 1_000);
    run(home.path(), &["sessions", "rename", "old", "Old title"]);
    assert!(
        stdout(&run(home.path(), &["sessions", "list"])).contains("Old title"),
        "the title is stored with the session, not in a sidecar"
    );
    std::fs::write(
        dir.join("old.memory.json"),
        r#"{"summary":"m","covered_turns":1,"covered_messages":2,"generated_at_ms":1}"#,
    )
    .unwrap();

    // No limits anywhere: refuses instead of deleting anything.
    let none = run(home.path(), &["sessions", "prune"]);
    assert!(!none.status.success());
    assert!(String::from_utf8_lossy(&none.stderr).contains("nothing to prune"));
    assert!(dir.join("old.jsonl").exists());

    let out = run(home.path(), &["sessions", "prune", "--keep-days", "30"]);
    assert!(out.status.success(), "{out:?}");
    assert!(
        stdout(&out).contains("pruned 1 session"),
        "{}",
        stdout(&out)
    );
    assert!(!dir.join("old.jsonl").exists() && !dir.join("old.meta.json").exists());
    assert!(!dir.join("old.memory.json").exists());
    assert!(dir.join("recent.jsonl").exists());

    // Limits can come from the config file.
    let cfg = home.path().join("c.toml");
    std::fs::write(&cfg, "[sessions]\nretention_keep_count = 1\n").unwrap();
    let out = run(
        home.path(),
        &["--config", cfg.to_str().unwrap(), "sessions", "prune"],
    );
    assert!(out.status.success(), "{out:?}");
    assert!(stdout(&out).contains("pruned 1 session"));
    let left = stdout(&run(home.path(), &["sessions", "list"]));
    assert!(
        left.contains("recent") && !left.contains("recent2"),
        "{left}"
    );
    assert!(
        !dir.join("old.jsonl").exists(),
        "the imported source is removed with the session, so it cannot be re-imported"
    );
}

#[test]
fn sessions_prune_needs_force_above_ten_sessions() {
    let home = tempfile::tempdir().unwrap();
    let dir = home.path().join(".eclipse/state/sessions");
    std::fs::create_dir_all(&dir).unwrap();
    for i in 0..12 {
        seed_aged_session(&dir, &format!("s{i}"), 1_000 + i);
    }
    let refused = run(home.path(), &["sessions", "prune", "--keep-count", "1"]);
    assert!(!refused.status.success());
    assert!(String::from_utf8_lossy(&refused.stderr).contains("--force"));
    assert_eq!(count_sessions(home.path()), 12);

    // Exactly ten is allowed without --force.
    let ten = run(home.path(), &["sessions", "prune", "--keep-count", "2"]);
    assert!(ten.status.success(), "{ten:?}");
    assert!(stdout(&ten).contains("pruned 10 session"));

    for i in 12..24 {
        seed_aged_session(&dir, &format!("s{i}"), 1_000 + i);
    }
    let forced = run(
        home.path(),
        &["sessions", "prune", "--keep-count", "1", "--force"],
    );
    assert!(forced.status.success(), "{forced:?}");
    assert!(
        stdout(&forced).contains("pruned 13 session"),
        "{}",
        stdout(&forced)
    );
    assert_eq!(count_sessions(home.path()), 1);
}

/// Without a TTY the REPL reads plain lines from stdin and neither needs nor writes a
/// history file.
#[test]
fn repl_without_a_tty_reads_plain_lines_and_writes_no_history() {
    let home = tempfile::tempdir().unwrap();
    let mut child = Command::new(env!("CARGO_BIN_EXE_eclipse"))
        .env_clear()
        .env("HOME", home.path())
        .env("NO_COLOR", "1")
        .env("ECLIPSE_BASE_URL", "http://127.0.0.1:9/v1")
        .env("ECLIPSE_MODEL", "m")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();
    child
        .stdin
        .take()
        .unwrap()
        .write_all(b"/id\n/bogus\n\n/help\n/exit\nignored after exit\n")
        .unwrap();
    let out = child.wait_with_output().unwrap();
    assert!(out.status.success(), "{out:?}");
    let text = String::from_utf8_lossy(&out.stdout);
    assert!(text.contains("you> "), "{text}");
    assert!(
        text.contains("(none yet)") && text.contains("unknown command"),
        "{text}"
    );
    for expected in ["/new", "/id", "/status", "/exit", "start a new session"] {
        assert!(
            text.contains(expected),
            "help should mention {expected}: {text}"
        );
    }
    assert!(!home.path().join(".eclipse/state/history").exists());
}

#[test]
fn repl_ends_cleanly_on_eof() {
    let home = tempfile::tempdir().unwrap();
    let out = Command::new(env!("CARGO_BIN_EXE_eclipse"))
        .env_clear()
        .env("HOME", home.path())
        .env("ECLIPSE_BASE_URL", "http://127.0.0.1:9/v1")
        .env("ECLIPSE_MODEL", "m")
        .stdin(Stdio::null())
        .output()
        .unwrap();
    assert!(out.status.success(), "{out:?}");
    // A run that ends cleanly says so instead of going quiet — and the REPL draws no screen, so
    // it says it without a single escape: the clearing is the full-screen interface's business.
    let text = String::from_utf8_lossy(&out.stdout);
    assert!(
        text.contains("no turns"),
        "the goodbye line says what happened: {text}"
    );
    assert!(
        !text.contains('\u{1b}'),
        "no escapes in a line-based exit: {text:?}"
    );
}

/// `!command` is the one thing typed at the composer that is not a turn.
///
/// The assertion is on the store, not on the screen: printing the output is what a turn would also
/// do, so `hi` in stdout proves nothing on its own. What proves it is that no session was created
/// — no user message, no tool result, nothing that would count against the context or break the
/// alternation on the next request.
#[test]
fn a_bang_line_runs_without_creating_a_session() {
    let home = tempfile::tempdir().unwrap();
    let mut child = Command::new(env!("CARGO_BIN_EXE_eclipse"))
        .env_clear()
        .env("HOME", home.path())
        .env("PATH", std::env::var("PATH").unwrap_or_default())
        .env("ECLIPSE_BASE_URL", "http://127.0.0.1:9/v1")
        .env("ECLIPSE_MODEL", "m")
        .env("NO_COLOR", "1")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();
    {
        let stdin = child.stdin.as_mut().unwrap();
        writeln!(stdin, "!echo hi").unwrap();
        // An empty bang is a usage error, not a command and not a prompt.
        writeln!(stdin, "!").unwrap();
        stdin.flush().unwrap();
    }
    drop(child.stdin.take());
    let out = child.wait_with_output().unwrap();
    let shown = String::from_utf8_lossy(&out.stdout);
    assert!(shown.contains("hi"), "the command printed: {shown}");
    assert!(
        shown.contains("! exit 0"),
        "and reported how it ended: {shown}"
    );
    assert!(
        shown.contains("usage: !command"),
        "an empty bang says how to use it: {shown}"
    );
    let sessions = home.path().join(".eclipse/state/sessions");
    let made = std::fs::read_dir(&sessions).map(|d| d.count()).unwrap_or(0);
    assert_eq!(made, 0, "a bang command wrote a session: {sessions:?}");
}

/// `eclipse run` has nobody at the keyboard, so a `!command` there is refused rather than obeyed.
///
/// The failure has to be the refusal, not a prompt: quietly demoting the line to prose would run a
/// model turn on text the caller meant as a shell command, and say nothing about it.
#[test]
fn a_bang_line_on_the_run_command_is_refused_and_runs_nothing() {
    let home = tempfile::tempdir().unwrap();
    let cwd = tempfile::tempdir().unwrap();
    let out = Command::new(env!("CARGO_BIN_EXE_eclipse"))
        .args(["run", "!touch", "should-not-exist"])
        .current_dir(cwd.path())
        .env_clear()
        .env("HOME", home.path())
        .env("PATH", std::env::var("PATH").unwrap_or_default())
        .env("ECLIPSE_BASE_URL", "http://127.0.0.1:9/v1")
        .env("ECLIPSE_MODEL", "m")
        .output()
        .unwrap();
    assert!(!out.status.success(), "{out:?}");
    let err = String::from_utf8_lossy(&out.stderr);
    assert!(err.contains("nobody at one"), "{err}");
    assert!(
        !cwd.path().join("should-not-exist").exists(),
        "the command must not have run"
    );
}

/// A stub that answers every request it is given, and keeps listening until the test is done.
///
/// It used to accept exactly one connection. That is fine until the *first* attempt hiccups — and
/// then the client's retry (`max_retries`, 3 by default, 2 s apart) lands on a port the stub has
/// already closed, so the error the test prints is a bare "Connection refused" that describes the
/// stub's lifetime rather than the code under test. It only showed up on a loaded machine, where
/// the first attempt has room to hiccup. So: serve in a loop, and read the request *body* before
/// answering — replying after the headers alone and then dropping the socket races the client's
/// write, and that reset is one way the first attempt hiccups.
struct Stub {
    stop: std::sync::Arc<std::sync::atomic::AtomicBool>,
    handle: Option<std::thread::JoinHandle<()>>,
}

impl Stub {
    /// Stop listening and wait for the stub thread. Signature-compatible with the `JoinHandle`
    /// this used to be, so `server.join().unwrap()` at the call sites still reads the same.
    fn join(mut self) -> std::thread::Result<()> {
        self.stop.store(true, std::sync::atomic::Ordering::SeqCst);
        match self.handle.take() {
            Some(h) => h.join(),
            None => Ok(()),
        }
    }
}

impl Drop for Stub {
    fn drop(&mut self) {
        self.stop.store(true, std::sync::atomic::Ordering::SeqCst);
        if let Some(h) = self.handle.take() {
            let _ = h.join();
        }
    }
}

/// Reads one HTTP request: the head, plus the body its `content-length` promises.
fn read_request(s: &mut std::net::TcpStream) -> Option<Vec<u8>> {
    let _ = s.set_read_timeout(Some(Duration::from_secs(5)));
    let mut req: Vec<u8> = Vec::new();
    let mut chunk = [0u8; 4096];
    let head_end = loop {
        if let Some(i) = req.windows(4).position(|w| w == b"\r\n\r\n") {
            break i + 4;
        }
        match s.read(&mut chunk) {
            Ok(0) | Err(_) => return None,
            Ok(n) => req.extend_from_slice(&chunk[..n]),
        }
    };
    let head = String::from_utf8_lossy(&req[..head_end]).to_ascii_lowercase();
    let want = head
        .lines()
        .find_map(|l| l.strip_prefix("content-length:"))
        .and_then(|v| v.trim().parse::<usize>().ok())
        .unwrap_or(0);
    while req.len() < head_end + want {
        match s.read(&mut chunk) {
            Ok(0) | Err(_) => break,
            Ok(n) => req.extend_from_slice(&chunk[..n]),
        }
    }
    Some(req)
}

/// Serve plain (non-streaming) chat completions whose text is `content`, for as long as the test
/// needs the server.
fn serve_one_reply(content: &str) -> (String, Stub) {
    let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
    listener.set_nonblocking(true).unwrap();
    let base = format!("http://{}/v1", listener.local_addr().unwrap());
    let body = serde_json::json!({
        "choices": [{"message": {"role": "assistant", "content": content}, "finish_reason": "stop"}]
    })
    .to_string();
    let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
    let flag = stop.clone();
    let handle = std::thread::spawn(move || {
        while !flag.load(std::sync::atomic::Ordering::SeqCst) {
            match listener.accept() {
                Ok((mut s, _)) => {
                    s.set_nonblocking(false).unwrap();
                    if read_request(&mut s).is_none() {
                        continue;
                    }
                    let _ = write!(
                        s,
                        "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
                        body.len()
                    );
                }
                Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => {
                    std::thread::sleep(Duration::from_millis(5));
                }
                Err(_) => break,
            }
        }
    });
    (
        base,
        Stub {
            stop,
            handle: Some(handle),
        },
    )
}

/// stdout is a pipe here, so the markdown renderer must stay off: no ANSI, source
/// text untouched, even though `NO_COLOR` is not set.
#[test]
fn run_with_piped_stdout_prints_markdown_source_without_ansi() {
    let (base, server) = serve_one_reply("# Title\n**bold** and `code`\n- item\n> quote");
    let home = tempfile::tempdir().unwrap();
    let out = Command::new(env!("CARGO_BIN_EXE_eclipse"))
        .args(["run", "hi"])
        .env_clear()
        .env("HOME", home.path())
        .env("ECLIPSE_BASE_URL", &base)
        .env("ECLIPSE_MODEL", "m")
        .env("TERM", "xterm-256color")
        .output()
        .unwrap();
    server.join().unwrap();
    assert!(out.status.success(), "{out:?}");
    assert_eq!(
        stdout(&out),
        "# Title\n**bold** and `code`\n- item\n> quote\n"
    );
    assert!(!out.stderr.contains(&0x1b), "no ANSI on stderr either");
}

fn now_ms() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_millis() as u64
}

/// `eclipse run hi` against a one-reply mock server, with `config_toml` as the config.
fn run_with_config(home: &std::path::Path, config_toml: &str, extra: &[&str]) -> Output {
    let (base, server) = serve_one_reply("ok");
    let cfg = home.join("c.toml");
    std::fs::write(&cfg, config_toml).unwrap();
    let out = Command::new(env!("CARGO_BIN_EXE_eclipse"))
        .args(["--config", cfg.to_str().unwrap(), "run"])
        .args(extra)
        .arg("hi")
        .env_clear()
        .env("HOME", home)
        .env("NO_COLOR", "1")
        .env("ECLIPSE_BASE_URL", &base)
        .env("ECLIPSE_MODEL", "m")
        .output()
        .unwrap();
    server.join().unwrap();
    out
}

/// The retry has to reach a *live* listener.
///
/// This pins the failure CI reported on a loaded machine: the stub hung up on the first
/// connection (the hiccup), the client retried, and a stub that had already stopped listening
/// answered that retry with "Connection refused" — an error about the harness, not the agent.
/// Here the first connection is dropped on purpose and the retry is served, so a stub that
/// accepts once fails this test instead of flaking somewhere else.
#[test]
fn a_retry_after_a_dropped_connection_finds_a_live_stub() {
    let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
    listener.set_nonblocking(true).unwrap();
    let base = format!("http://{}/v1", listener.local_addr().unwrap());
    let server = std::thread::spawn(move || {
        let mut deadline = std::time::Instant::now() + Duration::from_secs(10);
        let mut dropped_one = false;
        while std::time::Instant::now() < deadline {
            match listener.accept() {
                Ok((mut s, _)) => {
                    s.set_nonblocking(false).unwrap();
                    if !dropped_one {
                        // Hang up without a byte: the client has to retry.
                        dropped_one = true;
                        continue;
                    }
                    if read_request(&mut s).is_some() {
                        let body = r#"{"choices":[{"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}]}"#;
                        write!(
                            s,
                            "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
                            body.len()
                        )
                        .unwrap();
                    }
                    return;
                }
                Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => {
                    std::thread::sleep(Duration::from_millis(5));
                    deadline = std::time::Instant::now() + Duration::from_secs(10);
                }
                Err(_) => break,
            }
        }
    });
    let home = tempfile::tempdir().unwrap();
    let cfg = home.path().join("c.toml");
    std::fs::write(
        &cfg,
        "[provider]\nretry_base_delay_ms = 1\nmax_retries = 3\n",
    )
    .unwrap();
    let out = Command::new(env!("CARGO_BIN_EXE_eclipse"))
        .args(["--config", cfg.to_str().unwrap(), "run", "hi"])
        .env_clear()
        .env("HOME", home.path())
        .env("NO_COLOR", "1")
        .env("ECLIPSE_BASE_URL", &base)
        .env("ECLIPSE_MODEL", "m")
        .stdin(Stdio::null())
        .output()
        .unwrap();
    server.join().unwrap();
    assert!(
        out.status.success(),
        "the retry reached a closed port: {out:?}"
    );
    assert_eq!(stdout(&out), "ok\n");
}

/// The stub has to answer more than one request, because a retry opens a second connection.
#[test]
fn the_stub_answers_a_second_connection() {
    let (base, server) = serve_one_reply("ok");
    let addr = base.trim_start_matches("http://").trim_end_matches("/v1");
    for attempt in 1..=2 {
        let mut s = std::net::TcpStream::connect(addr).expect("the stub is still listening");
        write!(
            s,
            "POST /v1/chat/completions HTTP/1.1\r\nhost: {addr}\r\ncontent-length: 2\r\n\r\n{{}}"
        )
        .unwrap();
        let mut reply = Vec::new();
        let mut chunk = [0u8; 512];
        while !String::from_utf8_lossy(&reply).contains("ok") {
            let n = s.read(&mut chunk).unwrap();
            if n == 0 {
                break;
            }
            reply.extend_from_slice(&chunk[..n]);
        }
        let text = String::from_utf8_lossy(&reply).into_owned();
        assert!(
            text.starts_with("HTTP/1.1 200") && text.contains("ok"),
            "connection {attempt} was answered: {text:?}"
        );
    }
    server.join().unwrap();
}

fn sessions_dir(home: &std::path::Path) -> std::path::PathBuf {
    let dir = home.join(".eclipse/state/sessions");
    std::fs::create_dir_all(&dir).unwrap();
    dir
}

/// How many sessions the CLI knows about. Counting files would count the database and the
/// legacy transcripts it was imported from, which is not what these tests are about.
fn count_sessions(home: &std::path::Path) -> usize {
    let out = stdout(&run(home, &["sessions", "list"]));
    if out.starts_with("no sessions") {
        return 0;
    }
    out.lines().filter(|l| !l.trim().is_empty()).count()
}

#[test]
fn auto_prune_is_off_by_default() {
    let home = tempfile::tempdir().unwrap();
    let dir = sessions_dir(home.path());
    for i in 0..5 {
        seed_aged_session(&dir, &format!("s{i}"), 1_000 + i);
    }
    let out = run_with_config(home.path(), "[sessions]\nretention_keep_count = 1\n", &[]);
    assert!(out.status.success(), "{out:?}");
    assert_eq!(count_sessions(home.path()), 6, "5 seeded + the new run");
    assert!(!String::from_utf8_lossy(&out.stderr).contains("auto-prune"));
}

#[test]
fn auto_prune_deletes_at_most_ten_and_says_so() {
    let home = tempfile::tempdir().unwrap();
    let dir = sessions_dir(home.path());
    let now = now_ms();
    for i in 0..12 {
        seed_aged_session(&dir, &format!("s{i:02}"), now - 10_000 + i);
    }
    let out = run_with_config(
        home.path(),
        "[sessions]\nauto_prune = true\nretention_keep_count = 2\n",
        &[],
    );
    assert!(out.status.success(), "{out:?}");
    let err = String::from_utf8_lossy(&out.stderr);
    assert!(
        err.contains("auto-prune: removed 10 old session(s)"),
        "{err}"
    );
    assert_eq!(count_sessions(home.path()), 3, "2 kept + the new run");
    assert!(dir.join("s11.jsonl").exists() && dir.join("s10.jsonl").exists());
    assert_eq!(stdout(&out), "ok\n", "reports go to stderr, not the reply");
}

#[test]
fn auto_prune_refuses_to_delete_more_than_ten() {
    let home = tempfile::tempdir().unwrap();
    let dir = sessions_dir(home.path());
    let now = now_ms();
    for i in 0..13 {
        seed_aged_session(&dir, &format!("s{i:02}"), now - 10_000 + i);
    }
    let out = run_with_config(
        home.path(),
        "[sessions]\nauto_prune = true\nretention_keep_count = 2\n",
        &[],
    );
    assert!(out.status.success(), "the run itself still works: {out:?}");
    let err = String::from_utf8_lossy(&out.stderr);
    assert!(
        err.contains("auto-prune skipped: 11 sessions") && err.contains("nothing was deleted"),
        "{err}"
    );
    assert_eq!(
        count_sessions(home.path()),
        14,
        "13 seeded + the new run, none deleted"
    );
}

#[test]
fn auto_prune_without_any_limit_never_deletes() {
    let home = tempfile::tempdir().unwrap();
    let dir = sessions_dir(home.path());
    seed_aged_session(&dir, "ancient", 1_000);
    let out = run_with_config(home.path(), "[sessions]\nauto_prune = true\n", &[]);
    assert!(out.status.success(), "{out:?}");
    let err = String::from_utf8_lossy(&out.stderr);
    assert!(err.contains("neither retention_keep_days"), "{err}");
    assert!(dir.join("ancient.jsonl").exists());
}

#[test]
fn auto_prune_keeps_the_session_being_resumed() {
    let home = tempfile::tempdir().unwrap();
    let dir = sessions_dir(home.path());
    seed_aged_session(&dir, "resume-me", 1_000);
    seed_aged_session(&dir, "stale", 2_000);
    let out = run_with_config(
        home.path(),
        "[sessions]\nauto_prune = true\nretention_keep_days = 30\n",
        &["-s", "resume-me"],
    );
    assert!(out.status.success(), "{out:?}");
    assert!(dir.join("resume-me.jsonl").exists());
    assert!(!dir.join("stale.jsonl").exists());
}

/// Spawn the CLI with a mock provider that accepts the request and then never answers, so
/// the run stays in the model call. Returns the base URL, a receiver that fires once the
/// request arrived, and the server thread.
fn hanging_provider() -> (
    String,
    mpsc::Receiver<()>,
    std::thread::JoinHandle<()>,
    std::net::TcpListener,
) {
    let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
    let base = format!("http://{}/v1", listener.local_addr().unwrap());
    let spare = listener.try_clone().unwrap();
    let (tx, rx) = mpsc::channel::<()>();
    let server = std::thread::spawn(move || {
        let (mut s, _) = listener.accept().unwrap();
        let mut buf = [0u8; 4096];
        let _ = s.read(&mut buf);
        let _ = tx.send(());
        // Hold the connection open until the client gives up on it.
        while let Ok(n) = s.read(&mut buf) {
            if n == 0 {
                break;
            }
        }
    });
    (base, rx, server, spare)
}

fn run_with(home: &std::path::Path, args: &[&str], base: &str) -> Output {
    Command::new(env!("CARGO_BIN_EXE_eclipse"))
        .args(args)
        .env_clear()
        .env("HOME", home)
        .env("NO_COLOR", "1")
        .env("ECLIPSE_BASE_URL", base)
        .env("ECLIPSE_MODEL", "m")
        .output()
        .unwrap()
}

/// `sessions.lock_wait_secs = 0` so a refusal is immediate instead of a 30s wait.
fn config_with_lock_wait(home: &std::path::Path, secs: u64) {
    let dir = home.join(".eclipse");
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(
        dir.join("config.toml"),
        format!("[sessions]\nlock_wait_secs = {secs}\n"),
    )
    .unwrap();
}

#[cfg(unix)]
#[test]
fn a_session_running_in_another_process_is_refused_not_interleaved() {
    let (base, arrived, server, _listener) = hanging_provider();
    let home = tempfile::tempdir().unwrap();
    config_with_lock_wait(home.path(), 0);

    let mut holder = Command::new(env!("CARGO_BIN_EXE_eclipse"))
        .args(["run", "--session", "held", "hi"])
        .env_clear()
        .env("HOME", home.path())
        .env("NO_COLOR", "1")
        .env("ECLIPSE_BASE_URL", &base)
        .env("ECLIPSE_MODEL", "m")
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()
        .unwrap();
    arrived
        .recv_timeout(Duration::from_secs(10))
        .expect("the first run never reached the provider");

    let lock = home.path().join(".eclipse/state/sessions/held.lock");
    let holder_pid = holder.id().to_string();
    let recorded = std::fs::read_to_string(&lock).unwrap_or_default();
    assert!(
        recorded.contains(&holder_pid),
        "the lock file should name the holder: {recorded:?}"
    );

    // A second process on the same session is refused, and the message says who has it.
    let out = run_with(home.path(), &["run", "--session", "held", "hi"], &base);
    let err = String::from_utf8_lossy(&out.stderr);
    assert!(!out.status.success(), "the second run must not start");
    assert!(err.contains("in use by pid"), "{err}");
    assert!(
        err.contains(&holder_pid),
        "it must name the holder pid: {err}"
    );

    // Killing the holder (a crash, or `kill -9`) releases the lock: nothing is stuck.
    holder.kill().unwrap();
    holder.wait().unwrap();
    let freed = std::fs::read_to_string(&lock).unwrap_or_default();
    assert!(freed.starts_with("pid "), "{freed:?}");
    let _ = server.join();
}

#[cfg(unix)]
#[test]
fn ctrl_c_cancels_the_run_and_keeps_the_prompt() {
    let (base, arrived, server, _listener) = hanging_provider();
    let home = tempfile::tempdir().unwrap();
    let child = Command::new(env!("CARGO_BIN_EXE_eclipse"))
        .args(["run", "--session", "interrupted", "hi"])
        .env_clear()
        .env("HOME", home.path())
        .env("NO_COLOR", "1")
        .env("ECLIPSE_BASE_URL", &base)
        .env("ECLIPSE_MODEL", "m")
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();
    arrived
        .recv_timeout(Duration::from_secs(10))
        .expect("the run never reached the provider");

    let started = std::time::Instant::now();
    // SAFETY: the pid is this test's own child and is still alive.
    assert_eq!(unsafe { libc::kill(child.id() as i32, libc::SIGINT) }, 0);
    let out = child.wait_with_output().unwrap();
    assert!(
        started.elapsed() < Duration::from_secs(10),
        "Ctrl-C must not wait for the model call to finish"
    );
    let err = String::from_utf8_lossy(&out.stderr);
    assert_eq!(out.status.code(), Some(130), "{out:?}");
    assert!(err.contains("[cancelled]"), "{err}");

    // The prompt is kept, so the conversation can be continued.
    let shown = stdout(&run(home.path(), &["sessions", "show", "interrupted"]));
    assert!(
        shown.contains("hi") && shown.contains("user:"),
        "the prompt should stay in the session: {shown}"
    );
    let _ = server.join();
}

fn write_plugin(home: &std::path::Path, name: &str, manifest: &str) {
    let dir = home.join(".eclipse/plugins").join(name);
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(dir.join("plugin.toml"), manifest).unwrap();
}

fn write_config(home: &std::path::Path, text: &str) {
    let dir = home.join(".eclipse");
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(dir.join("config.toml"), text).unwrap();
}

#[cfg(unix)]
#[test]
fn plugins_list_shows_what_is_installed_enabled_and_broken() {
    let home = tempfile::tempdir().unwrap();
    write_plugin(
        home.path(),
        "good",
        "name = \"good\"\nversion = \"0.2.0\"\ndescription = \"Does good things\"\n\
         [[tool]]\nname = \"do_good\"\ndescription = \"x\"\ncommand = [\"true\"]\n\
         policy = \"allow\"\n",
    );
    write_plugin(home.path(), "broken", "name = \"broken\"\napi = 99\n");
    write_plugin(home.path(), "unlisted", "name = \"unlisted\"\n");
    write_config(home.path(), "[plugins]\nenabled = [\"good\", \"broken\"]\n");

    let out = run(home.path(), &["plugins", "list"]);
    assert!(out.status.success(), "{out:?}");
    let text = stdout(&out);
    assert!(text.contains("good") && text.contains("v0.2.0"), "{text}");
    assert!(text.contains("do_good"), "the tool is listed: {text}");
    assert!(text.contains("enabled"), "{text}");
    assert!(
        text.contains("unlisted"),
        "installed but not enabled must still be visible: {text}"
    );
    assert!(
        text.contains("api 99"),
        "the load failure is explained: {text}"
    );
    assert!(text.contains("profile:"), "{text}");
}

#[cfg(unix)]
#[test]
fn a_broken_plugin_warns_but_does_not_stop_a_run() {
    let home = tempfile::tempdir().unwrap();
    write_plugin(home.path(), "bad", "name = \"bad\"\napi = 7\n");
    write_config(home.path(), "[plugins]\nenabled = [\"bad\"]\n");
    let out = Command::new(env!("CARGO_BIN_EXE_eclipse"))
        .args(["run", "hi"])
        .env_clear()
        .env("HOME", home.path())
        .env("NO_COLOR", "1")
        .env("ECLIPSE_BASE_URL", "http://127.0.0.1:9/v1")
        .env("ECLIPSE_MODEL", "m")
        .output()
        .unwrap();
    let err = String::from_utf8_lossy(&out.stderr);
    assert!(err.contains("plugin:"), "the failure is reported: {err}");
    assert!(err.contains("api 7"), "{err}");
}

#[test]
fn a_profile_overlays_config_and_keeps_its_own_sessions() {
    let home = tempfile::tempdir().unwrap();
    write_config(
        home.path(),
        "[agent]\nmax_iterations = 4\n[sessions]\nretention_keep_days = 0\n",
    );
    let profile = home.path().join(".eclipse/profiles/work");
    std::fs::create_dir_all(&profile).unwrap();
    std::fs::write(profile.join("config.toml"), "[agent]\nmax_iterations = 9\n").unwrap();

    // The profile's session directory is separate from the default one.
    let state = home.path().join(".eclipse/state");
    std::fs::create_dir_all(profile.join("state/sessions")).unwrap();
    std::fs::write(
        profile.join("state/sessions/pw.jsonl"),
        "{\"ts\":0,\"message\":{\"role\":\"user\",\"content\":\"profile-only\"}}\n",
    )
    .unwrap();
    std::fs::create_dir_all(state.join("sessions")).unwrap();
    std::fs::write(
        state.join("sessions/pd.jsonl"),
        "{\"ts\":0,\"message\":{\"role\":\"user\",\"content\":\"default-only\"}}\n",
    )
    .unwrap();

    let profile_list = stdout(&run(
        home.path(),
        &["sessions", "list", "--profile", "work"],
    ));
    assert!(profile_list.contains("profile-only"), "{profile_list}");
    assert!(!profile_list.contains("default-only"), "{profile_list}");

    let default_list = stdout(&run(home.path(), &["sessions", "list"]));
    assert!(default_list.contains("default-only"), "{default_list}");
    assert!(!default_list.contains("profile-only"), "{default_list}");

    // The overlay changed one key and left the base config alone.
    let shown = stdout(&run(home.path(), &["config", "show", "--profile", "work"]));
    assert!(shown.contains("# profile: work"), "{shown}");
    assert!(shown.contains("max_iterations = 9"), "{shown}");
    let base = stdout(&run(home.path(), &["config", "show"]));
    assert!(base.contains("max_iterations = 4"), "{base}");

    // The profile comes from the environment too.
    let via_env = Command::new(env!("CARGO_BIN_EXE_eclipse"))
        .args(["config", "show"])
        .env_clear()
        .env("HOME", home.path())
        .env("NO_COLOR", "1")
        .env("ECLIPSE_PROFILE", "work")
        .output()
        .unwrap();
    assert!(stdout(&via_env).contains("# profile: work"));
}

#[test]
fn profiles_list_marks_the_current_one_and_counts_sessions() {
    let home = tempfile::tempdir().unwrap();
    write_config(home.path(), "");
    let dir = home.path().join(".eclipse/profiles/lab");
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(dir.join("config.toml"), "").unwrap();
    let state = home.path().join(".eclipse/profiles/lab/state/sessions");
    std::fs::create_dir_all(&state).unwrap();
    std::fs::write(state.join("s1.jsonl"), "").unwrap();

    let out = stdout(&run(home.path(), &["profiles", "list", "--profile", "lab"]));
    assert!(out.contains("default"), "{out}");
    assert!(
        out.lines().any(|l| l.starts_with("* lab")),
        "the profile in effect is marked: {out}"
    );
    assert!(out.contains("1 session"), "{out}");
    assert!(out.contains("config overlay"), "{out}");
}

/// `#228`: `/profile` in a running session names the profile, the file it was **started with**
/// (`--config`, which is not the default path), the home and the sessions directory — and refuses
/// a name, because a profile is a config file, a home and a store, none of which this transcript
/// can change underneath itself.
#[test]
fn profile_in_the_repl_names_the_file_the_home_and_the_store() {
    let home = tempfile::tempdir().unwrap();
    let (base, _server) = serve_turns(Some(Duration::from_millis(10)), "unused");
    let out = repl_against(
        home.path(),
        "[provider]\nmax_retries = 0\n",
        &base,
        "/profile\n/profile list\n/profile work\n/quit\n",
    );
    assert!(out.status.success(), "{out:?}");
    let text = stdout(&out);
    let cfg = home.path().join("c.toml");
    let root = home.path().join(".eclipse");
    assert!(
        text.contains("profile: default (the default profile)"),
        "{text}"
    );
    assert!(
        text.contains(&format!("config    {}", cfg.display())),
        "the file this process read, not the default one: {text}"
    );
    assert!(
        text.contains(&format!("home      {}", root.display())),
        "{text}"
    );
    assert!(
        text.contains(&format!(
            "sessions  {}",
            root.join("state/sessions").display()
        )),
        "{text}"
    );
    // `/profile list` is the same renderer `eclipse profiles list` prints.
    assert!(text.contains("--profile or ECLIPSE_PROFILE"), "{text}");
    // A name is refused, and the refusal names both ways to switch.
    assert!(text.contains("not switching to work"), "{text}");
    assert!(text.contains("`/new`"), "{text}");
    assert!(text.contains("`--profile work`"), "{text}");
}

/// `#229`: `/gateway` in a running session says what the long-lived process is doing — its state,
/// when it started, the port it serves and whether that port answers, the jobs behind it and the
/// newest run's outcome — and names the profile the *unit* was installed for, which is not
/// necessarily the one this session loaded. `/platforms` is the same report plus the truth about
/// platforms: there are none.
///
/// The unit is a scratch one and `systemctl` is a stand-in on `PATH`: the live unit on a real box
/// must never be the thing a test reads.
#[cfg(unix)]
#[test]
fn gateway_in_the_repl_reports_the_unit_the_port_and_the_jobs() {
    use std::os::unix::fs::PermissionsExt;

    let home = tempfile::tempdir().unwrap();
    let cfg = home.path().join("c.toml");
    let root = home.path().join(".eclipse");
    let unit = home
        .path()
        .join(".config/systemd/user/eclipse-gateway.service");
    std::fs::create_dir_all(unit.parent().unwrap()).unwrap();
    std::fs::create_dir_all(root.join("cron")).unwrap();
    std::fs::create_dir_all(root.join("state")).unwrap();
    // A port nothing listens on: the answer has to be "down" without waiting for a timeout.
    let free = {
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let port = listener.local_addr().unwrap().port();
        drop(listener);
        port
    };
    std::fs::write(
        &cfg,
        format!("[provider]\nmax_retries = 0\n\n[web]\nport = {free}\n"),
    )
    .unwrap();
    std::fs::write(
        &unit,
        format!(
            "[Service]\nEnvironment=\"ECLIPSE_PROFILE=work\"\nEnvironment=\"ECLIPSE_CONFIG={}\"\n",
            cfg.display()
        ),
    )
    .unwrap();
    let jobs =
        "[[job]]\nname = \"brief\"\nschedule = \"daily 07:30\"\nprompt = \"say good morning\"\n";
    std::fs::write(root.join("cron/jobs.toml"), jobs).unwrap();
    std::fs::write(
        root.join("state/cron.json"),
        r#"{"jobs": {"brief": {"runs": 4, "last_started_ms": 1764400000000, "last_finished_ms": 1764400060000, "last_outcome": "ok"}}}"#,
    )
    .unwrap();

    // A stand-in systemctl: the unit is up, its start time is not on offer, and the pid is one
    // nobody has to own. `0` for the monotonic stamp is systemd's own word for "never", which is
    // how this test asserts "unknown age" rather than a number it cannot know.
    let bin = home.path().join("fakebin");
    std::fs::create_dir_all(&bin).unwrap();
    let fake = bin.join("systemctl");
    std::fs::write(
        &fake,
        "#!/bin/sh\necho ActiveState=active\necho ActiveEnterTimestampMonotonic=0\necho ExecMainPID=4242\n",
    )
    .unwrap();
    std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();

    let (base, _server) = serve_turns(Some(Duration::from_millis(10)), "unused");
    let mut child = Command::new(env!("CARGO_BIN_EXE_eclipse"))
        .args(["--config", cfg.to_str().unwrap(), "--plain"])
        .current_dir(home.path())
        .env_clear()
        .env("HOME", home.path())
        .env("PATH", format!("{}:/usr/bin:/bin", bin.display()))
        .env("NO_COLOR", "1")
        .env("ECLIPSE_BASE_URL", &base)
        .env("ECLIPSE_MODEL", "m")
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .unwrap();
    {
        use std::io::Write;
        child
            .stdin
            .take()
            .unwrap()
            .write_all(b"/gateway\n/platforms\n/quit\n")
            .unwrap();
    }
    let out = child.wait_with_output().unwrap();
    assert!(out.status.success(), "{out:?}");
    let text = stdout(&out);

    assert!(text.contains("gateway: up"), "{text}");
    assert!(
        text.contains("  up for    unknown"),
        "systemd offered no start time, so none is claimed: {text}"
    );
    assert!(text.contains("  pid       4242"), "{text}");
    assert!(
        text.contains(&format!("  port      127.0.0.1:{free} — down")),
        "the port comes from the config the unit names: {text}"
    );
    assert!(
        text.contains("1 scheduled, 1 enabled") && text.contains("newest run brief: ok"),
        "{text}"
    );
    assert!(
        text.contains("profile work") && text.contains("not this session's (this one is default"),
        "the unit's own profile, not this session's: {text}"
    );
    assert!(
        text.contains("platforms: none configured"),
        "`/platforms` says there are none: {text}"
    );
    // Read-only: the jobs file the report read is byte-identical afterwards.
    assert_eq!(
        std::fs::read_to_string(root.join("cron/jobs.toml")).unwrap(),
        jobs,
        "the verb wrote the jobs file it was reporting on"
    );
}

/// Serve a tool call and then a reply, handing back the request bodies the CLI sent. The
/// second body is what the runtime sent after running (or refusing) the tool, which is how a
/// test can see the tool's result without knowing the session format.
fn serve_tool_then_reply(
    tool: &str,
    args: &str,
    content: &str,
) -> (String, mpsc::Receiver<String>, std::thread::JoinHandle<()>) {
    let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
    let base = format!("http://{}/v1", listener.local_addr().unwrap());
    let (tx, rx) = mpsc::channel::<String>();
    let tool = tool.to_string();
    let args = args.to_string();
    let content = content.to_string();
    let handle = std::thread::spawn(move || {
        for turn in 0..2 {
            let (mut s, _) = listener.accept().unwrap();
            let mut req = Vec::new();
            let mut chunk = [0u8; 4096];
            while !req.windows(4).any(|w| w == b"\r\n\r\n") {
                let n = s.read(&mut chunk).unwrap();
                if n == 0 {
                    return;
                }
                req.extend_from_slice(&chunk[..n]);
            }
            let split = req.windows(4).position(|w| w == b"\r\n\r\n").unwrap() + 4;
            let head = String::from_utf8_lossy(&req[..split]).to_ascii_lowercase();
            let want: usize = head
                .lines()
                .find_map(|l| l.strip_prefix("content-length:"))
                .and_then(|v| v.trim().parse().ok())
                .unwrap_or(0);
            let mut body = req[split..].to_vec();
            while body.len() < want {
                let n = s.read(&mut chunk).unwrap();
                if n == 0 {
                    break;
                }
                body.extend_from_slice(&chunk[..n]);
            }
            let _ = tx.send(String::from_utf8_lossy(&body).into_owned());

            let reply = if turn == 0 {
                serde_json::json!({"choices": [{
                    "message": {"role": "assistant", "content": null, "tool_calls": [{
                        "id": "c1", "type": "function",
                        "function": {"name": tool, "arguments": args}
                    }]},
                    "finish_reason": "tool_calls"
                }]})
                .to_string()
            } else {
                serde_json::json!({"choices": [
                    {"message": {"role": "assistant", "content": content}, "finish_reason": "stop"}
                ]})
                .to_string()
            };
            write!(
                s,
                "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{reply}",
                reply.len()
            )
            .unwrap();
        }
    });
    (base, rx, handle)
}

/// A REPL-shaped endpoint: the composer asks the provider for its model list before the first
/// turn, so a stub that answers exactly two connections answers the wrong two. This one answers
/// every `GET` with a model list, the first `POST` with a tool call and the second with `content`,
/// and hands back each `POST` **whole** — head and body — because the assertion these tests make is
/// about what the model was sent, and the composer's requests must not be assumed to carry a
/// `content-length`.
fn serve_tool_for_repl(
    tool: &str,
    args: &str,
    content: &str,
) -> (String, mpsc::Receiver<String>, std::thread::JoinHandle<()>) {
    let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
    let base = format!("http://{}/v1", listener.local_addr().unwrap());
    let (tx, rx) = mpsc::channel::<String>();
    let tool = tool.to_string();
    let args = args.to_string();
    let content = content.to_string();
    listener.set_nonblocking(true).unwrap();
    let handle = std::thread::spawn(move || {
        let deadline = std::time::Instant::now() + Duration::from_secs(15);
        let mut posts = 0;
        while posts < 2 && std::time::Instant::now() < deadline {
            let Ok((mut s, _)) = listener.accept() else {
                std::thread::sleep(Duration::from_millis(20));
                continue;
            };
            s.set_nonblocking(false).unwrap();
            s.set_read_timeout(Some(Duration::from_millis(300)))
                .unwrap();
            let mut req = Vec::new();
            let mut chunk = [0u8; 4096];
            while !req.windows(4).any(|w| w == b"\r\n\r\n") {
                match s.read(&mut chunk) {
                    Ok(0) | Err(_) => break,
                    Ok(n) => req.extend_from_slice(&chunk[..n]),
                }
            }
            // Whatever follows the head: with a `content-length` it is the body, and a client that
            // chunks is read to the end of what it sent rather than to a header it did not write.
            loop {
                match s.read(&mut chunk) {
                    Ok(0) | Err(_) => break,
                    Ok(n) => req.extend_from_slice(&chunk[..n]),
                }
            }
            let head = String::from_utf8_lossy(&req[..req.len().min(64)]).to_ascii_lowercase();
            let text = String::from_utf8_lossy(&req).to_ascii_lowercase();
            let reply = if head.starts_with("get") {
                serde_json::json!({"data": [{"id": "m"}]}).to_string()
            } else if !text.contains("\"tools\":") {
                // The composer asks the model to name the session before the first turn. A stub
                // that answered that with a tool call would spend the scripted turn on a title.
                serde_json::json!({"choices": [
                    {"message": {"role": "assistant", "content": "a session"}, "finish_reason": "stop"}
                ]})
                .to_string()
            } else {
                posts += 1;
                let _ = tx.send(String::from_utf8_lossy(&req).into_owned());
                if posts == 1 {
                    serde_json::json!({"choices": [{
                        "message": {"role": "assistant", "content": null, "tool_calls": [{
                            "id": "c1", "type": "function",
                            "function": {"name": tool, "arguments": args}
                        }]},
                        "finish_reason": "tool_calls"
                    }]})
                    .to_string()
                } else {
                    serde_json::json!({"choices": [
                        {"message": {"role": "assistant", "content": content}, "finish_reason": "stop"}
                    ]})
                    .to_string()
                }
            };
            let _ = write!(
                s,
                "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{reply}",
                reply.len()
            );
        }
    });
    (base, rx, handle)
}

/// Run `run hi` against `base` with `config_toml`, stdin closed so nothing can be typed at an
/// approval prompt.
fn run_against(home: &std::path::Path, config_toml: &str, base: &str) -> Output {
    let cfg = home.join("c.toml");
    std::fs::write(&cfg, config_toml).unwrap();
    Command::new(env!("CARGO_BIN_EXE_eclipse"))
        .args(["--config", cfg.to_str().unwrap(), "run", "hi"])
        // The tool workspace is the working directory, so run inside the temp home and keep
        // the test's files inside it: `read_file` refuses anything outside on purpose.
        .current_dir(home)
        .env_clear()
        .env("HOME", home)
        .env("TERM", "xterm-256color")
        .env("ECLIPSE_BASE_URL", base)
        .env("ECLIPSE_MODEL", "m")
        .stdin(Stdio::null())
        .output()
        .unwrap()
}

/// `[cli] approval = "auto"` is the `--yes` flag written down: a tool whose policy is `ask`
/// runs instead of waiting for a prompt that a script can never answer.
#[test]
fn approval_auto_runs_a_tool_whose_policy_is_ask() {
    let home = tempfile::tempdir().unwrap();
    std::fs::write(home.path().join("a.txt"), "FILE-CONTENT-BY-NOX").unwrap();
    let (base, bodies, server) = serve_tool_then_reply("read_file", "{\"path\":\"a.txt\"}", "done");
    let out = run_against(
        home.path(),
        "[tools]\nread_file = \"ask\"\n[cli]\napproval = \"auto\"\n",
        &base,
    );
    server.join().unwrap();
    assert!(out.status.success(), "{out:?}");
    let sent: Vec<String> = bodies.iter().collect();
    assert_eq!(sent.len(), 2, "one tool call, one follow-up");
    assert!(
        sent[1].contains("FILE-CONTENT-BY-NOX"),
        "the tool should have run; the model was sent: {}",
        sent[1]
    );
}

/// The same tool under the default `ask` policy, with no terminal to prompt on: it must be
/// refused, not run because nobody was there to say no.
#[test]
fn approval_ask_refuses_when_there_is_no_one_to_ask() {
    let home = tempfile::tempdir().unwrap();
    std::fs::write(home.path().join("a.txt"), "FILE-CONTENT-BY-NOX").unwrap();
    let (base, bodies, server) = serve_tool_then_reply("read_file", "{\"path\":\"a.txt\"}", "done");
    let out = run_against(home.path(), "[tools]\nread_file = \"ask\"\n", &base);
    server.join().unwrap();
    assert!(out.status.success(), "{out:?}");
    let sent: Vec<String> = bodies.iter().collect();
    assert!(!sent[1].contains("FILE-CONTENT-BY-NOX"), "{}", sent[1]);
    assert!(
        sent[1].contains("declined to run"),
        "expected a refusal, got: {}",
        sent[1]
    );
}

/// `[cli] markdown = true` overrides the pipe-based default: piped output is markdown unless
/// the config says otherwise, and ANSI is what rendering markdown actually means here.
#[test]
fn markdown_can_be_forced_on_even_when_stdout_is_a_pipe() {
    let (base, server) = serve_one_reply("**bold** word");
    let home = tempfile::tempdir().unwrap();
    let out = run_against(home.path(), "[cli]\nmarkdown = true\n", &base);
    server.join().unwrap();
    assert!(out.status.success(), "{out:?}");
    let text = stdout(&out);
    assert!(
        text.contains("\u{1b}[1m"),
        "expected bold ANSI, got {text:?}"
    );
    assert!(
        !text.contains("**bold**"),
        "markers should be rendered: {text:?}"
    );
}

#[test]
fn a_run_budget_of_zero_is_refused_rather_than_silently_read_as_one() {
    // No config file is needed: the flag is checked before the config is loaded, so the
    // refusal is about the number the user typed, not about the setup.
    let home = tempfile::tempdir().unwrap();
    let out = run(home.path(), &["run", "--max-iterations", "0", "hi"]);
    assert!(!out.status.success(), "{out:?}");
    let err = String::from_utf8_lossy(&out.stderr).into_owned();
    assert!(err.contains("at least 1"), "{err}");
}

#[test]
fn the_run_command_documents_its_budget_flag() {
    let home = tempfile::tempdir().unwrap();
    let out = run(home.path(), &["run", "--help"]);
    assert!(out.status.success(), "{out:?}");
    assert!(
        stdout(&out).contains("--max-iterations"),
        "{}",
        stdout(&out)
    );
}

// ---- M16: the front door ---------------------------------------------------------------
//
// A fresh install must be able to reach a working `eclipse` without hand-editing TOML. These
// drive the real binary with piped answers against a local server, so they test the prompts,
// the files written, and that the config those files make actually runs.

/// A server that answers `GET /models` with `models` and `POST` (chat) with `content`.
/// Serves `accepts` connections, then stops: the test never waits on a request it did not make.
fn serve_models_and_replies(
    models: &[&str],
    content: &str,
    accepts: usize,
) -> (String, std::thread::JoinHandle<()>) {
    let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
    let base = format!("http://{}/v1", listener.local_addr().unwrap());
    let ids: Vec<String> = models.iter().map(|m| (*m).to_string()).collect();
    let content = content.to_string();
    // Fail fast rather than hang the suite when the count is wrong: a test that blocks on a
    // request nobody makes is worse than a test that fails.
    listener.set_nonblocking(true).unwrap();
    let deadline = std::time::Instant::now() + Duration::from_secs(15);
    let handle = std::thread::spawn(move || {
        let mut served = 0;
        while served < accepts && std::time::Instant::now() < deadline {
            let Ok((mut s, _)) = listener.accept() else {
                std::thread::sleep(Duration::from_millis(20));
                continue;
            };
            served += 1;
            s.set_nonblocking(false).unwrap();
            let mut req = Vec::new();
            let mut chunk = [0u8; 4096];
            while !req.windows(4).any(|w| w == b"\r\n\r\n") {
                match s.read(&mut chunk) {
                    Ok(0) | Err(_) => break,
                    Ok(n) => req.extend_from_slice(&chunk[..n]),
                }
            }
            let head = String::from_utf8_lossy(&req).to_ascii_lowercase();
            let reply = if head.starts_with("get") {
                let rows: Vec<String> = ids
                    .iter()
                    .map(|id| format!("{{\"id\":\"{id}\"}}"))
                    .collect();
                format!("{{\"data\":[{}]}}", rows.join(","))
            } else {
                serde_json::json!({
                    "choices": [{"message": {"role": "assistant", "content": content},
                                 "finish_reason": "stop"}]
                })
                .to_string()
            };
            let _ = write!(
                s,
                "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{reply}",
                reply.len()
            );
        }
    });
    (base, handle)
}

/// `eclipse` with something on stdin (the wizard, and the first-run question).
fn run_with_stdin(home: &std::path::Path, args: &[&str], input: &str) -> Output {
    use std::process::Stdio;
    let mut child = Command::new(env!("CARGO_BIN_EXE_eclipse"))
        .args(args)
        .env_clear()
        .env("HOME", home)
        .env("NO_COLOR", "1")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();
    child
        .stdin
        .take()
        .unwrap()
        .write_all(input.as_bytes())
        .unwrap();
    child.wait_with_output().unwrap()
}

#[test]
fn setup_turns_a_fresh_install_into_a_working_one() {
    let home = tempfile::tempdir().unwrap();
    let (base, server) = serve_models_and_replies(&["small", "big"], "hello from the model", 2);

    // url, key (none), model by its number, profile, tools, dashboard
    let answers = format!("{base}\n\n2\n1\n1\ny\n");
    let out = run_with_stdin(home.path(), &["setup"], &answers);
    assert!(out.status.success(), "{out:?}");

    let cfg = home.path().join(".eclipse/config.toml");
    let text = std::fs::read_to_string(&cfg).unwrap();
    assert!(text.contains(&format!("base_url = \"{base}\"")), "{text}");
    assert!(text.contains("model = \"big\""), "picked by number: {text}");
    assert!(text.contains("profile = \"openai\""), "{text}");
    assert!(
        text.contains("write_file = \"ask\""),
        "the standard preset is the default: {text}"
    );
    // The file stays settings-only: no paragraph was written into it by the wizard, and the
    // three header lines are all the prose there is.
    assert!(text.contains("# What one does, and what it accepts: `eclipse config docs`"));
    assert!(
        !text.contains("Any OpenAI-compatible"),
        "the explanation moved to the manual: {text}"
    );
    // The dashboard token is a secret in .env, never in the config.
    let dotenv = home.path().join(".eclipse/.env");
    let secrets = std::fs::read_to_string(&dotenv).unwrap();
    assert!(secrets.contains("ECLIPSE_WEB_AUTH_TOKEN="), "{secrets}");
    assert!(!text.contains("ECLIPSE_WEB_AUTH_TOKEN="), "{text}");
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        for f in [&cfg, &dotenv] {
            let mode = std::fs::metadata(f).unwrap().permissions().mode() & 0o777;
            assert_eq!(mode, 0o600, "{}", f.display());
        }
    }

    // ...and the config it wrote is one the real program can run a prompt with.
    let run = run_with_stdin(home.path(), &["run", "hi"], "");
    server.join().unwrap();
    assert!(run.status.success(), "{run:?}");
    assert!(stdout(&run).contains("hello from the model"), "{run:?}");
}

#[test]
fn setup_with_a_profile_writes_its_overlay_and_leaves_the_base_alone() {
    let home = tempfile::tempdir().unwrap();
    let (base, server) = serve_models_and_replies(&["work-model"], "hello from the profile", 2);

    // url, key (none), model by its number, wire profile, tools. No dashboard question: the
    // dashboard reads the base config, so a profile has nothing to say about it.
    let answers = format!("{base}\n\n1\n1\n1\n");
    let out = run_with_stdin(home.path(), &["--profile", "work", "setup"], &answers);
    assert!(out.status.success(), "{out:?}");

    let overlay = home.path().join(".eclipse/profiles/work/config.toml");
    let text = std::fs::read_to_string(&overlay).unwrap();
    assert!(text.contains(&format!("base_url = \"{base}\"")), "{text}");
    assert!(text.contains("model = \"work-model\""), "{text}");
    assert!(
        text.contains("A profile overlay"),
        "a profile starts from the overlay starter: {text}"
    );
    assert!(
        !text.contains("# eclipse configuration"),
        "a profile must not restate the whole config: {text}"
    );
    // The base config was never touched: a profile is the exception, not the rule.
    assert!(!home.path().join(".eclipse/config.toml").exists());

    // ...and the profile it wrote is one the real program can run a prompt with.
    let run = run_with_stdin(home.path(), &["--profile", "work", "run", "hi"], "");
    server.join().unwrap();
    assert!(run.status.success(), "{run:?}");
    assert!(stdout(&run).contains("hello from the profile"), "{run:?}");
}

#[test]
fn setup_keeps_the_token_and_everything_it_was_not_asked_about() {
    let home = tempfile::tempdir().unwrap();
    let (base, server) = serve_models_and_replies(&["small"], "ok", 1);
    let answers = format!("{base}\n\n1\n1\n1\ny\n");
    assert!(run_with_stdin(home.path(), &["setup"], &answers)
        .status
        .success());
    server.join().unwrap();

    let cfg = home.path().join(".eclipse/config.toml");
    let dotenv = home.path().join(".eclipse/.env");
    let token = |p: &std::path::Path| {
        std::fs::read_to_string(p)
            .unwrap()
            .lines()
            .find(|l| l.starts_with("ECLIPSE_WEB_AUTH_TOKEN="))
            .unwrap()
            .to_string()
    };
    let first_token = token(&dotenv);
    // Something the wizard never asks about, written by hand before the second run.
    let edited = std::fs::read_to_string(&cfg)
        .unwrap()
        .replace("timeout_secs = 120", "timeout_secs = 999");
    std::fs::write(&cfg, &edited).unwrap();

    // Second run: keep the URL and the model, add a key, keep the rest.
    let (base2, server2) = serve_models_and_replies(&["small"], "ok", 1);
    let answers = "\nsk-typed\n\n\n\n\n";
    let _ = base2;
    let out = run_with_stdin(home.path(), &["setup"], answers);
    assert!(out.status.success(), "{out:?}");

    let text = std::fs::read_to_string(&cfg).unwrap();
    assert_eq!(
        token(&dotenv),
        first_token,
        "the dashboard token must survive"
    );
    assert!(
        text.contains("timeout_secs = 999"),
        "unrelated lines survive: {text}"
    );
    assert!(text.contains("api_key_env = \"ECLIPSE_API_KEY\""), "{text}");
    let secrets = std::fs::read_to_string(&dotenv).unwrap();
    assert!(secrets.contains("ECLIPSE_API_KEY=sk-typed"), "{secrets}");
    // The key itself never lands in the config.
    assert!(!text.contains("sk-typed"), "{text}");
    drop(server2);
}

#[test]
fn bare_eclipse_with_nothing_configured_says_what_to_do_and_does_not_hang() {
    let home = tempfile::tempdir().unwrap();
    // No stdin at all: this is the cron/pipe case, and it must fail fast rather than block.
    let out = Command::new(env!("CARGO_BIN_EXE_eclipse"))
        .env_clear()
        .env("HOME", home.path())
        .env("NO_COLOR", "1")
        .stdin(Stdio::null())
        .output()
        .unwrap();
    assert!(!out.status.success(), "{out:?}");
    let err = String::from_utf8_lossy(&out.stderr).into_owned();
    let out_text = stdout(&out);
    assert!(
        err.contains("eclipse setup") || out_text.contains("eclipse setup"),
        "it must name the fix: {err} {out_text}"
    );
    assert!(
        !out_text.contains("nothing was written") || true,
        "no config may be invented"
    );
    assert!(!home.path().join(".eclipse/config.toml").exists());
}

#[test]
fn the_first_run_question_can_set_everything_up_in_one_go() {
    let home = tempfile::tempdir().unwrap();
    let (base, server) = serve_models_and_replies(&["only-model"], "hi", 1);
    // "y" answers the first-run question, then the wizard's six answers.
    let answers = format!("y\n{base}\n\n1\n1\n1\nn\n");
    let out = run_with_stdin(home.path(), &[], &answers);
    server.join().unwrap();
    assert!(out.status.success(), "{out:?}");
    let text = std::fs::read_to_string(home.path().join(".eclipse/config.toml")).unwrap();
    assert!(text.contains(&format!("base_url = \"{base}\"")), "{text}");
    assert!(text.contains("model = \"only-model\""), "{text}");
    // Dashboard declined: the config must still load. The starter refers to
    // ${ECLIPSE_WEB_AUTH_TOKEN}, so the token is written regardless — the answer only decides
    // what the wizard tells you about. `config show` loading is what proves it.
    assert!(stdout(&out).contains("dashboard left alone"), "{out:?}");
    let show = run_with_stdin(home.path(), &["config", "show"], "");
    assert!(show.status.success(), "{show:?}");
}

// ---- M2: the layered context files ------------------------------------------------------
//
// The claim under test is the whole point of the milestone: a file on disk reaches the model's
// system prompt, in a documented order, labelled with where it came from — and the agent can
// write one back.

/// A repository with a root and a nested directory, and every context file a profile can have.
fn context_fixture() -> (tempfile::TempDir, std::path::PathBuf, std::path::PathBuf) {
    let home = tempfile::tempdir().unwrap();
    let repo = home.path().join("repo");
    let leaf = repo.join("crates/app");
    std::fs::create_dir_all(repo.join(".git")).unwrap();
    std::fs::create_dir_all(&leaf).unwrap();
    std::fs::write(repo.join(".git/HEAD"), "ref: refs/heads/main").unwrap();
    std::fs::write(repo.join("AGENT.md"), "REPO RULE: use the Makefile").unwrap();
    std::fs::write(leaf.join("AGENT.md"), "LEAF RULE: this crate is no_std").unwrap();

    // The context files live in `memory/`, one folder, while the config sits at the root.
    let cfgdir = home.path().join(".eclipse");
    let memdir = cfgdir.join("memory");
    std::fs::create_dir_all(&memdir).unwrap();
    std::fs::write(memdir.join("AGENT.md"), "GLOBAL RULE: answer in English").unwrap();
    std::fs::write(memdir.join("USER.md"), "USER FACT: Max runs two servers").unwrap();
    std::fs::write(
        memdir.join("MEMORY.md"),
        "MEMORY FACT: prefers local inference",
    )
    .unwrap();
    std::fs::write(
        cfgdir.join("config.toml"),
        format!(
            "[provider]\nbase_url = \"http://127.0.0.1:9/v1\"\nmodel = \"m\"\n\
             [tools]\nworkspace_root = \"{}\"\n",
            leaf.display()
        ),
    )
    .unwrap();
    (home, repo, leaf)
}

/// One reply, with the request body handed back for inspection.
fn serve_capturing(content: &str) -> (String, std::thread::JoinHandle<String>) {
    let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
    let base = format!("http://{}/v1", listener.local_addr().unwrap());
    let body = serde_json::json!({
        "choices": [{"message": {"role": "assistant", "content": content}, "finish_reason": "stop"}]
    })
    .to_string();
    let handle = std::thread::spawn(move || {
        let (mut s, _) = listener.accept().unwrap();
        let mut req = Vec::new();
        let mut chunk = [0u8; 4096];
        while !req.windows(4).any(|w| w == b"\r\n\r\n") {
            let n = s.read(&mut chunk).unwrap();
            if n == 0 {
                break;
            }
            req.extend_from_slice(&chunk[..n]);
        }
        let split = req.windows(4).position(|w| w == b"\r\n\r\n").unwrap() + 4;
        let head = String::from_utf8_lossy(&req[..split]).to_ascii_lowercase();
        let want: usize = head
            .lines()
            .find_map(|l| l.strip_prefix("content-length:"))
            .and_then(|v| v.trim().parse().ok())
            .unwrap_or(0);
        let mut body_bytes = req[split..].to_vec();
        while body_bytes.len() < want {
            let n = s.read(&mut chunk).unwrap();
            if n == 0 {
                break;
            }
            body_bytes.extend_from_slice(&chunk[..n]);
        }
        write!(
            s,
            "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
            body.len()
        )
        .unwrap();
        String::from_utf8_lossy(&body_bytes).into_owned()
    });
    (base, handle)
}

#[test]
fn every_context_file_reaches_the_model_labelled_and_in_order() {
    let (home, repo, _leaf) = context_fixture();
    let cfg = home.path().join(".eclipse/config.toml");
    let (base, server) = serve_capturing("ok");
    let text = std::fs::read_to_string(&cfg)
        .unwrap()
        .replace("http://127.0.0.1:9/v1", &base);
    std::fs::write(&cfg, text).unwrap();

    let out = run(home.path(), &["run", "hi"]);
    let sent = server.join().unwrap();
    assert!(out.status.success(), "{out:?}");

    let body: serde_json::Value = serde_json::from_str(&sent).unwrap();
    let system = body["messages"][0]["content"].as_str().unwrap();
    assert_eq!(body["messages"][0]["role"], "system");

    // Every layer is there...
    for needle in [
        "GLOBAL RULE: answer in English",
        "REPO RULE: use the Makefile",
        "LEAF RULE: this crate is no_std",
        "USER FACT: Max runs two servers",
        "MEMORY FACT: prefers local inference",
    ] {
        assert!(system.contains(needle), "{needle} missing from:\n{system}");
    }
    // ...in the documented order: global, repo, leaf, user, memory.
    let at = |needle: &str| system.find(needle).unwrap_or_else(|| panic!("{needle}"));
    assert!(at("GLOBAL RULE") < at("REPO RULE"), "global before project");
    assert!(
        at("REPO RULE") < at("LEAF RULE"),
        "outermost project file first"
    );
    assert!(
        at("LEAF RULE") < at("USER FACT"),
        "instructions before the user model"
    );
    assert!(at("USER FACT") < at("MEMORY FACT"), "memory last");
    // ...and each file layer is labelled with its own path, so a bad rule is traceable.
    assert!(system.contains(&format!(
        "## AGENT.md ({})",
        repo.join("AGENT.md").display()
    )));
    assert!(system.contains(&format!(
        "## USER.md ({})",
        home.path().join(".eclipse/memory/USER.md").display()
    )));
    // The storage format is not what the model reads.
    assert!(
        !system.contains('§'),
        "MEMORY.md is injected as a list, not as the file"
    );
    assert!(
        system.contains("- MEMORY FACT: prefers local inference"),
        "{system}"
    );
}

/// `#268`: a save from the dashboard's editor is a save of the file the prompt reads, so the next
/// run's system message contains it — proved on the request body, not on the screen.
///
/// The save goes through `context_files::write_file`, which is the function `POST /api/context`
/// calls; the route's own tests prove that wiring. What this test adds is the other half: that what
/// lands on disk is what the model is told on the next turn, with no restart and no cache in the
/// way.
#[test]
fn a_save_from_the_dashboard_reaches_the_next_system_prompt() {
    let (home, _repo, leaf) = context_fixture();
    let cfg_path = home.path().join(".eclipse/config.toml");

    // Point the fixture's provider at a server that hands the request body back.
    let (base, server) = serve_capturing("ok");
    let text = std::fs::read_to_string(&cfg_path)
        .unwrap()
        .replace("http://127.0.0.1:9/v1", &base);
    std::fs::write(&cfg_path, text).unwrap();

    // The dashboard's view of the same configuration: the file it was started with, read with the
    // same `HOME` a run gets.
    let env = |key: &str| match key {
        "HOME" => Some(home.path().display().to_string()),
        _ => None,
    };
    let cfg = eclipse_core::config::Config::load_with_profile(Some(&cfg_path), None, &env)
        .expect("the fixture's config loads");

    let user = eclipse_core::context_files::write_file(
        &cfg,
        &env,
        eclipse_core::context_files::Which::User,
        "USER FACT: edited in the browser\n",
    )
    .expect("a legal save");
    // The row it answered with is the file it wrote, and nothing outside the fixture moved.
    assert!(
        user.path.starts_with(home.path()),
        "{}",
        user.path.display()
    );
    assert_eq!(
        std::fs::read_to_string(&user.path).unwrap(),
        "USER FACT: edited in the browser\n"
    );

    let out = run(home.path(), &["run", "hi"]);
    let sent = server.join().unwrap();
    assert!(out.status.success(), "{out:?}");
    let body: serde_json::Value = serde_json::from_str(&sent).unwrap();
    let system = body["messages"][0]["content"].as_str().unwrap();
    assert!(
        system.contains("USER FACT: edited in the browser"),
        "the saved line is in the prompt:\n{system}"
    );
    assert!(
        !system.contains("USER FACT: Max runs two servers"),
        "the line it replaced is gone:\n{system}"
    );
    // And the workspace's own rules are still there: a save to one file is not a reset of the others.
    assert!(
        system.contains("LEAF RULE: this crate is no_std"),
        "{system}"
    );
    let _ = leaf;
}

#[test]
fn context_show_prints_what_would_be_injected() {
    let (home, repo, _leaf) = context_fixture();
    let out = run(home.path(), &["context", "show"]);
    assert!(out.status.success(), "{out:?}");
    let text = stdout(&out);
    // One line per layer, with a path and a character count.
    assert!(text.contains("AGENT.md"), "{text}");
    assert!(
        text.contains(&repo.join("AGENT.md").display().to_string()),
        "{text}"
    );
    assert!(text.contains("chars"), "{text}");
    assert!(text.contains("USER.md"), "{text}");
    assert!(text.contains("MEMORY.md"), "{text}");
    assert!(text.contains("# total:"), "{text}");
    // ...and then the prompt itself, which is the thing being explained.
    assert!(text.contains("REPO RULE: use the Makefile"), "{text}");
    assert!(text.contains("## USER.md"), "{text}");
}

#[test]
fn context_show_prints_the_skills_index_with_byte_counts_and_the_drop_notes() {
    let (home, _repo, _leaf) = context_fixture();
    let skills = home.path().join(".eclipse/skills");
    for (name, desc) in [("backup", "back up the notes"), ("deploy", "ship it")] {
        std::fs::create_dir_all(skills.join(name)).unwrap();
        std::fs::write(
            skills.join(name).join("SKILL.md"),
            format!("---\nname: {name}\ndescription: {desc}\n---\nSTEPS for {name}\n"),
        )
        .unwrap();
    }
    std::fs::create_dir_all(skills.join("nameless")).unwrap();
    std::fs::write(
        skills.join("nameless/SKILL.md"),
        "---\ndescription: x\n---\nbody\n",
    )
    .unwrap();

    let out = run(home.path(), &["context", "show"]);
    assert!(out.status.success(), "{out:?}");
    let text = stdout(&out);
    assert!(text.contains("skills index"), "{text}");
    assert!(text.contains("bytes"), "{text}");
    assert!(text.contains("## Skills"), "{text}");
    assert!(text.contains("- backup: back up the notes"), "{text}");
    assert!(
        !text.contains("STEPS for backup"),
        "the body is not injected: {text}"
    );
    assert!(
        text.find("MEMORY FACT").unwrap() < text.find("## Skills").unwrap(),
        "the index follows MEMORY.md: {text}"
    );
    assert!(text.contains("# skill `nameless` is broken"), "{text}");

    let cfg = home.path().join(".eclipse/config.toml");
    let tight = format!(
        "{}\n[skills]\nindex_budget_chars = 225\n",
        std::fs::read_to_string(&cfg).unwrap()
    );
    std::fs::write(&cfg, tight).unwrap();
    let out = run(home.path(), &["context", "show"]);
    let text = stdout(&out);
    assert!(text.contains("# skills index budget: 225 chars"), "{text}");
    assert!(text.contains("left out 1 of 2 skills"), "{text}");
    assert!(
        text.contains("- backup:") && !text.contains("- deploy:"),
        "{text}"
    );
}

/// A home with a config whose workspace is a temp directory of its own, so a `.eclipse/skills`
/// in the checkout running the tests cannot leak in. Returns the shared skills directory.
fn skills_home() -> (tempfile::TempDir, std::path::PathBuf) {
    let home = tempfile::tempdir().unwrap();
    let workspace = home.path().join("ws");
    std::fs::create_dir_all(&workspace).unwrap();
    write_config(
        home.path(),
        &format!(
            "[provider]\nbase_url = \"http://127.0.0.1:9/v1\"\nmodel = \"m\"\n\
             [tools]\nworkspace_root = \"{}\"\n",
            workspace.display()
        ),
    );
    let skills = home.path().join(".eclipse/skills");
    (home, skills)
}

fn write_skill(dir: &std::path::Path, name: &str, text: &str) {
    std::fs::create_dir_all(dir.join(name)).unwrap();
    std::fs::write(dir.join(name).join("SKILL.md"), text).unwrap();
}

#[test]
fn skills_list_names_source_and_path_and_says_why_a_skill_is_broken_and_who_won() {
    let (home, shared) = skills_home();
    write_skill(
        &shared,
        "backup",
        "---\nname: backup\ndescription: shared copy\n---\nbody\n",
    );
    write_skill(&shared, "nameless", "---\ndescription: x\n---\nbody\n");
    let profile = home.path().join(".eclipse/profiles/work/skills");
    write_skill(
        &profile,
        "backup",
        "---\nname: backup\ndescription: profile copy\n---\nbody\n",
    );
    write_skill(
        &home.path().join("ws/.eclipse/skills"),
        "deploy",
        "---\nname: deploy\ndescription: ship\n---\nbody\n",
    );

    let out = run(home.path(), &["--profile", "work", "skills", "list"]);
    assert!(out.status.success(), "{out:?}");
    let text = stdout(&out);
    assert!(text.contains("3 found, 1 broken"), "{text}");
    let winner = profile.join("backup/SKILL.md").display().to_string();
    let loser = shared.join("backup/SKILL.md").display().to_string();
    assert!(text.contains(&format!("profile:work  {winner}")), "{text}");
    assert!(
        text.contains(&format!("shadows: {loser} (shared)")),
        "{text}"
    );
    assert!(text.contains("workspace"), "{text}");
    assert!(text.contains("BROKEN: missing `name`"), "{text}");

    let out = run(
        home.path(),
        &["--profile", "work", "skills", "list", "--json"],
    );
    let listed: serde_json::Value = serde_json::from_str(&stdout(&out)).unwrap();
    let backup = listed
        .as_array()
        .unwrap()
        .iter()
        .find(|s| s["name"] == "backup")
        .unwrap();
    assert_eq!(backup["source"], "profile:work");
    assert_eq!(backup["description"], "profile copy");
    assert_eq!(backup["shadows"][0]["source"], "shared");
}

#[test]
fn skills_view_prints_a_real_hermes_skill_and_the_files_it_ships() {
    // A verbatim `latest-news-search` skill from Hermes, with its nested `metadata.hermes`
    // frontmatter, committed for the core tests and reused here.
    let fixture = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../eclipse-core/tests/fixtures/hermes-skill/SKILL.md");
    let text = std::fs::read_to_string(&fixture).unwrap_or_else(|e| {
        panic!(
            "the Hermes fixture is missing ({}): {e}. It is committed at \
             crates/eclipse-core/tests/fixtures/hermes-skill/SKILL.md",
            fixture.display()
        )
    });
    let (home, shared) = skills_home();
    write_skill(&shared, "latest-news-search", &text);
    std::fs::create_dir_all(shared.join("latest-news-search/references")).unwrap();
    std::fs::write(shared.join("latest-news-search/references/sources.md"), "s").unwrap();

    let out = run(home.path(), &["skills", "view", "latest-news-search"]);
    assert!(out.status.success(), "{out:?}");
    let shown = stdout(&out);
    assert!(shown.contains("latest-news-search"), "{shown}");
    assert!(shown.contains("description:"), "{shown}");
    assert!(shown.contains("references/sources.md"), "{shown}");

    let out = run(home.path(), &["skills", "view", "nope"]);
    assert!(!out.status.success());
    let err = String::from_utf8_lossy(&out.stderr).into_owned();
    assert!(err.contains("Available: latest-news-search"), "{err}");
}

#[test]
fn skills_validate_fails_naming_each_broken_skill_and_passes_when_there_are_none() {
    let (home, shared) = skills_home();
    write_skill(&shared, "fine", "---\nname: fine\n---\nbody\n");
    let out = run(home.path(), &["skills", "validate"]);
    assert!(out.status.success(), "{out:?}");
    assert!(stdout(&out).contains("ok: 1 skill(s)"), "{}", stdout(&out));

    write_skill(
        &shared,
        "unclosed",
        "---\nname: unclosed\nbody never closes\n",
    );
    write_skill(&shared, "empty", "---\nname: empty\n---\n\n");
    let out = run(home.path(), &["skills", "validate"]);
    assert_eq!(out.status.code(), Some(1), "{out:?}");
    let text = stdout(&out);
    assert!(text.contains("broken: unclosed"), "{text}");
    assert!(text.contains("broken: empty"), "{text}");
    assert!(!text.contains("broken: fine"), "{text}");
    let err = String::from_utf8_lossy(&out.stderr).into_owned();
    assert!(err.contains("2 problem(s)"), "{err}");
}

#[test]
fn the_memory_tool_writes_the_profiles_memory_file() {
    let home = tempfile::tempdir().unwrap();
    let workspace = home.path().join("ws");
    std::fs::create_dir_all(&workspace).unwrap();
    let (base, bodies, server) = serve_tool_then_reply(
        "memory",
        r#"{"action":"add","text":"Max prefers to be told when a command changes state"}"#,
        "noted",
    );
    write_config(
        home.path(),
        &format!(
            "[provider]\nbase_url = \"{base}\"\nmodel = \"m\"\n[tools]\nworkspace_root = \"{}\"\n",
            workspace.display()
        ),
    );

    let out = run(home.path(), &["run", "remember this"]);
    server.join().unwrap();
    assert!(out.status.success(), "{out:?}");

    let memory = home.path().join(".eclipse/memory/MEMORY.md");
    let stored = std::fs::read_to_string(&memory).unwrap();
    assert!(
        stored.contains("Max prefers to be told when a command changes state"),
        "{stored}"
    );
    // The model is told what happened: turn 1 is the first request, turn 2 carries the result.
    let _first = bodies.recv().unwrap();
    let second = bodies.recv().unwrap();
    assert!(second.contains("memory:"), "{second}");
    // ...and so is the person watching (tool output goes to stderr, like every other tool).
    let shown = String::from_utf8_lossy(&out.stderr).into_owned();
    assert!(shown.contains("memory:"), "{shown}");
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mode = std::fs::metadata(&memory).unwrap().permissions().mode() & 0o777;
        assert_eq!(mode, 0o600, "the memory file is private");
    }
}

#[test]
fn the_memory_tool_refuses_past_the_budget_and_says_what_is_stored() {
    let home = tempfile::tempdir().unwrap();
    let workspace = home.path().join("ws");
    std::fs::create_dir_all(&workspace).unwrap();
    let cfgdir = home.path().join(".eclipse");
    let memdir = cfgdir.join("memory");
    std::fs::create_dir_all(&memdir).unwrap();
    // Two thirds of a tiny budget is already gone.
    std::fs::write(memdir.join("MEMORY.md"), "a".repeat(30)).unwrap();

    let (base, _bodies, server) = serve_tool_then_reply(
        "memory",
        r#"{"action":"add","text":"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"}"#,
        "ok",
    );
    write_config(
        home.path(),
        &format!(
            "[provider]\nbase_url = \"{base}\"\nmodel = \"m\"\n\
             [tools]\nworkspace_root = \"{}\"\n\
             [user]\nmemory_budget_chars = 40\n",
            workspace.display()
        ),
    );

    let out = run(home.path(), &["run", "remember more"]);
    server.join().unwrap();
    assert!(out.status.success(), "{out:?}");
    let stored = std::fs::read_to_string(memdir.join("MEMORY.md")).unwrap();
    assert_eq!(stored.trim(), "a".repeat(30), "the refusal wrote nothing");
    let shown = String::from_utf8_lossy(&out.stderr).into_owned();
    assert!(shown.contains("memory is full"), "{shown}");
}

#[test]
fn memory_list_and_prune_work_on_the_profile_file() {
    let home = tempfile::tempdir().unwrap();
    let cfgdir = home.path().join(".eclipse");
    let memdir = cfgdir.join("memory");
    std::fs::create_dir_all(&memdir).unwrap();
    write_config(home.path(), "[user]\nmemory_budget_chars = 40\n");
    let memory = memdir.join("MEMORY.md");
    std::fs::write(
        &memory,
        "oldest entry here\n§\nmiddle entry here\n§\nnewest one\n",
    )
    .unwrap();

    let listed = run(home.path(), &["memory", "list"]);
    assert!(listed.status.success(), "{listed:?}");
    let text = stdout(&listed);
    assert!(text.contains("3 entries"), "{text}");
    assert!(text.contains("1. oldest entry here"), "{text}");

    let pruned = run(home.path(), &["memory", "prune"]);
    assert!(pruned.status.success(), "{pruned:?}");
    let after = std::fs::read_to_string(&memory).unwrap();
    assert!(after.contains("newest one"), "the newest survives: {after}");
    assert!(
        !after.contains("oldest entry here"),
        "the oldest goes first: {after}"
    );
    assert!(stdout(&pruned).contains("pruned"), "{pruned:?}");
}

#[test]
fn a_context_file_over_the_total_budget_is_dropped_and_said_so() {
    let (home, _repo, _leaf) = context_fixture();
    let cfg = home.path().join(".eclipse/config.toml");
    let text = format!(
        "{}\n[agent]\ncontext_files_budget_chars = 60\n",
        std::fs::read_to_string(&cfg).unwrap()
    );
    // `[agent]` has to come before other table headers to stay in the root table.
    let text = text.replace("[agent]", "");
    let text = format!("[agent]\ncontext_files_budget_chars = 60\n{text}");
    std::fs::write(&cfg, text).unwrap();

    let out = run(home.path(), &["context", "show"]);
    assert!(out.status.success(), "{out:?}");
    let shown = stdout(&out);
    assert!(
        shown.contains("dropped") && shown.contains("budget"),
        "the drop is never silent: {shown}"
    );
}

#[cfg(unix)]
#[test]
fn tools_list_shows_policy_provenance_and_whether_the_model_is_offered_a_tool() {
    let home = tempfile::tempdir().unwrap();
    write_plugin(
        home.path(),
        "greeter",
        "name = \"greeter\"\nversion = \"0.1.0\"\n\
         [[tool]]\nname = \"greet\"\ndescription = \"Say hello\"\n\
         command = [\"true\"]\npolicy = \"allow\"\n",
    );
    write_config(
        home.path(),
        "[provider]\nbase_url = \"http://127.0.0.1:9/v1\"\nmodel = \"m\"\n\
         [plugins]\nenabled = [\"greeter\"]\n\
         [tools]\ndisabled = [\"shell\"]\n",
    );

    let out = run(home.path(), &["tools", "list"]);
    assert!(out.status.success(), "{out:?}");
    let listed = stdout(&out);

    // Every built-in is there, with the policy the defaults give it. Spacing is collapsed before
    // comparing: the columns are padding, and the fact under test is name, policy, source.
    let flat = |text: &str| {
        text.lines()
            .map(|l| l.split_whitespace().collect::<Vec<_>>().join(" "))
            .collect::<Vec<_>>()
            .join("\n")
    };
    for row in [
        "read_file allow builtin yes",
        "write_file allow builtin yes",
        "patch allow builtin yes",
        "execute_code ask builtin yes",
        "fetch ask builtin yes",
        "script ask builtin yes",
        "search_files allow builtin yes",
        "memory ask builtin yes",
        "skill_view allow builtin yes",
        "skill_manage ask builtin yes",
        "delegate ask builtin yes",
        "cronjob_manage ask builtin yes",
        "session_search allow builtin yes",
    ] {
        assert!(flat(&listed).contains(row), "{row} missing from:\n{listed}");
    }
    // A plugin's tool says which plugin.
    assert!(
        flat(&listed).contains("greet allow plugin:greeter yes"),
        "{listed}"
    );
    // Disabled is not the same as denied, and the listing says which.
    assert!(listed.contains("no (disabled)"), "{listed}");
    // `#350` added `skill_search` and `#171` added `flares`, so every count here moved by one
    // each time. `shell` is disabled in this config and so is not in the offered set.
    assert!(listed.contains("16 offered to the model"), "{listed}");

    // --json is the same facts, machine-readable.
    let out = run(home.path(), &["tools", "list", "--json"]);
    assert!(out.status.success(), "{out:?}");
    let described: serde_json::Value = serde_json::from_str(&stdout(&out)).unwrap();
    let by_name = |name: &str| {
        described
            .as_array()
            .unwrap()
            .iter()
            .find(|d| d["name"] == name)
            .unwrap_or_else(|| panic!("{name} missing"))
            .clone()
    };
    assert_eq!(by_name("greet")["source"], "plugin:greeter");
    assert_eq!(by_name("greet")["policy"], "allow");
    assert_eq!(by_name("greet")["advertised"], true);
    assert_eq!(by_name("shell")["advertised"], false);
    assert_eq!(
        by_name("shell")["policy"],
        "ask",
        "disabled is not a policy change"
    );
}

#[cfg(unix)]
#[test]
fn a_deferred_tool_is_listed_as_deferred_and_adds_exactly_three_offered_tools() {
    let home = tempfile::tempdir().unwrap();
    write_config(
        home.path(),
        "[provider]\nbase_url = \"http://127.0.0.1:9/v1\"\nmodel = \"m\"\n\
         [tools]\ndeferred = [\"shell\", \"note_*\"]\n",
    );
    // `note_*` matches nothing, and saying so is the point: a pattern that silently defers
    // nothing is a tool the operator believes is out of the prompt.
    let out = run(home.path(), &["tools", "list"]);
    assert!(out.status.success(), "{out:?}");
    let listed = stdout(&out);
    // A pattern that matches nothing is a warning, not a row: it is a mistake in the file, so it
    // goes where the other problems go.
    let warned = stderr(&out);
    assert!(
        warned.contains("matches no registered tool: note_*"),
        "{warned}"
    );
    let flat = |text: &str| {
        text.lines()
            .map(|l| l.split_whitespace().collect::<Vec<_>>().join(" "))
            .collect::<Vec<_>>()
            .join("\n")
    };
    // Deferred, not disabled: the policy is untouched and the tool is still there.
    assert!(
        flat(&listed).contains("shell ask builtin deferred Run a command"),
        "{listed}"
    );
    // Sixteen built-ins, of which one is deferred, plus the three that reach it.
    assert!(
        listed.contains("19 tools, 18 offered to the model"),
        "{listed}"
    );
    assert!(listed.contains("tool_search"), "{listed}");
    assert!(listed.contains("tool_describe"), "{listed}");
    assert!(listed.contains("tool_call"), "{listed}");

    // Without a deferral the three are not registered at all: no tokens for nothing to reach.
    let plain = tempfile::tempdir().unwrap();
    write_config(
        plain.path(),
        "[provider]\nbase_url = \"http://127.0.0.1:9/v1\"\nmodel = \"m\"\n[tools]\n",
    );
    let listed = stdout(&run(plain.path(), &["tools", "list"]));
    assert!(!listed.contains("tool_search"), "{listed}");
    // `#350` added `skill_search` and `#171` added `flares`; every count here moved by one each
    // time, and with nothing deferred there is no bridge to add three more.
    assert!(listed.contains("16 offered to the model"), "{listed}");

    // A deferred tool is in the schema's `$defs` and not in its `oneOf`, like a disabled one:
    // the document says what may be called and still describes what may not.
    let out = run(home.path(), &["tools", "schema"]);
    assert!(out.status.success(), "{out:?}");
    let doc: serde_json::Value = serde_json::from_str(&stdout(&out)).unwrap();
    let branches = doc["oneOf"].as_array().unwrap();
    assert!(!branches
        .iter()
        .any(|b| b["properties"]["name"]["const"] == "shell"));
    assert!(branches
        .iter()
        .any(|b| b["properties"]["name"]["const"] == "tool_call"));
    assert!(
        doc["$defs"]["shell"].is_object(),
        "still described in $defs"
    );
}

#[cfg(unix)]
#[test]
fn tools_schema_is_one_document_and_leaves_disabled_tools_out_of_its_branches() {
    let home = tempfile::tempdir().unwrap();
    write_config(
        home.path(),
        "[provider]\nbase_url = \"http://127.0.0.1:9/v1\"\nmodel = \"m\"\n\
         [tools]\ndisabled = [\"shell\"]\n",
    );
    let out = run(home.path(), &["tools", "schema"]);
    assert!(out.status.success(), "{out:?}");
    let doc: serde_json::Value = serde_json::from_str(&stdout(&out)).unwrap();

    assert_eq!(
        doc["$schema"],
        "https://json-schema.org/draft/2020-12/schema"
    );
    assert_eq!(doc["$id"], "urn:eclipse:tools");
    let branches: Vec<&str> = doc["oneOf"]
        .as_array()
        .unwrap()
        .iter()
        .map(|b| b["properties"]["name"]["const"].as_str().unwrap())
        .collect();
    assert!(
        branches.contains(&"read_file") && branches.contains(&"memory"),
        "{branches:?}"
    );
    assert!(
        !branches.contains(&"shell"),
        "a disabled tool is not a branch"
    );
    // Its arguments schema is still described: the tool exists, this configuration just does
    // not offer it.
    assert!(doc["$defs"]["shell"].is_object(), "{:?}", doc["$defs"]);
    // Every $ref resolves into $defs.
    for b in doc["oneOf"].as_array().unwrap() {
        let r = b["properties"]["arguments"]["$ref"].as_str().unwrap();
        let name = r.strip_prefix("#/$defs/").expect("a local ref");
        assert!(doc["$defs"].get(name).is_some(), "{r} does not resolve");
    }
    // The schema is a usable description of the arguments, not just names.
    let read = &doc["$defs"]["read_file"];
    assert_eq!(read["type"], "object");
    assert!(read["properties"]["path"]["type"] == "string", "{read:#?}");
}

#[cfg(unix)]
#[test]
fn a_disabled_tool_is_neither_offered_to_the_model_nor_run_when_the_model_asks_anyway() {
    let home = tempfile::tempdir().unwrap();
    let workspace = home.path().join("ws");
    std::fs::create_dir_all(&workspace).unwrap();
    let (base, bodies, server) = serve_tool_then_reply(
        "shell",
        r#"{"command":"touch canary.txt"}"#,
        "I could not run it",
    );
    write_config(
        home.path(),
        &format!(
            "[provider]\nbase_url = \"{base}\"\nmodel = \"m\"\n\
             [tools]\nworkspace_root = \"{}\"\nshell = \"allow\"\ndisabled = [\"shell\"]\n",
            workspace.display()
        ),
    );

    let out = run(home.path(), &["run", "make a file"]);
    server.join().unwrap();
    assert!(
        out.status.success(),
        "the run survives a refused call: {out:?}"
    );

    let first = bodies.recv().unwrap();
    let body: serde_json::Value = serde_json::from_str(&first).unwrap();
    let offered: Vec<&str> = body["tools"]
        .as_array()
        .unwrap()
        .iter()
        .map(|t| t["function"]["name"].as_str().unwrap())
        .collect();
    assert!(
        !offered.contains(&"shell"),
        "not advertised even though its policy is allow: {offered:?}"
    );
    assert!(offered.contains(&"read_file"), "{offered:?}");

    // The model asked anyway — a hallucinated call gets a refusal that names the reason.
    let second = bodies.recv().unwrap();
    assert!(
        second.contains("disabled in the config"),
        "the refusal says why: {second}"
    );
    assert!(
        !workspace.join("canary.txt").exists(),
        "the command never ran"
    );
}

#[test]
fn a_disabled_entry_that_names_nothing_is_reported_rather_than_ignored() {
    let home = tempfile::tempdir().unwrap();
    write_config(
        home.path(),
        "[provider]\nbase_url = \"http://127.0.0.1:9/v1\"\nmodel = \"m\"\n\
         [tools]\ndisabled = [\"shel\"]\n",
    );
    let out = run(home.path(), &["tools", "list"]);
    assert!(out.status.success(), "{out:?}");
    let warned = String::from_utf8_lossy(&out.stderr).into_owned();
    assert!(warned.contains("shel"), "{warned}");
    assert!(warned.contains("Available:"), "{warned}");
}

/// A server that answers `GET /models` with the given ids and refuses everything else.
fn serve_models(ids: &[&str]) -> (String, std::thread::JoinHandle<()>) {
    let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
    let base = format!("http://{}/v1", listener.local_addr().unwrap());
    let body = serde_json::json!({
        "object": "list",
        "data": ids.iter().map(|id| serde_json::json!({"id": id})).collect::<Vec<_>>(),
    })
    .to_string();
    let handle = std::thread::spawn(move || {
        let (mut s, _) = listener.accept().unwrap();
        let mut req = Vec::new();
        let mut chunk = [0u8; 2048];
        while !req.windows(4).any(|w| w == b"\r\n\r\n") {
            let n = s.read(&mut chunk).unwrap();
            if n == 0 {
                return;
            }
            req.extend_from_slice(&chunk[..n]);
        }
        let head = String::from_utf8_lossy(&req).to_ascii_lowercase();
        assert!(head.starts_with("get "), "the listing is a GET:\n{head}");
        assert!(head.contains("/v1/models"), "{head}");
        let out = format!(
            "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{}",
            body.len(),
            body
        );
        let _ = s.write_all(out.as_bytes());
    });
    (base, handle)
}

#[test]
fn models_lists_what_the_endpoint_serves_and_marks_the_configured_one() {
    let home = tempfile::tempdir().unwrap();
    let (base, server) = serve_models(&["small-model", "big-model"]);
    write_config(
        home.path(),
        &format!("[provider]\nbase_url = \"{base}\"\nmodel = \"big-model\"\n"),
    );
    let out = run(home.path(), &["models"]);
    server.join().unwrap();
    assert!(out.status.success(), "{out:?}");
    let listed = stdout(&out);
    assert!(listed.contains("1) small-model"), "{listed}");
    assert!(
        listed.contains("* 2) big-model"),
        "the configured one is marked: {listed}"
    );
    // Numbered, so `/model 1` inside the interface means the same thing.
    assert!(
        listed.contains("`*` is what this configuration uses"),
        "{listed}"
    );
}

#[test]
fn a_run_with_model_sends_that_model_and_leaves_the_config_alone() {
    let home = tempfile::tempdir().unwrap();
    let (base, server) = serve_capturing("hi");
    let cfg = format!("[provider]\nbase_url = \"{base}\"\nmodel = \"the-configured-one\"\n");
    write_config(home.path(), &cfg);

    let out = run(
        home.path(),
        &["--model", "chosen-for-this-run", "run", "hello"],
    );
    let sent = server.join().unwrap();
    assert!(out.status.success(), "{out:?}");
    let body: serde_json::Value = serde_json::from_str(&sent).unwrap();
    assert_eq!(body["model"], "chosen-for-this-run", "{body}");

    // The file is not the switch: `--model` is per run.
    let after = std::fs::read_to_string(home.path().join(".eclipse/config.toml")).unwrap();
    assert_eq!(after, cfg, "the config must be untouched");
}

#[test]
fn the_plain_prompt_still_answers_on_a_pipe() {
    // The menu needs a terminal; a pipe must keep working, because that is what a script and
    // every other test in this file drives.
    let home = tempfile::tempdir().unwrap();
    let workspace = home.path().join("ws");
    std::fs::create_dir_all(&workspace).unwrap();
    // `rm` is the class of command the prompt exists for; `true` would simply run.
    let (base, bodies, server) =
        serve_tool_then_reply("shell", r#"{"command":"rm -rf build"}"#, "ok");
    write_config(
        home.path(),
        &format!(
            "[provider]\nbase_url = \"{base}\"\nmodel = \"m\"\n\
             [tools]\nworkspace_root = \"{}\"\nshell = \"ask\"\n",
            workspace.display()
        ),
    );
    let out = run_with_stdin(home.path(), &["run", "go"], "s\n");
    server.join().unwrap();
    assert!(out.status.success(), "{out:?}");
    let shown = String::from_utf8_lossy(&out.stderr).into_owned();
    assert!(
        shown.contains("[y/s/N]"),
        "the prompt names the three answers: {shown}"
    );
    let _first = bodies.recv().unwrap();
    let second = bodies.recv().unwrap();
    assert!(
        !second.contains("declined"),
        "`s` is one of the two ways to say yes: {second}"
    );
}

/// The other half of the same rule, and the reason people were declining the harness: a command
/// that cannot destroy anything must run without a question. Without this, "only dangerous
/// commands ask" is a claim no test holds.
#[test]
fn an_ordinary_command_runs_without_asking_anything() {
    let home = tempfile::tempdir().unwrap();
    let workspace = home.path().join("work");
    std::fs::create_dir_all(&workspace).unwrap();
    let (base, bodies, server) = serve_tool_then_reply("shell", r#"{"command":"ls -la"}"#, "ok");
    write_config(
        home.path(),
        &format!(
            "[provider]\nbase_url = \"{base}\"\nmodel = \"m\"\n\
             [tools]\nworkspace_root = \"{}\"\nshell = \"ask\"\n",
            workspace.display()
        ),
    );
    let out = run_with_stdin(home.path(), &["run", "go"], "\n");
    server.join().unwrap();
    assert!(out.status.success(), "{out:?}");
    let shown = String::from_utf8_lossy(&out.stderr).into_owned();
    assert!(
        !shown.contains("[y/s/N]"),
        "`ls` is not a decision: {shown}"
    );
    let _first = bodies.recv().unwrap();
    let second = bodies.recv().unwrap();
    assert!(!second.contains("declined"), "it ran: {second}");
}

#[test]
fn continue_reopens_the_newest_session_so_it_carries_the_earlier_turns() {
    let home = tempfile::tempdir().unwrap();
    let (base, bodies, server) = serve_tool_then_reply("shell", r#"{"command":"true"}"#, "first");
    write_config(
        home.path(),
        &format!("[provider]\nbase_url = \"{base}\"\nmodel = \"m\"\n"),
    );
    let first = run(home.path(), &["run", "remember this"]);
    assert!(first.status.success(), "{first:?}");
    server.join().unwrap();
    // Drain the first conversation: a call and its reply are two requests.
    let _ = bodies.recv();
    let _ = bodies.recv();

    // A second server, because the first has finished.
    let (base2, bodies2, server2) =
        serve_tool_then_reply("shell", r#"{"command":"true"}"#, "second");
    write_config(
        home.path(),
        &format!("[provider]\nbase_url = \"{base2}\"\nmodel = \"m\"\n"),
    );
    let second = run(home.path(), &["--continue", "run", "and then"]);
    assert!(second.status.success(), "{second:?}");
    server2.join().unwrap();

    let carried = bodies2.recv().unwrap();
    assert!(
        carried.contains("remember this"),
        "--continue must carry the earlier turn, not start over:\n{carried}"
    );
    assert!(carried.contains("and then"), "{carried}");
}

#[test]
fn continue_with_nothing_to_continue_says_so_and_does_not_invent_a_session() {
    let home = tempfile::tempdir().unwrap();
    write_config(
        home.path(),
        "[provider]\nbase_url = \"http://127.0.0.1:9/v1\"\nmodel = \"m\"\n",
    );
    let out = run(home.path(), &["--continue", "run", "hello"]);
    assert!(
        !out.status.success(),
        "it must not pretend to resume: {out:?}"
    );
    let shown = String::from_utf8_lossy(&out.stderr).into_owned();
    assert!(
        shown.contains("no sessions to continue"),
        "the message names the problem: {shown}"
    );
    // And it did not create one on the way out.
    let listed = run(home.path(), &["sessions", "list"]);
    let text = stdout(&listed);
    assert!(text.contains("no sessions"), "still empty:\n{text}");
}

#[test]
fn sessions_show_last_keeps_the_end_and_says_what_it_left_out() {
    let home = tempfile::tempdir().unwrap();
    let (base, bodies, server) =
        serve_tool_then_reply("shell", r#"{"command":"true"}"#, "the reply");
    write_config(
        home.path(),
        &format!("[provider]\nbase_url = \"{base}\"\nmodel = \"m\"\n"),
    );
    let run_out = run(home.path(), &["run", "the question"]);
    assert!(run_out.status.success(), "{run_out:?}");
    server.join().unwrap();
    let _ = bodies.recv();
    let _ = bodies.recv();

    let listed = run(home.path(), &["sessions", "list"]);
    let id = String::from_utf8_lossy(&listed.stdout)
        .split_whitespace()
        .next()
        .unwrap()
        .to_string();

    let shown = run(home.path(), &["sessions", "show", &id, "--last", "1"]);
    assert!(shown.status.success(), "{shown:?}");
    let text = stdout(&shown);
    assert!(
        text.contains("the reply"),
        "the tail is what is shown:\n{text}"
    );
    assert!(
        !text.contains("the question"),
        "--last 1 means one message:\n{text}"
    );
    let note = String::from_utf8_lossy(&shown.stderr).into_owned();
    assert!(note.contains("earlier messages not shown"), "{note}");
}

#[test]
fn show_without_last_still_prints_everything() {
    let home = tempfile::tempdir().unwrap();
    let (base, bodies, server) =
        serve_tool_then_reply("shell", r#"{"command":"true"}"#, "the reply");
    write_config(
        home.path(),
        &format!("[provider]\nbase_url = \"{base}\"\nmodel = \"m\"\n"),
    );
    let run_out = run(home.path(), &["run", "the question"]);
    assert!(run_out.status.success(), "{run_out:?}");
    server.join().unwrap();
    let _ = bodies.recv();
    let _ = bodies.recv();

    let listed = run(home.path(), &["sessions", "list"]);
    let id = String::from_utf8_lossy(&listed.stdout)
        .split_whitespace()
        .next()
        .unwrap()
        .to_string();
    let text = stdout(&run(home.path(), &["sessions", "show", &id]));
    assert!(
        text.contains("the question") && text.contains("the reply"),
        "{text}"
    );
}

/// A home with a config and an (empty) scripts directory where `eclipse` looks for one.
#[cfg(unix)]
fn scripts_home() -> (tempfile::TempDir, std::path::PathBuf) {
    let home = tempfile::tempdir().unwrap();
    write_config(
        home.path(),
        "[provider]\nbase_url = \"http://127.0.0.1:9/v1\"\nmodel = \"m\"\n",
    );
    let scripts = home.path().join(".eclipse/scripts");
    (home, scripts)
}

#[cfg(unix)]
fn write_script(dir: &std::path::Path, name: &str, text: &str, mode: u32) {
    use std::os::unix::fs::PermissionsExt;
    std::fs::create_dir_all(dir).unwrap();
    std::fs::write(dir.join(name), text).unwrap();
    std::fs::set_permissions(dir.join(name), std::fs::Permissions::from_mode(mode)).unwrap();
}

#[cfg(unix)]
fn stderr(o: &Output) -> String {
    String::from_utf8_lossy(&o.stderr).into_owned()
}

#[cfg(unix)]
#[test]
fn scripts_list_with_no_directory_prints_the_path_and_says_there_are_none() {
    let (home, scripts) = scripts_home();
    let out = run(home.path(), &["scripts", "list"]);
    assert!(out.status.success(), "{out:?}");
    let text = stdout(&out);
    assert!(text.contains(&scripts.display().to_string()), "{text}");
    assert!(text.contains("no scripts"), "{text}");
    assert!(!scripts.exists(), "listing must not create the directory");

    let out = run(home.path(), &["scripts", "list", "--json"]);
    assert!(out.status.success(), "{out:?}");
    assert_eq!(stdout(&out).trim(), "[]");
}

#[cfg(unix)]
#[test]
fn scripts_list_shows_name_description_and_path_as_text_and_as_json() {
    let (home, scripts) = scripts_home();
    write_script(
        &scripts,
        "backup-media.sh",
        "#!/bin/sh\n# Copy new photos to the NAS.\necho ok\n",
        0o755,
    );
    write_script(&scripts, "bare.sh", "#!/bin/sh\necho ok\n", 0o644);

    let text = stdout(&run(home.path(), &["scripts", "list"]));
    assert!(
        text.contains("backup-media.sh") && text.contains("Copy new photos to the NAS."),
        "{text}"
    );
    assert!(
        text.contains(&scripts.join("backup-media.sh").display().to_string()),
        "{text}"
    );
    assert!(text.contains("not executable"), "{text}");
    assert!(
        text.find("backup-media.sh").unwrap() < text.find("bare.sh").unwrap(),
        "sorted by name: {text}"
    );

    let out = run(home.path(), &["scripts", "list", "--json"]);
    let listed: serde_json::Value = serde_json::from_str(&stdout(&out)).unwrap();
    assert_eq!(listed[0]["name"], "backup-media.sh");
    assert_eq!(listed[0]["description"], "Copy new photos to the NAS.");
    assert_eq!(listed[0]["executable"], true);
    assert_eq!(listed[1]["description"], serde_json::Value::Null);
    assert_eq!(listed[1]["executable"], false);
}

#[cfg(unix)]
#[test]
fn scripts_cat_prints_the_file_with_its_shebang_even_when_it_is_not_executable() {
    let (home, scripts) = scripts_home();
    let body = "#!/bin/sh\n# Say hi.\necho hi\n";
    write_script(&scripts, "hi.sh", body, 0o644);
    let out = run(home.path(), &["scripts", "cat", "hi.sh"]);
    assert!(out.status.success(), "{out:?}");
    assert_eq!(stdout(&out), body);

    for bad in ["../config.toml", "missing.sh"] {
        let out = run(home.path(), &["scripts", "cat", bad]);
        assert!(!out.status.success(), "{bad}");
        assert!(stderr(&out).contains("refused"), "{}", stderr(&out));
    }
}

#[cfg(unix)]
#[test]
fn scripts_run_passes_arguments_through_and_exits_with_the_scripts_own_code() {
    let (home, scripts) = scripts_home();
    write_script(
        &scripts,
        "args.sh",
        "#!/bin/sh\necho \"n=$# first=$1 second=$2\"\necho \"dir=$PWD\"\necho oops >&2\nexit 7\n",
        0o755,
    );
    let out = run(
        home.path(),
        &["scripts", "run", "args.sh", "--dry-run", "two words"],
    );
    assert_eq!(out.status.code(), Some(7), "{out:?}");
    let text = stdout(&out);
    assert!(
        text.contains("n=2 first=--dry-run second=two words"),
        "{text}"
    );
    assert!(text.contains("dir="), "{text}");
    assert!(stderr(&out).contains("oops"), "{}", stderr(&out));

    write_script(&scripts, "fine.sh", "#!/bin/sh\necho fine\n", 0o755);
    let out = run(home.path(), &["scripts", "run", "fine.sh"]);
    assert_eq!(out.status.code(), Some(0), "{out:?}");
    assert_eq!(stdout(&out).trim(), "fine");
}

#[cfg(unix)]
#[test]
fn scripts_run_refuses_what_the_tool_refuses_with_a_reason_and_its_own_exit_code() {
    let (home, scripts) = scripts_home();
    write_script(&scripts, "plain.sh", "#!/bin/sh\necho no\n", 0o644);
    let absolute = scripts.join("plain.sh").display().to_string();
    for (name, why) in [
        ("a..b", "`..`"),
        ("../config.toml", "path separator"),
        ("sub/x.sh", "path separator"),
        (absolute.as_str(), "absolute path"),
        ("missing.sh", "no such file"),
        ("plain.sh", "chmod +x"),
    ] {
        let out = run(home.path(), &["scripts", "run", name]);
        assert_eq!(out.status.code(), Some(126), "{name}: {out:?}");
        assert!(stdout(&out).is_empty(), "{name}: nothing may have run");
        let err = stderr(&out);
        assert!(
            err.contains("refused") && err.contains(why),
            "{name}: {err}"
        );
    }
}

#[cfg(unix)]
#[test]
fn the_script_tool_is_in_tools_list_and_tools_schema() {
    let (home, _) = scripts_home();
    let listed = stdout(&run(home.path(), &["tools", "list"]));
    // Column padding is not the fact under test: a new tool with a longer name re-widths the
    // table, and that should not fail a test about whether `script` is offered.
    let flat = listed
        .lines()
        .map(|l| l.split_whitespace().collect::<Vec<_>>().join(" "))
        .collect::<Vec<_>>()
        .join("\n");
    assert!(flat.contains("script ask builtin yes"), "{listed}");

    let schema = stdout(&run(home.path(), &["tools", "schema"]));
    let schema: serde_json::Value = serde_json::from_str(&schema).unwrap();
    assert!(
        schema.to_string().contains("\"list\"") && schema.to_string().contains("\"script\""),
        "{schema}"
    );
}

/// Serve `replies` one per request, in order, and send each request body down the channel.
#[cfg(unix)]
fn serve_replies(
    replies: Vec<serde_json::Value>,
) -> (String, mpsc::Receiver<String>, std::thread::JoinHandle<()>) {
    let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
    let base = format!("http://{}/v1", listener.local_addr().unwrap());
    let (tx, rx) = mpsc::channel::<String>();
    let handle = std::thread::spawn(move || {
        for reply in replies {
            let (mut s, _) = listener.accept().unwrap();
            let mut req = Vec::new();
            let mut chunk = [0u8; 4096];
            while !req.windows(4).any(|w| w == b"\r\n\r\n") {
                let n = s.read(&mut chunk).unwrap();
                if n == 0 {
                    return;
                }
                req.extend_from_slice(&chunk[..n]);
            }
            let split = req.windows(4).position(|w| w == b"\r\n\r\n").unwrap() + 4;
            let head = String::from_utf8_lossy(&req[..split]).to_ascii_lowercase();
            let want: usize = head
                .lines()
                .find_map(|l| l.strip_prefix("content-length:"))
                .and_then(|v| v.trim().parse().ok())
                .unwrap_or(0);
            let mut body = req[split..].to_vec();
            while body.len() < want {
                let n = s.read(&mut chunk).unwrap();
                if n == 0 {
                    break;
                }
                body.extend_from_slice(&chunk[..n]);
            }
            let _ = tx.send(String::from_utf8_lossy(&body).into_owned());
            let reply = reply.to_string();
            write!(
                s,
                "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{reply}",
                reply.len()
            )
            .unwrap();
        }
    });
    (base, rx, handle)
}

/// Hand the answer to the kernel and then close the way a server is supposed to.
///
/// `write!` only queues bytes. Closing while the client still has anything in flight — a request
/// body half sent, or our answer not yet read — makes the kernel send an RST instead of a FIN, and
/// an RST throws away what the client has not read: that is how a request that *was* answered came
/// back as "the connection dropped while reading it" (#310). So: half-close to say the answer is
/// complete, then read until the client hangs up, bounded so a client that never closes cannot hang
/// the test.
#[cfg(unix)]
fn answer_and_hang_up(s: &mut std::net::TcpStream) {
    let _ = s.flush();
    let _ = s.shutdown(std::net::Shutdown::Write);
    let _ = s.set_read_timeout(Some(Duration::from_secs(2)));
    let mut sink = [0u8; 1024];
    while let Ok(n) = s.read(&mut sink) {
        if n == 0 {
            break;
        }
    }
}

/// One failing request, then one answer: the shape of a turn that failed and was retried.
///
/// Counts the chat requests it saw, because "the retry was answered" is only true if nothing else
/// was: a session-title call is a `/chat/completions` request too, and when one of those took the
/// answer this test passed on the strength of the first turn's reply (#310).
#[cfg(unix)]
fn serve_failure_then_answer(
    content: &str,
) -> (String, std::thread::JoinHandle<()>, Arc<AtomicUsize>) {
    let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
    let base = format!("http://{}/v1", listener.local_addr().unwrap());
    let content = content.to_string();
    let asked = Arc::new(AtomicUsize::new(0));
    let counted = asked.clone();
    let handle = std::thread::spawn(move || {
        for conn in listener.incoming().flatten() {
            let mut s = conn;
            // The head first, then the body `content-length` promises: answering a client that is
            // still writing looks like a broken connection rather than a 502, and a byte left
            // unread in the buffer is what turns the close into a reset.
            let mut req = Vec::new();
            let mut chunk = [0u8; 4096];
            while !req.windows(4).any(|w| w == b"\r\n\r\n") {
                let n = s.read(&mut chunk).unwrap_or(0);
                if n == 0 {
                    break;
                }
                req.extend_from_slice(&chunk[..n]);
            }
            // A connection that opened and closed without a request is not a turn — a reachability
            // probe looks exactly like that, and answering the next real request with its 502
            // would make the test pass or fail for the wrong reason.
            let Some(split) = req.windows(4).position(|w| w == b"\r\n\r\n").map(|p| p + 4) else {
                continue;
            };
            let head = String::from_utf8_lossy(&req[..split]).to_ascii_lowercase();
            let want: usize = head
                .lines()
                .find_map(|l| l.strip_prefix("content-length:"))
                .and_then(|v| v.trim().parse().ok())
                .unwrap_or(0);
            while req.len() < split + want {
                let n = s.read(&mut chunk).unwrap_or(0);
                if n == 0 {
                    break;
                }
                req.extend_from_slice(&chunk[..n]);
            }
            let line = req
                .split(|b| *b == b'\n')
                .next()
                .map(|l| String::from_utf8_lossy(l).into_owned())
                .unwrap_or_default();
            // `/models` and whatever else the endpoint is asked about its capabilities are not
            // turns: they are answered every time, and only `/chat/completions` decides which
            // attempt fails.
            if !line.contains("/chat/completions") {
                let body = if line.contains("/models") {
                    r#"{"object":"list","data":[{"id":"m","object":"model"}]}"#
                } else {
                    "{}"
                };
                let _ = write!(
                    s,
                    "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
                    body.len()
                );
                answer_and_hang_up(&mut s);
                continue;
            }
            let attempt = counted.fetch_add(1, Ordering::SeqCst) + 1;
            if attempt == 1 {
                let _ = write!(
                    s,
                    "HTTP/1.1 502 Bad Gateway\r\ncontent-type: text/plain\r\ncontent-length: 4\r\nconnection: close\r\n\r\nboom"
                );
                answer_and_hang_up(&mut s);
                continue;
            }
            let body = serde_json::json!({"choices": [
                {"message": {"role": "assistant", "content": content}, "finish_reason": "stop"}
            ]})
            .to_string();
            let _ = write!(
                s,
                "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
                body.len()
            );
            // The client hangs up here, which is the signal that the answer arrived whole; then
            // the loop (and the listener) ends. Dropping the listener the instant the bytes were
            // written is what refused the *next* connection while this one was still closing.
            answer_and_hang_up(&mut s);
            return;
        }
    });
    (base, handle, asked)
}

/// The REPL, driven by a pipe, against a given endpoint.
#[cfg(unix)]
fn repl_against(
    home: &std::path::Path,
    config_toml: &str,
    base: &str,
    input: &str,
) -> std::process::Output {
    repl_with_args(home, config_toml, base, &[], input)
}

/// The same session with flags in front of `--config` — `--yes` is the one these tests need,
/// because `/yolo off` has to be able to undo a flag the process was started with.
fn repl_with_args(
    home: &std::path::Path,
    config_toml: &str,
    base: &str,
    args: &[&str],
    input: &str,
) -> std::process::Output {
    use std::process::Stdio;
    let cfg = home.join("c.toml");
    std::fs::write(&cfg, config_toml).unwrap();
    let mut child = Command::new(env!("CARGO_BIN_EXE_eclipse"))
        .args(args)
        .args(["--config", cfg.to_str().unwrap()])
        .current_dir(home)
        .env_clear()
        .env("HOME", home)
        .env("NO_COLOR", "1")
        .env("ECLIPSE_BASE_URL", base)
        .env("ECLIPSE_MODEL", "m")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();
    child
        .stdin
        .take()
        .unwrap()
        .write_all(input.as_bytes())
        .unwrap();
    child.wait_with_output().unwrap()
}

/// M224: `/retry` sends the last question again and the store keeps one copy of it.
///
/// The assertion is on the store, not on the screen: a retry that looks right in the transcript but
/// writes a second user row is the bug this verb exists to avoid — compaction would then see two
/// questions where the person asked one.
#[cfg(unix)]
#[test]
fn a_retry_runs_the_last_question_without_storing_it_twice() {
    let home = tempfile::tempdir().unwrap();
    let (base, server, asked) = serve_failure_then_answer("the sky is blue");
    // `autotitle = false` is not tidiness: the session title is a `/chat/completions` request of
    // its own, so with it on the mock's "the first attempt fails" lands on the title call and the
    // answer goes to the turn rather than the retry — the test then passed on the first turn's
    // reply while the retry was refused (#310).
    let config = "[provider]\nmax_retries = 0\n[sessions]\nautotitle = false\n";
    let out = repl_against(
        home.path(),
        config,
        &base,
        "why is the sky blue\n/retry\n/quit\n",
    );
    server.join().unwrap();

    let text = format!("{}{}", stdout(&out), String::from_utf8_lossy(&out.stderr));
    assert!(text.contains("retrying the last question"), "{text}");
    assert!(
        text.contains("the sky is blue"),
        "the retry was answered: {text}"
    );
    // And it is the *retry's* answer: the first chat request fails, so an answer printed before
    // the retry line would mean the mock answered a request that was not the retry — exactly how
    // this test passed on the wrong reply before #310.
    let printed = stdout(&out);
    let at = |needle: &str| {
        printed
            .find(needle)
            .unwrap_or_else(|| panic!("{needle:?} is missing from stdout: {printed}"))
    };
    assert!(
        at("retrying the last question") < at("the sky is blue"),
        "the answer comes after the retry: {printed}"
    );
    assert_eq!(
        asked.load(Ordering::SeqCst),
        2,
        "one turn that failed and one retry that answered, and nothing else asked: {text}"
    );

    let sessions = home.path().join(".eclipse/state/sessions");
    let store = eclipse_core::session::SessionStore::new(&sessions);
    let listed = store.list().unwrap();
    assert_eq!(listed.len(), 1, "one session, not two");
    let records = store.load_records(&listed[0].id).unwrap();
    let users = records
        .iter()
        .filter(|r| r.message.role == eclipse_core::message::Role::User)
        .count();
    let answers = records
        .iter()
        .filter(|r| r.message.role == eclipse_core::message::Role::Assistant)
        .count();
    assert_eq!(
        users, 1,
        "the question is stored once however many attempts it took: {records:?}"
    );
    assert_eq!(
        answers, 1,
        "and the attempt that worked is stored: {records:?}"
    );
    let question = records
        .iter()
        .find(|r| r.message.role == eclipse_core::message::Role::User)
        .and_then(|r| r.message.content.clone())
        .unwrap_or_default();
    assert_eq!(question, "why is the sky blue");
}

#[cfg(unix)]
fn tool_call_reply(id: &str, tool: &str, args: serde_json::Value) -> serde_json::Value {
    serde_json::json!({"choices": [{
        "message": {"role": "assistant", "content": null, "tool_calls": [{
            "id": id, "type": "function",
            "function": {"name": tool, "arguments": args.to_string()}
        }]},
        "finish_reason": "tool_calls"
    }]})
}

#[cfg(unix)]
fn text_reply(content: &str) -> serde_json::Value {
    serde_json::json!({"choices": [
        {"message": {"role": "assistant", "content": content}, "finish_reason": "stop"}
    ]})
}

/// M5's done-when: one run writes a script and runs it, a second run calls it by name.
#[cfg(unix)]
#[test]
fn a_run_writes_a_script_and_a_later_run_calls_it_by_name() {
    use std::os::unix::fs::PermissionsExt;
    let home = tempfile::tempdir().unwrap();
    let scripts = home.path().join(".eclipse/scripts");
    let target = scripts.join("greet.sh");
    let config = "[cli]\napproval = \"auto\"\n";

    let (base, bodies, server) = serve_replies(vec![
        tool_call_reply(
            "c1",
            "write_file",
            serde_json::json!({
                "path": target.display().to_string(),
                "content": "#!/bin/sh\n# Greet whoever is named.\necho \"hello $1 from the script\"\n",
            }),
        ),
        tool_call_reply(
            "c2",
            "shell",
            serde_json::json!({"command": format!("chmod +x {}", target.display())}),
        ),
        tool_call_reply(
            "c3",
            "script",
            serde_json::json!({"name": "greet.sh", "args": ["world"]}),
        ),
        text_reply("greeted"),
    ]);
    let first = run_against(home.path(), config, &base);
    server.join().unwrap();
    assert!(first.status.success(), "{first:?}");
    let sent: Vec<String> = bodies.iter().collect();
    assert_eq!(sent.len(), 4);
    assert!(
        sent[0].contains("There are no scripts yet"),
        "the first run starts with an empty directory"
    );
    assert!(sent[1].contains("wrote"), "write_file ran: {}", sent[1]);
    assert!(
        sent[3].contains("hello world from the script") && sent[3].contains("exit code: 0"),
        "the script tool ran what was written: {}",
        sent[3]
    );
    assert!(stdout(&first).contains("greeted"), "{first:?}");
    let mode = std::fs::metadata(&target).unwrap().permissions().mode();
    assert_ne!(mode & 0o111, 0, "chmod +x ran");

    let (base, bodies, server) = serve_replies(vec![
        tool_call_reply(
            "c1",
            "script",
            serde_json::json!({"name": "greet.sh", "args": ["again"]}),
        ),
        text_reply("greeted again"),
    ]);
    let second = run_against(home.path(), config, &base);
    server.join().unwrap();
    assert!(second.status.success(), "{second:?}");
    let sent: Vec<String> = bodies.iter().collect();
    assert_eq!(sent.len(), 2);
    assert!(
        sent[0].contains("Scripts when this run started: greet.sh"),
        "the second run is told what exists: {}",
        sent[0]
    );
    assert!(
        sent[1].contains("hello again from the script") && sent[1].contains("exit code: 0"),
        "{}",
        sent[1]
    );
    assert!(stdout(&second).contains("greeted again"), "{second:?}");
}

// ---- M12: routes --------------------------------------------------------------------------

fn dead_base() -> String {
    let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
    let base = format!("http://{}/v1", listener.local_addr().unwrap());
    drop(listener);
    base
}

/// A chain of a dead `local` route and a live `big` one, written to `home/routes.toml`.
fn routes_config(home: &std::path::Path, live: &str) -> std::path::PathBuf {
    let path = home.join("routes.toml");
    std::fs::write(
        &path,
        format!(
            "[provider]\nfallback = [\"local\", \"big\"]\n\
             [[provider.route]]\nname = \"local\"\nbase_url = \"{}\"\nmodel = \"small\"\n\
             stream = false\nmax_retries = 0\napi_key = \"sk-local-secret\"\n\
             [[provider.route]]\nname = \"big\"\nbase_url = \"{live}\"\nmodel = \"large\"\n\
             stream = false\nmax_retries = 0\n",
            dead_base()
        ),
    )
    .unwrap();
    path
}

fn err_text(o: &Output) -> String {
    String::from_utf8_lossy(&o.stderr).into_owned()
}

fn eclipse_with(
    home: &std::path::Path,
    cfg: &std::path::Path,
    env: &[(&str, &str)],
    args: &[&str],
) -> Output {
    Command::new(env!("CARGO_BIN_EXE_eclipse"))
        .args(["--config", cfg.to_str().unwrap()])
        .args(args)
        .env_clear()
        .env("HOME", home)
        .env("NO_COLOR", "1")
        .envs(env.iter().copied())
        .output()
        .unwrap()
}

#[test]
fn run_prints_the_route_line_when_it_hopped_and_nothing_when_the_first_route_answered() {
    let home = tempfile::tempdir().unwrap();
    let (live, server) = serve_one_reply("from the big one");
    let cfg = routes_config(home.path(), &live);
    let out = eclipse_with(home.path(), &cfg, &[], &["run", "hi"]);
    server.join().unwrap();
    assert!(out.status.success(), "{out:?}");
    assert_eq!(stdout(&out), "from the big one\n");
    assert!(
        err_text(&out).contains("route: local \u{2192} big (unreachable)"),
        "{}",
        err_text(&out)
    );

    // Pinned to the live route: it answers first time, so there is nothing to say.
    let (live, server) = serve_one_reply("straight answer");
    let cfg = routes_config(home.path(), &live);
    let out = eclipse_with(home.path(), &cfg, &[], &["run", "--route", "big", "hi"]);
    server.join().unwrap();
    assert!(out.status.success(), "{out:?}");
    assert!(!err_text(&out).contains("route:"), "{}", err_text(&out));
}

#[test]
fn a_pinned_cli_run_fails_naming_the_route_and_eclipse_route_does_the_same() {
    let home = tempfile::tempdir().unwrap();
    let (live, server) = serve_one_reply("never asked");
    let cfg = routes_config(home.path(), &live);
    let by_flag = eclipse_with(home.path(), &cfg, &[], &["run", "--route", "local", "hi"]);
    assert!(!by_flag.status.success());
    assert!(
        err_text(&by_flag).contains("route `local` failed"),
        "{}",
        err_text(&by_flag)
    );

    let by_env = eclipse_with(
        home.path(),
        &cfg,
        &[("ECLIPSE_ROUTE", "local")],
        &["run", "hi"],
    );
    assert!(!by_env.status.success());
    assert!(
        err_text(&by_env).contains("route `local` failed"),
        "{}",
        err_text(&by_env)
    );
    // Nothing reached the live server, so release its accept().
    let _ =
        std::net::TcpStream::connect(live.trim_start_matches("http://").trim_end_matches("/v1"));
    server.join().unwrap();
}

#[test]
fn an_unknown_route_flag_lists_the_routes_that_exist() {
    let home = tempfile::tempdir().unwrap();
    let cfg = routes_config(home.path(), "http://127.0.0.1:9/v1");
    let out = eclipse_with(home.path(), &cfg, &[], &["run", "--route", "nope", "hi"]);
    assert!(!out.status.success());
    let err = err_text(&out);
    assert!(err.contains("nope"), "{err}");
    assert!(err.contains("local") && err.contains("big"), "{err}");
}

#[test]
fn config_show_prints_the_route_table_with_keys_redacted() {
    let home = tempfile::tempdir().unwrap();
    let cfg = routes_config(home.path(), "http://127.0.0.1:9/v1");
    let out = eclipse_with(home.path(), &cfg, &[], &["config", "show"]);
    assert!(out.status.success(), "{out:?}");
    let shown = stdout(&out);
    assert!(
        shown.contains("# routes: local \u{2192} big (fallback chain)"),
        "{shown}"
    );
    assert!(shown.contains("[[provider.route]]"), "{shown}");
    assert!(shown.contains("name = \"local\""), "{shown}");
    assert!(!shown.contains("sk-local-secret"), "{shown}");
}

#[test]
fn config_show_prints_the_aux_key_and_the_role_table() {
    let home = tempfile::tempdir().unwrap();
    let cfg = routes_config(home.path(), "http://127.0.0.1:9/v1");
    let out = eclipse_with(home.path(), &cfg, &[], &["config", "show"]);
    let shown = stdout(&out);
    assert!(shown.contains("# aux: (not set)"), "{shown}");
    assert!(
        shown.contains("#   judgement \u{2192} local (no aux route set)"),
        "{shown}"
    );
    assert!(
        shown.contains("#   delegate \u{2192} local (no delegate route set)"),
        "{shown}"
    );
    assert!(shown.contains("# delegate: (not set)"), "{shown}");
    // No `title` key of its own: the sessions table has `autotitle`, which is a different key and
    // a different promise, so what is refused here is a line that *starts* with `title`.
    assert!(
        !shown
            .lines()
            .any(|l| l.starts_with("title") || l.starts_with("title ")),
        "{shown}"
    );

    let text = std::fs::read_to_string(&cfg).unwrap();
    std::fs::write(
        &cfg,
        text.replacen("fallback", "aux = \"big\"\nfallback", 1),
    )
    .unwrap();
    let shown = stdout(&eclipse_with(home.path(), &cfg, &[], &["config", "show"]));
    assert!(shown.contains("# aux: big"), "{shown}");
    assert!(shown.contains("#   judgement \u{2192} big\n"), "{shown}");
    assert!(shown.contains("aux = \"big\""), "{shown}");

    std::fs::write(
        &cfg,
        text.replacen("fallback", "aux = \"ghost\"\nfallback", 1),
    )
    .unwrap();
    let out = eclipse_with(home.path(), &cfg, &[], &["config", "show"]);
    assert!(!out.status.success());
    let err = err_text(&out);
    assert!(
        err.contains("ghost") && err.contains("local") && err.contains("big"),
        "{err}"
    );
}

#[test]
fn slash_status_in_the_repl_lists_the_chain_and_the_model_each_route_serves() {
    let home = tempfile::tempdir().unwrap();
    let cfg = routes_config(home.path(), "http://127.0.0.1:9/v1");
    let mut child = Command::new(env!("CARGO_BIN_EXE_eclipse"))
        .args(["--config", cfg.to_str().unwrap()])
        .env_clear()
        .env("HOME", home.path())
        .env("NO_COLOR", "1")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();
    child
        .stdin
        .take()
        .unwrap()
        .write_all(b"/status\n/exit\n")
        .unwrap();
    let out = child.wait_with_output().unwrap();
    assert!(out.status.success(), "{out:?}");
    let text = stdout(&out);
    assert!(text.contains("local \u{2192} big"), "{text}");
    assert!(text.contains("local: small @"), "{text}");
    assert!(text.contains("big: large @"), "{text}");
}

#[test]
fn slash_status_names_the_aux_route_only_when_one_is_set() {
    let status = |aux: bool| {
        let home = tempfile::tempdir().unwrap();
        let cfg = routes_config(home.path(), "http://127.0.0.1:9/v1");
        if aux {
            let text = std::fs::read_to_string(&cfg).unwrap();
            std::fs::write(
                &cfg,
                text.replacen("fallback", "aux = \"big\"\nfallback", 1),
            )
            .unwrap();
        }
        let mut child = Command::new(env!("CARGO_BIN_EXE_eclipse"))
            .args(["--config", cfg.to_str().unwrap()])
            .env_clear()
            .env("HOME", home.path())
            .env("NO_COLOR", "1")
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
            .unwrap();
        child
            .stdin
            .take()
            .unwrap()
            .write_all(b"/status\n/exit\n")
            .unwrap();
        let out = child.wait_with_output().unwrap();
        assert!(out.status.success(), "{out:?}");
        stdout(&out)
    };
    let with = status(true);
    assert!(
        with.contains("roles") && with.contains("judgement \u{2192} big"),
        "{with}"
    );
    let without = status(false);
    assert!(!without.contains("summary"), "{without}");
}

#[test]
fn config_show_and_slash_status_say_where_delegate_goes_when_it_has_a_route() {
    let home = tempfile::tempdir().unwrap();
    let cfg = routes_config(home.path(), "http://127.0.0.1:9/v1");
    let text = std::fs::read_to_string(&cfg).unwrap();
    std::fs::write(
        &cfg,
        text.replacen("fallback", "delegate = \"big\"\nfallback", 1),
    )
    .unwrap();
    let shown = stdout(&eclipse_with(home.path(), &cfg, &[], &["config", "show"]));
    assert!(shown.contains("# delegate: big"), "{shown}");
    assert!(shown.contains("#   delegate \u{2192} big\n"), "{shown}");
    assert!(
        shown.contains("#   judgement \u{2192} local (no aux route set)"),
        "{shown}"
    );

    let mut child = Command::new(env!("CARGO_BIN_EXE_eclipse"))
        .args(["--config", cfg.to_str().unwrap()])
        .env_clear()
        .env("HOME", home.path())
        .env("NO_COLOR", "1")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();
    child
        .stdin
        .take()
        .unwrap()
        .write_all(b"/status\n/exit\n")
        .unwrap();
    let out = child.wait_with_output().unwrap();
    let status = stdout(&out);
    assert!(
        status.contains("roles") && status.contains("delegate \u{2192} big"),
        "{status}"
    );
    assert!(!status.contains("summary"), "{status}");
}

/// A child session made the way `delegate` makes one, newer than everything else in the store.
fn seed_subagent(home: &std::path::Path, id: &str, parent: &str, route: &str) {
    let store = eclipse_core::session::SessionStore::new(home.join(".eclipse/state/sessions"));
    store.begin_subagent(id, parent, route).unwrap();
    store
        .append(id, &eclipse_core::message::Message::user("CHILD-JOB"))
        .unwrap();
}

#[test]
fn sessions_list_shows_a_subagent_session_and_whose_it_is() {
    let home = tempfile::tempdir().unwrap();
    seed_session(home.path(), "parent1");
    seed_subagent(home.path(), "child1", "parent1", "big");
    let list = stdout(&run(home.path(), &["sessions", "list"]));
    let child = list.lines().find(|l| l.contains("child1")).expect(&list);
    assert!(
        child.contains("[subagent of parent1 \u{b7} big]") && child.contains("CHILD-JOB"),
        "{list}"
    );
    let parent = list.lines().find(|l| l.contains("parent1  ")).expect(&list);
    assert!(!parent.contains("subagent"), "{list}");
}

#[test]
fn continue_skips_a_subagent_session_even_when_it_is_the_newest() {
    let home = tempfile::tempdir().unwrap();
    seed_session(home.path(), "parent1");
    seed_subagent(home.path(), "child1", "parent1", "big");
    let (base, server) = serve_capturing("ok");
    write_config(
        home.path(),
        &format!("[provider]\nbase_url = \"{base}\"\nmodel = \"m\"\n"),
    );
    let out = run(home.path(), &["--continue", "run", "next"]);
    assert!(out.status.success(), "{out:?}");
    let sent = server.join().unwrap();
    assert!(
        sent.contains("what is in a.txt?") && !sent.contains("CHILD-JOB"),
        "--continue went to the conversation, not the child:\n{sent}"
    );
}

/// A server that answers its n-th request with `bodies[n]` and hands back what it was asked.
fn serve_bodies(bodies: Vec<String>) -> (String, std::thread::JoinHandle<Vec<String>>) {
    let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
    let base = format!("http://{}/v1", listener.local_addr().unwrap());
    let handle = std::thread::spawn(move || {
        let mut seen = Vec::new();
        for body in bodies {
            let (mut s, _) = listener.accept().unwrap();
            let mut req = Vec::new();
            let mut chunk = [0u8; 4096];
            let split = loop {
                let n = s.read(&mut chunk).unwrap();
                req.extend_from_slice(&chunk[..n]);
                if let Some(p) = req.windows(4).position(|w| w == b"\r\n\r\n") {
                    break p + 4;
                }
                if n == 0 {
                    return seen;
                }
            };
            let head = String::from_utf8_lossy(&req[..split]).to_ascii_lowercase();
            let want: usize = head
                .lines()
                .find_map(|l| l.strip_prefix("content-length:"))
                .and_then(|v| v.trim().parse().ok())
                .unwrap_or(0);
            while req.len() < split + want {
                let n = s.read(&mut chunk).unwrap();
                if n == 0 {
                    break;
                }
                req.extend_from_slice(&chunk[..n]);
            }
            seen.push(String::from_utf8_lossy(&req[split..]).into_owned());
            let resp = format!(
                "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
                body.len()
            );
            s.write_all(resp.as_bytes()).unwrap();
        }
        seen
    });
    (base, handle)
}

fn chat_body(content: &str, usage: Option<(u64, u64)>) -> String {
    let mut body = serde_json::json!({
        "choices": [{"message": {"role": "assistant", "content": content}, "finish_reason": "stop"}]
    });
    if let Some((p, c)) = usage {
        body["usage"] = serde_json::json!({"prompt_tokens": p, "completion_tokens": c});
    }
    body.to_string()
}

#[test]
fn a_run_that_delegated_says_what_its_child_cost_and_the_child_session_is_listed() {
    let home = tempfile::tempdir().unwrap();
    let call = serde_json::json!({
        "choices": [{"message": {"role": "assistant", "content": null, "tool_calls": [{
            "id": "c1", "type": "function",
            "function": {"name": "delegate", "arguments": "{\"prompt\":\"dig into it\"}"}
        }]}, "finish_reason": "tool_calls"}]
    })
    .to_string();
    let (small, small_seen) = serve_bodies(vec![call, chat_body("PARENT-FINAL", Some((7, 3)))]);
    let (big, big_seen) = serve_bodies(vec![chat_body("CHILD-ANSWER", Some((40, 9)))]);
    let cfg = home.path().join("c.toml");
    std::fs::write(
        &cfg,
        format!(
            "[provider]\nfallback = [\"small\"]\ndelegate = \"big\"\n\
             [[provider.route]]\nname = \"small\"\nbase_url = \"{small}\"\nmodel = \"s\"\n\
             stream = false\nmax_retries = 0\n\
             [[provider.route]]\nname = \"big\"\nbase_url = \"{big}\"\nmodel = \"b\"\n\
             stream = false\nmax_retries = 0\n\
             [cli]\napproval = \"auto\"\n"
        ),
    )
    .unwrap();
    let out = eclipse_with(home.path(), &cfg, &[], &["run", "go"]);
    assert!(out.status.success(), "{out:?}");
    assert_eq!(stdout(&out), "PARENT-FINAL\n");
    let err = err_text(&out);
    assert!(
        err.contains(
            "delegated: 1 subagent (big) \u{2014} child usage: 40 prompt / 9 completion tokens, 1 iteration"
        ),
        "{err}"
    );
    assert!(big_seen.join().unwrap()[0].contains("dig into it"));
    let parent_second = &small_seen.join().unwrap()[1];
    assert!(parent_second.contains("CHILD-ANSWER"), "{parent_second}");

    let listed = stdout(&eclipse_with(home.path(), &cfg, &[], &["sessions", "list"]));
    assert!(listed.contains("[subagent of "), "{listed}");
    assert!(listed.contains("big"), "{listed}");
    assert!(listed.contains("hi") || listed.contains("go"), "{listed}");
}

#[test]
fn doctor_finds_what_is_wrong_fixes_what_is_safe_and_goes_quiet() {
    let home = tempfile::tempdir().unwrap();
    assert!(run(home.path(), &["config", "init"]).status.success());

    // A fresh install has nothing dangerous; the session directory is created on first use.
    let out = run(home.path(), &["doctor", "--offline"]);
    assert!(out.status.success(), "{out:?}");
    let first = stdout(&out);
    assert!(first.contains("eclipse doctor"), "{first}");
    assert!(first.contains("ok"), "{first}");

    // Break two things a doctor exists for: a secret file anyone can read, and a plugin the
    // config names but nothing can find.
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let dotenv = home.path().join(".eclipse/.env");
        std::fs::set_permissions(&dotenv, std::fs::Permissions::from_mode(0o644)).unwrap();
    }
    write_config(
        home.path(),
        "[provider]\nbase_url = \"\"\n[plugins]\nenabled = [\"gone\"]\n",
    );

    let out = run(home.path(), &["doctor", "--offline"]);
    let said = stdout(&out);
    assert!(
        said.contains("is enabled but its directory is not there"),
        "{said}"
    );
    #[cfg(unix)]
    assert!(
        said.contains("only its owner should be able to read it"),
        "{said}"
    );

    // `--fix` applies the safe repairs and says what it did.
    let fixed = run(home.path(), &["doctor", "--offline", "--fix"]);
    let said = stdout(&fixed);
    assert!(said.contains("fixed:"), "{said}");
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mode = std::fs::metadata(home.path().join(".eclipse/.env"))
            .unwrap()
            .permissions()
            .mode()
            & 0o777;
        assert_eq!(mode, 0o600, "the doctor did not restore the permission");
    }
    let config = std::fs::read_to_string(home.path().join(".eclipse/config.toml")).unwrap();
    assert!(
        !config.contains("\"gone\""),
        "the broken plugin came out of [plugins] enabled: {config}"
    );

    // What was broken is gone. (The `shell` area is not asserted on: this harness runs the
    // binary with a minimal environment, so a machine that really has bubblewrap may still be
    // reported as not having it — which is what the doctor is *for*, not a flake to hide.)
    let again = run(home.path(), &["doctor", "--offline", "--json"]);
    assert!(again.status.success(), "{again:?}");
    let parsed: serde_json::Value = serde_json::from_str(&stdout(&again)).expect("valid json");
    assert_eq!(parsed["problems"], 0, "{}", stdout(&again));
    let findings = parsed["findings"].as_array().unwrap();
    assert!(
        !findings
            .iter()
            .any(|f| f["detail"].as_str().unwrap_or_default().contains("gone")),
        "the missing plugin is still reported: {parsed}"
    );
    #[cfg(unix)]
    assert!(
        !findings
            .iter()
            .any(|f| f["area"] == "permissions" && f["level"] == "warn"),
        "{parsed}"
    );
}

#[test]
fn doctor_reports_a_config_that_does_not_load_instead_of_refusing_to_run() {
    let home = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(home.path().join(".eclipse")).unwrap();
    std::fs::write(
        home.path().join(".eclipse/config.toml"),
        "[provider\nbase_url = \"\"\n",
    )
    .unwrap();
    let out = run(home.path(), &["doctor", "--offline"]);
    assert!(
        !out.status.success(),
        "a broken config is not a passing doctor"
    );
    let said = stdout(&out);
    assert!(said.contains("does not load"), "{said}");
}

#[test]
fn config_set_changes_one_key_and_leaves_the_rest_of_the_file_alone() {
    let home = tempfile::tempdir().unwrap();
    let path = home.path().join(".eclipse/config.toml");
    assert!(run(home.path(), &["config", "init"]).status.success());
    let before = std::fs::read_to_string(&path).unwrap();

    let out = run(
        home.path(),
        &["config", "set", "provider.model", "qwen3.8-27b"],
    );
    assert!(out.status.success(), "{out:?}");
    let after = std::fs::read_to_string(&path).unwrap();
    assert!(after.contains("model = \"qwen3.8-27b\""), "{after}");
    assert_eq!(
        after.lines().count(),
        before.lines().count(),
        "one line changed in place: no line added, none lost"
    );
    assert!(
        after.starts_with("# Every setting this build reads"),
        "the header survived, and the file is still the shipped shape: {after}"
    );
    assert!(
        after.contains("# A commented key is not in use"),
        "and so did the convention line: {after}"
    );

    // A fresh load — which is what the next run does — reads the value back.
    let shown = stdout(&run(home.path(), &["config", "show"]));
    assert!(shown.contains("qwen3.8-27b"), "{shown}");
    let keys = stdout(&run(home.path(), &["config", "keys"]));
    assert!(keys.contains("provider.model = \"qwen3.8-27b\""), "{keys}");
    assert!(
        keys.contains("provider.api_key = «redacted»"),
        "a secret is listed, never printed: {keys}"
    );

    // A wrong type, and a key that lives elsewhere, are both refused with the file untouched.
    for (key, value, want) in [
        ("web.port", "nine", "an integer"),
        ("web.model", "x", "read under [provider]"),
        ("provider.modl", "x", "not a setting"),
    ] {
        let out = run(home.path(), &["config", "set", key, value]);
        assert!(!out.status.success(), "{key} was accepted");
        let said = String::from_utf8_lossy(&out.stderr).to_string();
        assert!(said.contains(want), "{key}: {said}");
        assert_eq!(
            std::fs::read_to_string(&path).unwrap(),
            after,
            "{key} edited the file"
        );
    }

    // The dashboard's own keys say when they take effect.
    let out = run(home.path(), &["config", "set", "web.port", "9000"]);
    assert!(out.status.success(), "{out:?}");
    assert!(
        stdout(&out).contains("restart eclipse-web"),
        "{}",
        stdout(&out)
    );

    // Unsetting comments the line out and the default comes back.
    let out = run(home.path(), &["config", "unset", "web.port"]);
    assert!(out.status.success(), "{out:?}");
    let after = std::fs::read_to_string(&path).unwrap();
    assert!(after.contains("# port = 9000"), "{after}");
    assert!(
        stdout(&run(home.path(), &["config", "keys"])).contains("web.port = 8787 (default)"),
        "the default is back"
    );
}

/// `#596` on the command line: `config set` saved the file and only then loaded it, so an edit the
/// *loader* refuses — `provider.fallback` naming a route that does not exist, which `parse_text`
/// does not check — left a config the next command could not read at all.
#[test]
fn config_set_refuses_a_value_the_loader_would_reject_and_writes_nothing() {
    let home = tempfile::tempdir().unwrap();
    assert!(run(home.path(), &["config", "init"]).status.success());
    let path = home.path().join(".eclipse/config.toml");
    assert!(
        run(home.path(), &["config", "set", "provider.model", "kept"])
            .status
            .success()
    );
    let before = std::fs::read_to_string(&path).unwrap();

    let out = run(
        home.path(),
        &["config", "set", "provider.fallback", "[\"nope\"]"],
    );
    assert!(!out.status.success(), "an unloadable value was accepted");
    let said = String::from_utf8_lossy(&out.stderr).to_string();
    assert!(said.contains("nothing was saved"), "{said}");
    assert_eq!(
        std::fs::read_to_string(&path).unwrap(),
        before,
        "the file is untouched"
    );
    assert!(
        stdout(&run(home.path(), &["config", "keys"])).contains("provider.model = \"kept\""),
        "and the config still loads"
    );
}

#[test]
fn config_show_says_which_hooks_run_and_where_they_are_wired() {
    let home = tempfile::tempdir().unwrap();
    let shown = stdout(&run(home.path(), &["config", "show"]));
    assert!(shown.contains("# hooks, in run order"), "{shown}");
    assert!(
        shown.contains("#   1. redact-secrets @ on_outcome"),
        "{shown}"
    );
    // Shipped but off: `config show` names it so the question "why does a new session carry old
    // text" has an answer in the output rather than in the source.
    assert!(
        shown.contains("#   - recall-sessions @ on_completion_call (off)"),
        "{shown}"
    );
    assert!(
        shown.contains("[hooks]"),
        "the section itself is printed: {shown}"
    );

    write_config(home.path(), "[hooks]\norder = []\n");
    let shown = stdout(&run(home.path(), &["config", "show"]));
    assert!(shown.contains("# hooks: none (order = []"), "{shown}");
}

#[test]
fn a_hooks_section_that_would_silently_do_nothing_stops_the_command_and_names_the_file() {
    let home = tempfile::tempdir().unwrap();
    write_config(
        home.path(),
        "[hooks]\norder = []\n[hooks.redact-secrets]\nallow = []\n",
    );
    let out = run(home.path(), &["config", "show"]);
    assert!(!out.status.success());
    let err = String::from_utf8_lossy(&out.stderr).into_owned();
    assert!(err.contains("config.toml"), "{err}");
    assert!(err.contains("never run"), "{err}");
}

/// A model that asks to read `env.txt`, then answers with what the tool result looked like.
fn serve_a_reader() -> (String, std::thread::JoinHandle<Vec<String>>) {
    let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
    let base = format!("http://{}/v1", listener.local_addr().unwrap());
    let server = std::thread::spawn(move || {
        let mut bodies = Vec::new();
        for _ in 0..2 {
            let (mut s, _) = listener.accept().unwrap();
            let mut req = Vec::new();
            let mut chunk = [0u8; 8192];
            let body = loop {
                let n = s.read(&mut chunk).unwrap();
                assert!(n > 0, "client closed early");
                req.extend_from_slice(&chunk[..n]);
                let text = String::from_utf8_lossy(&req).into_owned();
                if let Some((head, body)) = text.split_once("\r\n\r\n") {
                    let want: usize = head
                        .to_ascii_lowercase()
                        .lines()
                        .find_map(|l| l.strip_prefix("content-length:").map(str::to_string))
                        .and_then(|v| v.trim().parse().ok())
                        .unwrap_or(0);
                    if body.len() >= want {
                        break body.to_string();
                    }
                }
            };
            let reply = if body.contains("\"role\":\"tool\"") {
                r#"{"choices":[{"message":{"role":"assistant","content":"the file was read"}}]}"#
            } else {
                r#"{"choices":[{"message":{"role":"assistant","content":null,"tool_calls":[{"id":"c1","type":"function","function":{"name":"read_file","arguments":"{\"path\":\"env.txt\"}"}}]}}]}"#
            };
            write!(
                s,
                "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{reply}",
                reply.len()
            )
            .unwrap();
            bodies.push(body);
        }
        bodies
    });
    (base, server)
}

fn run_reading_a_key(hooks: &str) -> (Output, Vec<String>) {
    let home = tempfile::tempdir().unwrap();
    let ws = home.path().join("ws");
    std::fs::create_dir_all(&ws).unwrap();
    std::fs::write(
        ws.join("env.txt"),
        "API_TOKEN=abcdef0123456789abcdef\nkey sk-proj-ZmFrZWtleWZvcnRlc3RzMDEyMzQ1Njc4OQ\n",
    )
    .unwrap();
    let (base, server) = serve_a_reader();
    write_config(
        home.path(),
        &format!(
            "[provider]\nbase_url = \"{base}\"\nmodel = \"m\"\nstream = false\nmax_retries = 0\n\
             [tools]\nworkspace_root = \"{}\"\n{hooks}",
            ws.display()
        ),
    );
    let out = run(home.path(), &["run", "--yes", "read env.txt"]);
    (out, server.join().unwrap())
}

#[test]
fn a_run_redacts_what_a_tool_read_and_says_so_once_on_stderr() {
    let (out, bodies) = run_reading_a_key("");
    assert!(out.status.success(), "{out:?}");
    assert!(
        !bodies[1].contains("abcdef0123456789abcdef") && !bodies[1].contains("ZmFrZWtleWZvcnRl")
    );
    assert!(bodies[1].contains("[redacted:token]") && bodies[1].contains("[redacted:api-key]"));
    let err = String::from_utf8_lossy(&out.stderr);
    assert_eq!(
        err.matches("note: redact-secrets replaced 2 secrets in tool output")
            .count(),
        1,
        "{err}"
    );
    assert!(err.contains("[hooks] order turns it off"), "{err}");
}

#[test]
fn a_run_with_an_empty_order_sends_the_file_as_it_is_and_prints_no_note() {
    let (out, bodies) = run_reading_a_key("[hooks]\norder = []\n");
    assert!(out.status.success(), "{out:?}");
    assert!(bodies[1].contains("abcdef0123456789abcdef"));
    assert!(!String::from_utf8_lossy(&out.stderr).contains("redact-secrets"));
}

/// Serve a llama.cpp-shaped streaming reply — one reasoning fragment, one text fragment and a
/// final chunk carrying `finish_reason` and `usage` — and answer the startup probes so the run
/// gets as far as its request. The listener is dropped when the thread ends, which is what
/// leaves the port with nothing behind it.
#[cfg(unix)]
fn serve_one_stream(
    reasoning: &str,
    content: &str,
) -> (String, std::net::SocketAddr, std::thread::JoinHandle<()>) {
    let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
    let addr = listener.local_addr().unwrap();
    let base = format!("http://{addr}/v1");
    let sse = format!(
        "data: {}\n\ndata: {}\n\ndata: {}\n\ndata: [DONE]\n\n",
        serde_json::json!({"choices": [{"index": 0, "delta": {"reasoning_content": reasoning}}]}),
        serde_json::json!({"choices": [{"index": 0, "delta": {"content": content}}]}),
        serde_json::json!({
            "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}],
            "usage": {"prompt_tokens": 9, "completion_tokens": 3, "total_tokens": 12}
        }),
    );
    let handle = std::thread::spawn(move || {
        for conn in listener.incoming() {
            let Ok(mut s) = conn else { return };
            let mut head = Vec::new();
            let mut chunk = [0u8; 2048];
            while !head.windows(4).any(|w| w == b"\r\n\r\n") {
                match s.read(&mut chunk) {
                    Ok(0) | Err(_) => break,
                    Ok(n) => head.extend_from_slice(&chunk[..n]),
                }
            }
            // The startup probe asks /props and /v1/models; only the turn is worth an answer.
            if String::from_utf8_lossy(&head).starts_with("POST") {
                // Read the body off the socket before answering, so the client is not writing
                // into a closed connection.
                s.set_read_timeout(Some(Duration::from_millis(200))).ok();
                let want: usize = String::from_utf8_lossy(&head)
                    .to_ascii_lowercase()
                    .lines()
                    .find_map(|l| {
                        l.strip_prefix("content-length:")
                            .map(|v| v.trim().to_string())
                    })
                    .and_then(|v| v.parse().ok())
                    .unwrap_or(0);
                let split = head.windows(4).position(|w| w == b"\r\n\r\n").unwrap() + 4;
                let mut body = head[split..].to_vec();
                while body.len() < want {
                    match s.read(&mut chunk) {
                        Ok(0) | Err(_) => break,
                        Ok(n) => body.extend_from_slice(&chunk[..n]),
                    }
                }
                write!(
                    s,
                    "HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\nconnection: close\r\n\r\n{sse}"
                )
                .unwrap();
                return; // one turn, then this server is gone for good
            }
            write!(
                s,
                "HTTP/1.1 404 Not Found\r\ncontent-length: 0\r\nconnection: close\r\n\r\n"
            )
            .unwrap();
        }
    });
    (base, addr, handle)
}

/// M14's done-when: a recorded run replays with no server running. The recorder is a stub that
/// speaks llama.cpp's wire shape; it is stopped before the replay, the replay points at the
/// same dead port, and the only way it can print the reply is from the cassette.
#[cfg(unix)]
#[test]
fn a_recorded_run_replays_with_no_server_running() {
    let (base, addr, server) =
        serve_one_stream("weighing the options", "replayed from the cassette");
    let home = tempfile::tempdir().unwrap();
    let eclipse = || {
        let mut c = Command::new(env!("CARGO_BIN_EXE_eclipse"));
        c.env_clear()
            .env("HOME", home.path())
            .env("ECLIPSE_MODEL", "m")
            .env("NO_COLOR", "1")
            .stdin(Stdio::null());
        c
    };

    let recorded = eclipse()
        .args(["run", "--cassette", "offline", "hi"])
        .env("ECLIPSE_BASE_URL", &base)
        .output()
        .unwrap();
    server.join().unwrap();
    assert!(recorded.status.success(), "{recorded:?}");
    let first = stdout(&recorded);
    assert!(first.contains("replayed from the cassette"), "{first}");
    assert!(
        !first.contains("weighing the options"),
        "the reasoner's fragments are not prose: {first}"
    );
    assert!(
        std::net::TcpStream::connect_timeout(&addr, Duration::from_millis(250)).is_err(),
        "the stub that recorded the cassette must be gone: {addr} still answers"
    );

    let replayed = eclipse()
        .args(["run", "--replay-cassette", "offline", "hi"])
        .env("ECLIPSE_BASE_URL", &base)
        .output()
        .unwrap();
    assert!(replayed.status.success(), "{replayed:?}");
    assert_eq!(
        stdout(&replayed),
        first,
        "the replay answers from the cassette, not from a server that is not there"
    );
}

/// `eclipse context show` is a configuration readout: it names the window policy and the rail it
/// implies, and it says plainly when it cannot know the window rather than inventing one.
#[test]
fn context_show_names_the_window_policy_and_the_rail() {
    let home = tempfile::tempdir().unwrap();
    let dir = home.path().join(".eclipse");
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(
        dir.join("config.toml"),
        "[provider]\nbase_url = \"http://127.0.0.1:9/v1\"\nmodel = \"m\"\n\n\
         [context]\ncompact_at = 0.5\nprotect_last_n = 7\nwindow_tokens = 131072\n",
    )
    .unwrap();

    let out = run(home.path(), &["context", "show"]);
    let text = stdout(&out);
    assert!(out.status.success(), "{out:?}");
    assert!(
        text.contains("# window: 131072 (compact_at 0.5)"),
        "the window and the share are named: {text}"
    );
    assert!(
        text.contains("# budget: 65536 estimated tokens (protect_last_n 7 turns verbatim"),
        "the rail and the tail are named: {text}"
    );

    // Off is off: no threshold, and a budget only from an explicit one.
    std::fs::write(
        dir.join("config.toml"),
        "[provider]\nbase_url = \"http://127.0.0.1:9/v1\"\nmodel = \"m\"\n\n\
         [context]\ncompact_at = 0\n",
    )
    .unwrap();
    let text = stdout(&run(home.path(), &["context", "show"]));
    assert!(
        text.contains("compaction off (context.compact_at = 0)")
            && text.contains("# budget: none: a request is never shortened"),
        "{text}"
    );
}

/// With no window stated anywhere, the readout says so — a guessed window would be a rail
/// nobody can explain.
#[test]
fn context_show_does_not_invent_a_window() {
    let home = tempfile::tempdir().unwrap();
    let dir = home.path().join(".eclipse");
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(
        dir.join("config.toml"),
        "[provider]\nbase_url = \"http://127.0.0.1:9/v1\"\nmodel = \"m\"\n",
    )
    .unwrap();
    let text = stdout(&run(home.path(), &["context", "show"]));
    assert!(text.contains("# window: unknown"), "{text}");
    assert!(text.contains("# budget: none"), "{text}");
}

/// `eclipse context handoff` prints what a compaction would put in the system prompt: read out
/// of the transcript, bounded, and citing rows the session actually has.
#[test]
fn context_handoff_prints_the_compiled_middle() {
    let home = tempfile::tempdir().unwrap();
    let dir = home.path().join(".eclipse");
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(
        dir.join("config.toml"),
        "[provider]\nbase_url = \"http://127.0.0.1:9/v1\"\nmodel = \"m\"\n\n\
         [context]\nprotect_last_n = 2\nhandoff_chars = 4000\n",
    )
    .unwrap();

    let store = eclipse_core::session::SessionStore::new(dir.join("state/sessions"));
    store
        .append(
            "handoff-1",
            &eclipse_core::message::Message::user("fix the port in /etc/eclipse/config.toml"),
        )
        .unwrap();
    for index in 0..6 {
        store
            .append(
                "handoff-1",
                &eclipse_core::message::Message::assistant(format!("step {index} done")),
            )
            .unwrap();
        store
            .append(
                "handoff-1",
                &eclipse_core::message::Message::user(format!("and now step {index}")),
            )
            .unwrap();
    }

    let out = run(home.path(), &["context", "handoff", "-s", "handoff-1"]);
    let text = stdout(&out);
    assert!(out.status.success(), "{text}");
    assert!(text.contains("## Original Request"), "{text}");
    assert!(
        text.contains("fix the port in /etc/eclipse/config.toml"),
        "the first ask is not in the handoff: {text}"
    );
    assert!(text.contains("## Session Log (oldest first)"), "{text}");
    assert!(text.contains("[#"), "no row is cited: {text}");
    assert!(
        text.lines()
            .any(|line| line.starts_with("# ") && line.contains("compiled to")),
        "the header does not say what was compiled: {text}"
    );

    // A budget too small to say everything still says something, and says what it left out.
    let small = stdout(&run(
        home.path(),
        &["context", "handoff", "-s", "handoff-1", "--chars", "300"],
    ));
    assert!(
        small.contains("omitted") || small.contains("compiled to 3"),
        "{small}"
    );

    // JSON for anything that wants to read it.
    let json = stdout(&run(
        home.path(),
        &["context", "handoff", "-s", "handoff-1", "--json"],
    ));
    let value: serde_json::Value = serde_json::from_str(&json).expect("valid json");
    assert_eq!(value["session"], "handoff-1");
    assert!(value["handoff"]
        .as_str()
        .unwrap()
        .contains("## Session Log"));

    // An unknown session is an error, not an empty handoff.
    let missing = run(home.path(), &["context", "handoff", "-s", "nope"]);
    assert!(!missing.status.success());
}

/// `eclipse compact verify` and `compare`: the harness measures a stored session, reports the
/// numbers a person can read, and stays green only while the log's refs actually resolve.
#[test]
fn compact_verify_and_compare_measure_a_stored_session() {
    let home = tempfile::tempdir().unwrap();
    let dir = home.path().join(".eclipse");
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(
        dir.join("config.toml"),
        "[provider]\nbase_url = \"http://127.0.0.1:9/v1\"\nmodel = \"m\"\n\n\
         [context]\nprotect_last_n = 2\nhandoff_chars = 4000\n",
    )
    .unwrap();

    let store = eclipse_core::session::SessionStore::new(dir.join("state/sessions"));
    store
        .append(
            "compact-1",
            &eclipse_core::message::Message::user(
                "why is the port in /etc/eclipse/config.toml wrong",
            ),
        )
        .unwrap();
    for index in 0..8 {
        store
            .append(
                "compact-1",
                &eclipse_core::message::Message::assistant_tool_calls(
                    None,
                    vec![eclipse_core::message::ToolCall {
                        id: format!("c{index}"),
                        kind: "function".into(),
                        function: eclipse_core::message::FunctionCall {
                            name: "read_file".into(),
                            arguments: format!(r#"{{"path":"/etc/eclipse/conf.d/{index}.toml"}}"#),
                        },
                    }],
                ),
            )
            .unwrap();
        store
            .append(
                "compact-1",
                &eclipse_core::message::Message::tool_result(
                    format!("c{index}"),
                    format!(r#"{{"resolved_path":"/etc/eclipse/conf.d/{index}.toml"}}"#),
                ),
            )
            .unwrap();
    }

    let verify = run(
        home.path(),
        &["compact", "verify", "-s", "compact-1", "--determinism"],
    );
    let text = stdout(&verify);
    assert!(verify.status.success(), "{text}");
    assert!(text.contains("byte-identical"), "{text}");
    assert!(text.contains("0 violation(s)"), "{text}");
    assert!(
        text.lines()
            .any(|line| line.starts_with("# session compact-1")),
        "the header does not name the session: {text}"
    );

    let compare = run(home.path(), &["compact", "compare", "-s", "compact-1"]);
    let text = stdout(&compare);
    assert!(compare.status.success(), "{text}");
    assert!(text.contains("files"), "{text}");
    assert!(text.contains("retained"), "{text}");

    // The tallies are what a script reads, so they have to be in the JSON.
    let json = stdout(&run(
        home.path(),
        &["compact", "compare", "-s", "compact-1", "--json"],
    ));
    let value: serde_json::Value = serde_json::from_str(&json).expect("valid json");
    assert_eq!(value["session"], "compact-1");
    assert!(
        value["retention"]["total"].as_u64().unwrap() >= 8,
        "{value}"
    );
    assert!(value["log_lines"].as_u64().unwrap() > 0);
    assert_eq!(value["violations"].as_array().unwrap().len(), 0);

    // An unknown session is an error here too, not a measurement of nothing.
    let missing = run(home.path(), &["compact", "verify", "-s", "nope"]);
    assert!(!missing.status.success());
}

// ---- M13: durable approvals ---------------------------------------------------------------

/// Any command against a temp home, with a config file and a scripted provider. Both halves of the
/// M13 flow need this: `run` with `--approvals-out`, then `approve` after the first process is gone.
#[cfg(unix)]
fn run_cmd(home: &std::path::Path, config_toml: &str, base: &str, args: &[&str]) -> Output {
    let cfg = home.join("c.toml");
    std::fs::write(&cfg, config_toml).unwrap();
    Command::new(env!("CARGO_BIN_EXE_eclipse"))
        .arg("--config")
        .arg(&cfg)
        .args(args)
        .current_dir(home)
        .env_clear()
        .env("HOME", home)
        .env("TERM", "xterm-256color")
        .env("ECLIPSE_BASE_URL", base)
        .env("ECLIPSE_MODEL", "m")
        .stdin(Stdio::null())
        .output()
        .unwrap()
}

/// `#230`: `/cron` in the composer is the table `eclipse cron list` prints — the same bytes, because
/// both go through `cron_cli::table` — and it says what is not going to fire it.
///
/// The comparison is against the command's own stdout rather than a copy of the strings: a second
/// copy is exactly what the issue asks not to grow.
#[cfg(unix)]
#[test]
fn the_cron_verb_prints_the_table_the_command_prints() {
    let home = tempfile::tempdir().unwrap();
    let config = "[tools]\n";
    let added = run_cmd(
        home.path(),
        config,
        "http://127.0.0.1:9/v1",
        &[
            "cron",
            "add",
            "--name",
            "brief",
            "--schedule",
            "every 1h",
            "--prompt",
            "summarise",
        ],
    );
    assert!(added.status.success(), "{added:?}");

    let listed = run_cmd(
        home.path(),
        config,
        "http://127.0.0.1:9/v1",
        &["cron", "list"],
    );
    let listed_text = String::from_utf8_lossy(&listed.stdout)
        .trim_end()
        .to_string();
    assert!(listed_text.contains("brief"), "{listed_text}");

    let said = repl_says(home.path(), config, "/cron\n/quit\n");
    assert!(
        said.contains(&listed_text),
        "the composer's table is the command's table, byte for byte:\n-- command --\n{listed_text}\n-- composer --\n{said}"
    );
    // This scratch home has no timer unit, which is the "nothing is scheduling these" case.
    assert!(
        said.contains("scheduler:") && said.contains("install-timer"),
        "the line under it names what is missing and how to fix it: {said}"
    );
}

/// `/cron run <name>` fires the job, reports its exit code, and leaves the composer open.
///
/// `ECLIPSE_BIN` points at a stand-in, so what is being tested is the composer's half — spawn, wait,
/// report — and not a model call. The follow-up command is the proof the session survived it.
#[cfg(unix)]
#[test]
fn the_cron_verb_runs_a_job_and_stays_in_the_composer() {
    use std::os::unix::fs::PermissionsExt;
    let home = tempfile::tempdir().unwrap();
    let config = "[tools]\n";
    run_cmd(
        home.path(),
        config,
        "http://127.0.0.1:9/v1",
        &[
            "cron",
            "add",
            "--name",
            "brief",
            "--schedule",
            "every 1h",
            "--prompt",
            "summarise",
        ],
    );

    // A stand-in that reports what it was asked and fails, so the exit code is not the happy one.
    let stub = home.path().join("stand-in-eclipse");
    std::fs::write(&stub, "#!/bin/sh\necho \"stand-in ran: $*\"\nexit 3\n").unwrap();
    std::fs::set_permissions(&stub, std::fs::Permissions::from_mode(0o755)).unwrap();

    let said = repl_says_env(
        home.path(),
        config,
        &[("ECLIPSE_BIN", stub.to_str().unwrap())],
        "/cron run brief\n/id\n/quit\n",
    );
    // `#442`: the child is pinned to the config this process read. It used to be told the profile
    // and not the config, so a composer started with `--config somewhere.toml` fired its job
    // against whatever the default path resolved to — found and listed here, run there.
    let expected_config = home.path().join("c.toml");
    assert!(
        said.contains(&format!(
            "stand-in ran: --config {} cron run brief",
            expected_config.display()
        )),
        "the job's child is told which config to read: {said}"
    );
    assert!(
        said.contains("exit code: 3"),
        "and its code is reported: {said}"
    );
    assert!(
        said.contains("(none yet)"),
        "the composer took the next command: {said}"
    );

    // An unknown name refuses, and says which names exist.
    let refused = repl_says(home.path(), config, "/cron run breg\n/quit\n");
    assert!(
        refused.contains("breg") && refused.contains("`brief`"),
        "{refused}"
    );
}

/// `#230`: adding a job is the CLI's, and the refusal names the command.
#[cfg(unix)]
#[test]
fn the_cron_verb_refuses_to_add_or_remove_and_names_the_cli() {
    let home = tempfile::tempdir().unwrap();
    let config = "[tools]\n";
    let said = repl_says(
        home.path(),
        config,
        "/cron add --name x\n/cron remove brief\n/quit\n",
    );
    assert!(said.contains("eclipse cron add"), "{said}");
    assert!(said.contains("eclipse cron remove"), "{said}");
    // Nothing was written: a refusal that still leaves a job behind is not a refusal.
    assert!(
        !home.path().join(".eclipse/cron/jobs.toml").exists(),
        "no job file was created"
    );
}

/// A REPL run on a scratch home with nothing typed at a terminal.
fn repl_says(home: &std::path::Path, config_toml: &str, input: &str) -> String {
    repl_says_env(home, config_toml, &[], input)
}

/// The same, with extra environment for the child.
fn repl_says_env(
    home: &std::path::Path,
    config_toml: &str,
    env: &[(&str, &str)],
    input: &str,
) -> String {
    let mut command = Command::new(env!("CARGO_BIN_EXE_eclipse"));
    command
        .env_clear()
        .env("HOME", home)
        .env("PATH", std::env::var("PATH").unwrap_or_default())
        .env("ECLIPSE_BASE_URL", "http://127.0.0.1:9/v1")
        .env("ECLIPSE_MODEL", "m")
        .env("NO_COLOR", "1")
        .env("ECLIPSE_CONFIG", home.join("c.toml"))
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    for (key, value) in env {
        command.env(key, value);
    }
    let mut child = command.spawn().unwrap();
    std::fs::write(home.join("c.toml"), config_toml).unwrap();
    {
        let stdin = child.stdin.as_mut().unwrap();
        write!(stdin, "{input}").unwrap();
        stdin.flush().unwrap();
    }
    drop(child.stdin.take());
    let out = child.wait_with_output().unwrap();
    format!(
        "{}\n--stderr--\n{}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr)
    )
}

/// `#588`: the listing someone reads just before typing `--all` is built from the model's own
/// arguments, so a control character in a path must not be able to redraw the terminal or fake a
/// second row. `approve.rs` already escaped these in the prompt; the listing did not.
#[cfg(unix)]
#[test]
fn the_approve_listing_escapes_what_the_model_wrote() {
    let home = tempfile::tempdir().unwrap();
    let waiting = home.path().join("waiting.json");
    let config = "[tools]\nwrite_file = \"ask\"\n[cli]\napproval = \"ask\"\n";
    let poisoned = "made\u{1b}[2K.txt\n 2. bash  rm -rf ~";

    let (base, _bodies, _server) = serve_replies(vec![tool_call_reply(
        "c1",
        "write_file",
        serde_json::json!({"path": poisoned, "content": "x"}),
    )]);

    let first = run_cmd(
        home.path(),
        config,
        &base,
        &[
            "run",
            "-s",
            "s1",
            "--approvals-out",
            waiting.to_str().unwrap(),
            "write made.txt",
        ],
    );
    assert_eq!(
        first.status.code(),
        Some(3),
        "a waiting run exits 3: {first:?}"
    );

    let listed = run_cmd(home.path(), config, &base, &["approve", "s1", "--list"]);
    assert!(listed.status.success(), "{listed:?}");
    let out = stdout(&listed);
    assert!(
        !out.contains('\u{1b}'),
        "an escape sequence reached the terminal: {out:?}"
    );
    assert!(
        !out.lines().any(|l| l.trim_start().starts_with("2. bash")),
        "a newline in the summary faked a second row: {out:?}"
    );
    assert!(
        out.contains("\\u{1b}") && out.contains("\\n"),
        "the escapes are shown as text, so the row stays one row: {out:?}"
    );
}

/// M13's done-when, end to end across two processes: a run that stops on a gate it cannot answer
/// leaves the call on record, `approve` resolves it, the resumed run really executes it, and the
/// transcript carries the approval as the tool result instead of "interrupted".
#[cfg(unix)]
#[test]
fn a_run_paused_on_an_approval_is_finished_by_approve_in_another_process() {
    let home = tempfile::tempdir().unwrap();
    let waiting = home.path().join("waiting.json");
    let config = "[tools]\nwrite_file = \"ask\"\n[cli]\napproval = \"ask\"\n";
    let target = home.path().join("made.txt");

    let (base, bodies, server) = serve_replies(vec![
        tool_call_reply(
            "c1",
            "write_file",
            serde_json::json!({"path": "made.txt", "content": "written after the approval"}),
        ),
        // The resumed turn: the call has run, so the model is asked once more for its answer.
        text_reply("done: made.txt is written"),
    ]);

    // ---- process 1: nobody to answer, so it stops with the call on record
    let first = run_cmd(
        home.path(),
        config,
        &base,
        &[
            "run",
            "-s",
            "s1",
            "--approvals-out",
            waiting.to_str().unwrap(),
            "write made.txt",
        ],
    );
    assert_eq!(
        first.status.code(),
        Some(3),
        "a waiting run exits 3, so a script can branch on it: {first:?}"
    );
    let err = String::from_utf8_lossy(&first.stderr).into_owned();
    assert!(
        err.contains("eclipse approve s1 --all"),
        "the hint has to name the command that resolves it: {err}"
    );
    assert!(!target.exists(), "a waiting call has not run");
    let set = std::fs::read_to_string(&waiting).expect("the waiting set is written");
    assert!(set.contains("c1") && set.contains("write_file"), "{set}");
    assert!(
        set.contains("made.txt"),
        "the arguments travel with the call: {set}"
    );

    // `--list` changes nothing, and says what is waiting.
    let listed = run_cmd(home.path(), config, &base, &["approve", "s1", "--list"]);
    assert!(listed.status.success(), "{listed:?}");
    assert!(
        stdout(&listed).contains("write_file") && stdout(&listed).contains("made.txt"),
        "{listed:?}"
    );

    // ---- process 2: answer it, and the run picks itself back up
    let approved = run_cmd(home.path(), config, &base, &["approve", "s1", "--all"]);
    server.join().unwrap();
    assert!(approved.status.success(), "{approved:?}");
    assert_eq!(
        std::fs::read_to_string(&target).expect("the approved call ran"),
        "written after the approval"
    );
    assert!(
        stdout(&approved).contains("done: made.txt is written"),
        "the resumed run finishes the turn: {approved:?}"
    );
    // The model read an approval, not an interruption.
    let sent: Vec<String> = bodies.iter().collect();
    assert_eq!(sent.len(), 2, "one call, one follow-up");
    assert!(
        sent[1].contains("written after the approval") && !sent[1].contains("interrupted"),
        "the transcript's tool result is what the tool said: {}",
        sent[1]
    );

    // ---- and the answer is spent: a second approve has nothing to do. A dead base proves it
    // never asks the model: nothing was waiting, so there is no turn to continue.
    let again = run_cmd(
        home.path(),
        config,
        &dead_base(),
        &["approve", "s1", "--all"],
    );
    assert!(again.status.success(), "{again:?}");
    assert!(
        stdout(&again).contains("nothing was waiting"),
        "a resolved run is not resumed twice: {again:?}"
    );
}

/// A denial is a decision with a reason, and it travels to the model as one.
#[cfg(unix)]
#[test]
fn an_approve_deny_reaches_the_model_as_the_reason_and_runs_nothing() {
    let home = tempfile::tempdir().unwrap();
    let config = "[tools]\nwrite_file = \"ask\"\n[cli]\napproval = \"ask\"\n";
    let target = home.path().join("made.txt");

    let (base, bodies, server) = serve_replies(vec![
        tool_call_reply(
            "c1",
            "write_file",
            serde_json::json!({"path": "made.txt", "content": "never written"}),
        ),
        text_reply("understood, I will not"),
    ]);
    let first = run_cmd(
        home.path(),
        config,
        &base,
        &[
            "run",
            "-s",
            "s2",
            "--approvals-out",
            "/dev/null",
            "write made.txt",
        ],
    );
    assert_eq!(first.status.code(), Some(3), "{first:?}");

    let denied = run_cmd(
        home.path(),
        config,
        &base,
        &[
            "approve",
            "s2",
            "--all",
            "--deny",
            "that file is not mine to write",
        ],
    );
    server.join().unwrap();
    assert!(denied.status.success(), "{denied:?}");
    assert!(!target.exists(), "a denied call runs nothing");
    let sent: Vec<String> = bodies.iter().collect();
    assert!(
        sent[1].contains("declined") && sent[1].contains("not mine to write"),
        "the model reads the reason: {}",
        sent[1]
    );
}

/// `--index` counts from one and refuses a number that is not waiting, before writing anything.
#[cfg(unix)]
#[test]
fn approve_refuses_an_index_that_is_not_waiting_and_changes_nothing() {
    let home = tempfile::tempdir().unwrap();
    let config = "[tools]\nwrite_file = \"ask\"\n[cli]\napproval = \"ask\"\n";
    let (base, _bodies, server) = serve_replies(vec![tool_call_reply(
        "c1",
        "write_file",
        serde_json::json!({"path": "made.txt", "content": "x"}),
    )]);
    let first = run_cmd(
        home.path(),
        config,
        &base,
        &["run", "-s", "s3", "--approvals-out", "/dev/null", "write"],
    );
    server.join().unwrap();
    assert_eq!(first.status.code(), Some(3), "{first:?}");

    let out = run_cmd(
        home.path(),
        config,
        "http://127.0.0.1:9/v1",
        &["approve", "s3", "--index", "2"],
    );
    assert!(!out.status.success(), "there is no second call: {out:?}");
    let err = String::from_utf8_lossy(&out.stderr).into_owned();
    assert!(err.contains("does not exist"), "{err}");

    // Still waiting, with nothing answered.
    let listed = run_cmd(
        home.path(),
        config,
        "http://127.0.0.1:9/v1",
        &["approve", "s3"],
    );
    assert!(stdout(&listed).contains("write_file"), "{listed:?}");
}

// ---- M15: structured output ---------------------------------------------------------------

/// A schema on the command line shapes the request and judges the reply; what comes back on
/// stdout is the document, because that is what a shell can hand to `jq`.
#[cfg(unix)]
#[test]
fn a_schema_run_sends_the_schema_and_prints_the_json_reply() {
    let home = tempfile::tempdir().unwrap();
    let config = "[tools]\nwrite_file = \"allow\"\n";
    let (base, bodies, server) = serve_replies(vec![text_reply(
        r#"{"goal": "ship M15", "steps": ["ask", "parse"]}"#,
    )]);

    let out = run_cmd(
        home.path(),
        config,
        &base,
        &[
            "run",
            "-s",
            "s1",
            "--schema",
            r#"{"type":"object","required":["goal","steps"]}"#,
            "plan it",
        ],
    );
    server.join().unwrap();
    assert!(
        out.status.success(),
        "a JSON reply is not a failure: {out:?}"
    );
    // The reply is printed as it came, so a pipe can read it.
    let doc: serde_json::Value = serde_json::from_str(stdout(&out).trim())
        .expect("stdout is the JSON document, not prose about it");
    assert_eq!(doc["goal"], "ship M15");

    // ...and the request asked for that shape, in the wire's own spelling.
    let sent: Vec<String> = bodies.iter().collect();
    assert_eq!(sent.len(), 1);
    let body: serde_json::Value = serde_json::from_str(&sent[0]).unwrap();
    assert_eq!(body["response_format"]["type"], "json_schema");
    assert_eq!(
        body["response_format"]["json_schema"]["schema"]["required"][0],
        "goal"
    );
}

/// A backend that ignores `response_format` gets one retry carrying the parse error, and then a
/// status of its own — not a silent empty value, and not a success with prose in it.
#[cfg(unix)]
#[test]
fn a_prose_reply_is_retried_once_with_the_error_then_exits_4() {
    let home = tempfile::tempdir().unwrap();
    let config = "[tools]\nwrite_file = \"allow\"\n";
    let (base, bodies, server) = serve_replies(vec![
        text_reply("Sure! Here is your plan: ship it."),
        text_reply("Still prose, I am afraid."),
    ]);

    let out = run_cmd(
        home.path(),
        config,
        &base,
        &[
            "run",
            "-s",
            "s2",
            "--schema",
            r#"{"type":"object"}"#,
            "plan it",
        ],
    );
    server.join().unwrap();
    assert_eq!(
        out.status.code(),
        Some(4),
        "a parse failure has its own status: {out:?}"
    );
    let err = String::from_utf8_lossy(&out.stderr).into_owned();
    assert!(
        err.contains("did not match the schema") && err.contains("Still prose"),
        "the refusal says what was expected and what it said instead: {err}"
    );

    // Exactly two requests, and the second one carried the error back to the model.
    let sent: Vec<String> = bodies.iter().collect();
    assert_eq!(sent.len(), 2, "one answer and one retry, no more");
    let second: serde_json::Value = serde_json::from_str(&sent[1]).unwrap();
    let last = second["messages"].as_array().unwrap().last().unwrap();
    assert_eq!(last["role"], "user");
    assert!(
        last["content"]
            .as_str()
            .unwrap_or_default()
            .contains("does not match the JSON schema"),
        "the retry's feedback is the parse error: {last}"
    );
}

/// A schema path that does not exist fails before a request is sent, and says which path.
#[cfg(unix)]
#[test]
fn a_missing_schema_file_is_reported_before_any_request() {
    let home = tempfile::tempdir().unwrap();
    let out = run_cmd(
        home.path(),
        "[tools]\nwrite_file = \"allow\"\n",
        &dead_base(),
        &["run", "--schema", "no/such/schema.json", "plan it"],
    );
    assert!(!out.status.success());
    let err = String::from_utf8_lossy(&out.stderr).into_owned();
    assert!(err.contains("no/such/schema.json"), "{err}");
}

/// A job may demand a shape. The schema is stored in the job file, sent as `response_format`, and
/// a backend that answers in prose fails the job — which is the whole reason to put a shape on an
/// unattended prompt: nobody reads the log at 07:30 to notice a shrug.
#[cfg(unix)]
#[test]
fn a_cron_job_with_a_schema_fails_when_the_answer_is_prose() {
    let home = tempfile::tempdir().unwrap();
    let config = "[tools]\nwrite_file = \"allow\"\n";
    let (base, bodies, server) = serve_replies(vec![
        text_reply("Sure! Here is your headline."),
        text_reply("Still prose, sorry."),
    ]);

    let added = run_cmd(
        home.path(),
        config,
        &base,
        &[
            "cron",
            "add",
            "--name",
            "shaped",
            "--schedule",
            "every 1m",
            "--prompt",
            "summarise the news",
            "--schema",
            r#"{"type":"object","required":["headline"]}"#,
        ],
    );
    assert!(added.status.success(), "{added:?}");
    let jobs = std::fs::read_to_string(home.path().join(".eclipse/cron/jobs.toml")).unwrap();
    assert!(jobs.contains("schema = "), "the schema is kept: {jobs}");

    let ran = run_cmd(home.path(), config, &base, &["cron", "run", "shaped"]);
    server.join().unwrap();
    assert_eq!(
        ran.status.code(),
        Some(1),
        "a job whose answer was prose has failed: {ran:?}"
    );

    // The job's own schema went out on the wire, not the machine-wide default.
    let sent: Vec<String> = bodies.iter().collect();
    assert_eq!(sent.len(), 2, "one answer and the one retry M15 promises");
    let body: serde_json::Value = serde_json::from_str(&sent[0]).unwrap();
    assert_eq!(body["response_format"]["type"], "json_schema");
    assert_eq!(
        body["response_format"]["json_schema"]["schema"]["required"][0], "headline",
        "{body}"
    );

    // And the run log carries the failure, with the parse error, where the next reader looks.
    let runs = home.path().join(".eclipse/cron/runs/shaped");
    let log = std::fs::read_dir(&runs).unwrap().next().unwrap().unwrap();
    let text = std::fs::read_to_string(log.path()).unwrap();
    assert!(text.contains("# shaped — failed"), "{text}");
    assert!(text.contains("schema"), "the log says why: {text}");
}

/// `--workdir` is where the job's tools run. It was parsed, stored and written to `jobs.toml`, and
/// nothing read it: a job scoped to a directory wrote into the default workspace instead, while the
/// flag read as working.
#[cfg(unix)]
#[test]
fn a_cron_job_starts_in_the_directory_it_was_given() {
    let home = tempfile::tempdir().unwrap();
    let notes = home.path().join("notes");
    std::fs::create_dir_all(&notes).unwrap();
    let config = "[tools]\nwrite_file = \"allow\"\n";
    let (base, _bodies, server) = serve_replies(vec![
        tool_call_reply(
            "c1",
            "write_file",
            serde_json::json!({"path": "where.txt", "content": "here"}),
        ),
        text_reply("wrote it"),
    ]);

    let added = run_cmd(
        home.path(),
        config,
        &base,
        &[
            "cron",
            "add",
            "--name",
            "scoped",
            "--schedule",
            "every 1m",
            "--prompt",
            "write where.txt",
            "--workdir",
            notes.to_str().unwrap(),
        ],
    );
    assert!(added.status.success(), "{added:?}");

    let ran = run_cmd(home.path(), config, &base, &["cron", "run", "scoped"]);
    server.join().unwrap();
    assert!(ran.status.success(), "{ran:?}");
    assert!(
        notes.join("where.txt").is_file(),
        "the job's own directory is where its files land: {:?}",
        ran
    );
}

/// A directory that does not exist is caught at `add`: a job that starts somewhere else than the
/// person asked is worse than a job that refuses to be written.
#[cfg(unix)]
#[test]
fn a_cron_job_refuses_a_workdir_that_is_not_a_directory() {
    let home = tempfile::tempdir().unwrap();
    let missing = home.path().join("no/such/place");
    let out = run_cmd(
        home.path(),
        "",
        "http://127.0.0.1:1/v1",
        &[
            "cron",
            "add",
            "--name",
            "nowhere",
            "--schedule",
            "every 1m",
            "--prompt",
            "touch things",
            "--workdir",
            missing.to_str().unwrap(),
        ],
    );
    assert!(!out.status.success());
    let err = String::from_utf8_lossy(&out.stderr).into_owned();
    assert!(err.contains("no/such/place"), "{err}");
    assert!(
        !home.path().join(".eclipse/cron/jobs.toml").exists(),
        "nothing is written for a job that could never run where it was told"
    );
}

/// `#598`: two ticks over one state dir run each due job once, and the counters are the ones the
/// tick that ran them wrote.
///
/// The tick read the state that decides what is due *before* it took the lock, so a tick could read
/// just before another one recorded its run, wait for the lock, find it free, and decide from a
/// snapshot that still said "never run": the same job went twice, and the second tick wrote its
/// older copy of `cron.json` over the first one's counters. That window is microseconds wide in
/// real life, so this test holds it open: the second tick's state read is a FIFO, and the first
/// tick is frozen with `SIGSTOP` while the test installs it, so neither can get out of step while
/// the window is being built.
#[cfg(unix)]
#[test]
fn two_ticks_over_one_state_dir_run_each_job_once() {
    use std::os::unix::fs::PermissionsExt;

    let home = tempfile::tempdir().unwrap();
    let root = home.path().join(".eclipse");
    std::fs::create_dir_all(root.join("cron")).unwrap();
    std::fs::create_dir_all(root.join("state")).unwrap();
    std::fs::write(
        root.join("cron/jobs.toml"),
        "[[job]]\nname = \"alpha\"\nschedule = \"every 1m\"\nprompt = \"first\"\n\n\
         [[job]]\nname = \"beta\"\nschedule = \"every 1m\"\nprompt = \"second\"\n",
    )
    .unwrap();
    let cfg = home.path().join("c.toml");
    std::fs::write(&cfg, "[provider]\nmax_retries = 0\n").unwrap();

    // Answers arrive slowly, which is what gives the test time to build the window while the first
    // tick is inside a job with the lock held.
    let (base, asked, _server) = serve_slowly(Duration::from_millis(400));
    let spawn = |args: &[&str]| {
        Command::new(env!("CARGO_BIN_EXE_eclipse"))
            .args(["--config", cfg.to_str().unwrap()])
            .args(args)
            .current_dir(home.path())
            .env_clear()
            .env("HOME", home.path())
            .env("PATH", "/usr/bin:/bin")
            .env("TERM", "xterm-256color")
            .env("ECLIPSE_BASE_URL", &base)
            .env("ECLIPSE_MODEL", "m")
            .stdin(Stdio::null())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
            .unwrap()
    };

    let first = spawn(&["cron", "run"]);
    asked
        .recv_timeout(Duration::from_secs(20))
        .expect("the first tick never asked the model anything");
    assert!(
        root.join("state/cron.lock").exists(),
        "the first tick is not holding the lock while it runs a job"
    );
    // Frozen, so it cannot save `cron.json` over the FIFO between the two lines below.
    signal(first.id(), libc::SIGSTOP);

    let state_path = root.join("state/cron.json");
    std::fs::remove_file(&state_path).unwrap();
    let fifo = std::ffi::CString::new(state_path.to_str().unwrap()).unwrap();
    // SAFETY: a path in a directory this test made, passed as a NUL-terminated string.
    assert_eq!(unsafe { libc::mkfifo(fifo.as_ptr(), 0o600) }, 0);
    assert_eq!(
        std::fs::metadata(&state_path).unwrap().permissions().mode() & 0o170000,
        0o010000,
        "the state path is not a FIFO"
    );

    let second = spawn(&["cron", "run"]);

    // A writer's open of a FIFO returns only once a reader has it open: this is the second tick
    // saying it is about to read its state, and it is now inside the window the audit described.
    let (opened, seen_open) = mpsc::channel();
    let fifo_for_thread = state_path.clone();
    std::thread::spawn(move || {
        let file = std::fs::OpenOptions::new()
            .write(true)
            .open(&fifo_for_thread)
            .unwrap();
        let _ = opened.send(file);
    });
    let mut writer = seen_open
        .recv_timeout(Duration::from_secs(20))
        .expect("the second tick never opened its state file");

    // The first tick finishes both jobs, records them and lets go of the lock.
    signal(first.id(), libc::SIGCONT);
    let done = first.wait_with_output().unwrap();
    assert!(done.status.success(), "{done:?}");

    // Only now does the second tick's read return — with the empty state a tick starting a moment
    // before the first one would have taken, which says both jobs have still never run.
    writer.write_all(b"{\"jobs\":{}}").unwrap();
    drop(writer);

    let second = second.wait_with_output().unwrap();
    assert!(second.status.success(), "{second:?}");

    let runs = |job: &str| {
        std::fs::read_dir(root.join("cron/runs").join(job))
            .map(|entries| entries.flatten().count())
            .unwrap_or(0)
    };
    assert_eq!(
        (runs("alpha"), runs("beta")),
        (1, 1),
        "a tick decided from a state it had read before the other tick recorded its run, so a job \
         ran twice: {}",
        stdout(&second)
    );

    // And the record is the record: one entry per run that happened, written by the tick that ran
    // it rather than by the one holding the older snapshot.
    let state: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(&state_path).unwrap()).unwrap();
    for job in ["alpha", "beta"] {
        assert_eq!(
            state["jobs"][job]["runs"].as_u64(),
            Some(1),
            "{job}'s count does not match the one run it had: {state}"
        );
        assert_eq!(
            state["jobs"][job]["last_outcome"].as_str(),
            Some("ok"),
            "{job}'s outcome was overwritten: {state}"
        );
        assert!(
            state["jobs"][job]["last_finished_ms"].as_i64().is_some(),
            "{job} finished but the record does not say when: {state}"
        );
    }
}

/// Answer chat requests after `delay`, and say when one arrives: the caller wants to know the
/// moment a tick is inside a job, which `serve_turns` does not report.
#[cfg(unix)]
fn serve_slowly(delay: Duration) -> (String, mpsc::Receiver<()>, std::thread::JoinHandle<()>) {
    let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
    let base = format!("http://{}/v1", listener.local_addr().unwrap());
    let (tx, rx) = mpsc::channel::<()>();
    let handle = std::thread::spawn(move || {
        for conn in listener.incoming() {
            let Ok(mut s) = conn else { return };
            let mut head = Vec::new();
            let mut chunk = [0u8; 4096];
            while !head.windows(4).any(|w| w == b"\r\n\r\n") {
                match s.read(&mut chunk) {
                    Ok(0) | Err(_) => break,
                    Ok(n) => head.extend_from_slice(&chunk[..n]),
                }
            }
            let text = String::from_utf8_lossy(&head).into_owned();
            if !(text.starts_with("POST")
                && text.to_ascii_lowercase().contains("/chat/completions"))
            {
                let body = "{\"data\":[{ \"id\": \"m\" }]}";
                let _ = write!(
                    s,
                    "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
                    body.len()
                );
                continue;
            }
            let _ = tx.send(());
            std::thread::sleep(delay);
            let body = serde_json::json!({
                "choices": [{"message": {"role": "assistant", "content": "done"}, "finish_reason": "stop"}]
            })
            .to_string();
            let _ = write!(
                s,
                "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
                body.len()
            );
        }
    });
    (base, rx, handle)
}

/// The pane and the terminal read one struct: `cron list --json` is the same shape the dashboard
/// renders, so a field added for the page cannot exist only in the page.
#[test]
fn cron_list_json_is_the_struct_the_dashboard_renders() {
    let home = tempfile::tempdir().unwrap();
    let added = run_cmd(
        home.path(),
        "",
        "http://127.0.0.1:1/v1",
        &[
            "cron",
            "add",
            "--name",
            "brief",
            "--schedule",
            "daily 07:30",
            "--prompt",
            "brief me",
        ],
    );
    assert!(
        added.status.success(),
        "{}",
        String::from_utf8_lossy(&added.stderr)
    );

    let out = run_cmd(
        home.path(),
        "",
        "http://127.0.0.1:1/v1",
        &["cron", "list", "--json"],
    );
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    let parsed: serde_json::Value = serde_json::from_slice(&out.stdout).expect("json on stdout");
    let jobs = parsed["jobs"].as_array().expect("a jobs array");
    assert_eq!(jobs.len(), 1, "{parsed}");
    assert_eq!(jobs[0]["name"], "brief");
    assert_eq!(jobs[0]["schedule"], "daily 07:30");
    assert_eq!(jobs[0]["prompt"], "brief me");
    assert_eq!(jobs[0]["enabled"], true);
    assert!(jobs[0]["next_ms"].as_i64().is_some(), "{parsed}");
    assert!(parsed["now_ms"].as_i64().unwrap_or(0) > 0);
    assert!(
        parsed["jobs_file"]
            .as_str()
            .unwrap_or("")
            .ends_with("jobs.toml"),
        "{parsed}"
    );
}

/// Switching a job off is not removing it: the file keeps the prompt, and `--json` says so.
#[test]
fn cron_disable_keeps_the_job_and_enable_brings_it_back() {
    let home = tempfile::tempdir().unwrap();
    let added = run_cmd(
        home.path(),
        "",
        "http://127.0.0.1:1/v1",
        &[
            "cron",
            "add",
            "--name",
            "brief",
            "--schedule",
            "hourly",
            "--prompt",
            "brief me",
        ],
    );
    assert!(added.status.success());

    let off = run_cmd(
        home.path(),
        "",
        "http://127.0.0.1:1/v1",
        &["cron", "disable", "brief"],
    );
    assert!(
        off.status.success(),
        "{}",
        String::from_utf8_lossy(&off.stderr)
    );
    let out = run_cmd(
        home.path(),
        "",
        "http://127.0.0.1:1/v1",
        &["cron", "list", "--json"],
    );
    let parsed: serde_json::Value = serde_json::from_slice(&out.stdout).expect("json");
    assert_eq!(parsed["jobs"][0]["enabled"], false, "{parsed}");
    assert_eq!(parsed["jobs"][0]["prompt"], "brief me");
    assert!(
        parsed["jobs"][0]["next_ms"].is_null(),
        "a disabled job has no next fire"
    );

    let on = run_cmd(
        home.path(),
        "",
        "http://127.0.0.1:1/v1",
        &["cron", "enable", "brief"],
    );
    assert!(on.status.success());
    let out = run_cmd(
        home.path(),
        "",
        "http://127.0.0.1:1/v1",
        &["cron", "list", "--json"],
    );
    let parsed: serde_json::Value = serde_json::from_slice(&out.stdout).expect("json");
    assert_eq!(parsed["jobs"][0]["enabled"], true);

    let missing = run_cmd(
        home.path(),
        "",
        "http://127.0.0.1:1/v1",
        &["cron", "disable", "nope"],
    );
    assert!(!missing.status.success());
    let err = String::from_utf8_lossy(&missing.stderr);
    assert!(err.contains("no job named `nope`"), "{err}");
}

/// `cron logs --json`: the answer, the text, and how much of it was left on disk.
#[test]
fn cron_logs_json_hands_over_the_answer_and_the_text() {
    let home = tempfile::tempdir().unwrap();
    let added = run_cmd(
        home.path(),
        "",
        "http://127.0.0.1:1/v1",
        &[
            "cron",
            "add",
            "--name",
            "brief",
            "--schedule",
            "hourly",
            "--prompt",
            "brief me",
        ],
    );
    assert!(added.status.success());
    let runs = home.path().join(".eclipse/cron/runs/brief");
    std::fs::create_dir_all(&runs).unwrap();
    std::fs::write(
        runs.join("1700000000000.md"),
        "# brief \u{2014} 2026-11-14 22:13\n\nschedule every 1h\n\n---\n\nthe answer\n",
    )
    .unwrap();

    let out = run_cmd(
        home.path(),
        "",
        "http://127.0.0.1:1/v1",
        &["cron", "logs", "brief", "--json"],
    );
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    let parsed: serde_json::Value = serde_json::from_slice(&out.stdout).expect("json");
    assert_eq!(parsed["job"], "brief");
    let runs = parsed["runs"].as_array().expect("runs");
    assert_eq!(runs.len(), 1, "{parsed}");
    assert_eq!(runs[0]["answer"], "the answer");
    assert_eq!(runs[0]["truncated"], false);
    assert!(runs[0]["text"].as_str().unwrap().contains("the answer"));
    assert!(runs[0]["path"]
        .as_str()
        .unwrap()
        .ends_with("1700000000000.md"));
}

/// `--no-mcp` takes the servers out of the process, not out of a menu: with the flag nothing is
/// spawned and nothing is reported, so a server that hangs or is missing cannot cost a startup.
#[cfg(unix)]
#[test]
fn no_mcp_means_no_server_is_started_and_nothing_is_reported() {
    let home = tempfile::tempdir().unwrap();
    let plugins = home.path().join("plugins");
    std::fs::create_dir_all(plugins.join("dead")).unwrap();
    std::fs::write(
        plugins.join("dead").join("plugin.toml"),
        "name = \"dead\"\n\n[[mcp]]\nname = \"gone\"\ncommand = \"/nonexistent/server\"\n",
    )
    .unwrap();
    let config = format!(
        "[plugins]\ndir = \"{}\"\nenabled = [\"dead\"]\n",
        plugins.display()
    );

    let without = run_cmd(home.path(), &config, &dead_base(), &["tools", "list"]);
    let with = run_cmd(
        home.path(),
        &config,
        &dead_base(),
        &["--no-mcp", "tools", "list"],
    );
    let said = |out: &std::process::Output| {
        format!(
            "{}{}",
            stdout(out),
            String::from_utf8_lossy(&out.stderr).into_owned()
        )
    };
    let a = said(&without);
    assert!(
        a.contains("gone") || a.contains("nonexistent"),
        "the broken server is reported when MCP is on: {a}"
    );
    let b = said(&with);
    assert!(
        !b.contains("gone") && !b.contains("nonexistent"),
        "--no-mcp still mentioned the server it was told to skip: {b}"
    );
}

/// A status subcommand exists so a script can branch on it. `systemctl is-active` answering
/// `inactive` (exit 3) printed a line and returned success — exit 0 for a gateway that is down.
#[cfg(unix)]
#[test]
fn gateway_status_exits_non_zero_when_the_unit_is_down() {
    use std::os::unix::fs::PermissionsExt;

    let home = tempfile::tempdir().unwrap();
    let bin = tempfile::tempdir().unwrap();
    let fake = bin.path().join("systemctl");
    let write_fake = |body: &str| {
        std::fs::write(&fake, body).unwrap();
        std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
    };
    let run_status = || {
        Command::new(env!("CARGO_BIN_EXE_eclipse"))
            .args(["gateway", "status"])
            .env_clear()
            .env("HOME", home.path())
            .env("NO_COLOR", "1")
            .env("PATH", bin.path())
            .output()
            .unwrap()
    };

    // Down: systemctl says so with its own exit status, and the CLI must not call that success.
    write_fake("#!/bin/sh\necho inactive\nexit 3\n");
    let out = run_status();
    assert_eq!(
        out.status.code(),
        Some(1),
        "a gateway that is not running is a failure for a script: {out:?}"
    );
    assert!(stdout(&out).contains("inactive"), "{}", stdout(&out));

    // Up: the same call is a success.
    write_fake("#!/bin/sh\necho active\nexit 0\n");
    let out = run_status();
    assert!(out.status.success(), "{out:?}");
    assert!(stdout(&out).contains("is up"), "{}", stdout(&out));
}

/// One shared shape for the three unit commands: a fake `systemctl` on `PATH` that answers whatever
/// the test needs, and a HOME with no units in it.
#[cfg(unix)]
fn with_fake_systemctl(exits_zero: bool, args: &[&str]) -> (Output, tempfile::TempDir) {
    use std::os::unix::fs::PermissionsExt;

    // The fake lives inside the same temp dir as HOME, so one TempDir owns both and nothing leaks.
    let home = tempfile::tempdir().unwrap();
    let bin = home.path().join("fake-bin");
    std::fs::create_dir_all(&bin).unwrap();
    let fake = bin.join("systemctl");
    std::fs::write(
        &fake,
        if exits_zero {
            "#!/bin/sh\nexit 0\n"
        } else {
            "#!/bin/sh\necho 'Failed to disable unit: Interactive authentication required.' >&2\nexit 1\n"
        },
    )
    .unwrap();
    std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
    let out = Command::new(env!("CARGO_BIN_EXE_eclipse"))
        .args(args)
        .env_clear()
        .env("HOME", home.path())
        .env("NO_COLOR", "1")
        .env("PATH", &bin)
        .output()
        .unwrap();
    (out, home)
}

/// `stop` ignored the `disable --now` status and printed "stopped and disabled" either way: a
/// gateway that refused to stop looked like a successful one.
#[cfg(unix)]
#[test]
fn gateway_stop_says_it_failed_when_systemctl_did_not_take_it() {
    let (out, _home) = with_fake_systemctl(false, &["gateway", "stop"]);
    assert!(
        !out.status.success(),
        "a stop that did not happen is not a success: {out:?}"
    );
    let err = String::from_utf8_lossy(&out.stderr);
    assert!(
        err.contains("may still be running"),
        "the failure says what state the gateway may be in: {err}"
    );
    assert!(
        !stdout(&out).contains("stopped and disabled"),
        "and it does not claim it stopped: {}",
        stdout(&out)
    );

    let (out, _home) = with_fake_systemctl(true, &["gateway", "stop"]);
    assert!(out.status.success(), "{out:?}");
    assert!(stdout(&out).contains("stopped and disabled"));
}

/// `start` is the inverse of `stop`: `enable --now`, never a `disable`, and no unit rewrite. The
/// argv is what the test reads, because the tempting implementation — "restart is stop then
/// start" — would disable the unit that the next reboot needs.
#[cfg(unix)]
#[test]
fn gateway_start_enables_and_never_disables() {
    use std::os::unix::fs::PermissionsExt;

    let home = tempfile::tempdir().unwrap();
    let unit = home
        .path()
        .join(".config/systemd/user/eclipse-gateway.service");
    std::fs::create_dir_all(unit.parent().unwrap()).unwrap();
    std::fs::write(&unit, "[Unit]\nDescription=test\n").unwrap();
    let bin = home.path().join("fake-bin");
    std::fs::create_dir_all(&bin).unwrap();
    let log = home.path().join("calls.txt");
    // Inactive until the enable lands, active afterwards: a `start` that reported success without
    // watching the unit settle would pass the first half and fail this one.
    std::fs::write(
        bin.join("systemctl"),
        format!(
            "#!/bin/sh\nprintf '%s\\n' \"$*\" >> {log}\n\
             case \"$*\" in\n  *is-active*)\n    \
             if grep -q enable {log}; then echo active; exit 0; fi\n    \
             echo inactive; exit 3;;\nesac\nexit 0\n",
            log = log.display()
        ),
    )
    .unwrap();
    std::fs::set_permissions(
        bin.join("systemctl"),
        std::fs::Permissions::from_mode(0o755),
    )
    .unwrap();

    let out = Command::new(env!("CARGO_BIN_EXE_eclipse"))
        .args(["gateway", "start"])
        .env_clear()
        .env("HOME", home.path())
        .env("NO_COLOR", "1")
        // The fake first, so it wins; the system dirs behind it for `grep` inside the fake.
        .env("PATH", format!("{}:/usr/bin:/bin", bin.display()))
        .output()
        .unwrap();
    assert!(out.status.success(), "{out:?}");
    assert!(
        stdout(&out).contains("started and enabled"),
        "{}",
        stdout(&out)
    );

    let calls = std::fs::read_to_string(&log).unwrap();
    assert!(
        calls.contains("--user enable --now eclipse-gateway.service"),
        "the unit has to be enabled as well as started: {calls}"
    );
    assert!(
        !calls.contains("disable"),
        "start must never disable what it starts: {calls}"
    );
    assert!(
        !calls.contains("daemon-reload") && !calls.contains("install"),
        "start does not rewrite the unit: {calls}"
    );
}

/// With no unit on disk, `start` names `install` and does not guess a profile: writing a unit
/// takes the `--profile`/`--config` the person has to choose.
#[cfg(unix)]
#[test]
fn gateway_start_refuses_when_nothing_is_installed() {
    let (out, _home) = with_fake_systemctl(true, &["gateway", "start"]);
    assert!(!out.status.success(), "{out:?}");
    let err = String::from_utf8_lossy(&out.stderr);
    assert!(err.contains("eclipse gateway install"), "{err}");
}

/// `stop` is `disable --now`, so the obvious `systemctl start` afterwards comes back for one boot
/// and then vanishes. The command that restores both halves is the line this guards.
#[cfg(unix)]
#[test]
fn gateway_stop_says_how_to_come_back() {
    let (out, _home) = with_fake_systemctl(true, &["gateway", "stop"]);
    assert!(out.status.success(), "{out:?}");
    assert!(
        stdout(&out).contains("eclipse gateway start"),
        "{}",
        stdout(&out)
    );
}

/// `cron install-timer` wrote both units, failed to enable the timer, printed the manual steps and
/// exited 0 — a provisioning script saw a working schedule that does not tick.
#[cfg(unix)]
#[test]
fn cron_install_timer_fails_when_the_timer_cannot_be_enabled() {
    let (out, home) = with_fake_systemctl(false, &["cron", "install-timer"]);
    assert!(
        !out.status.success(),
        "a timer that is written but not enabled is a failed install: {out:?}"
    );
    // The files are still written — the error is about enabling, and it names the directory.
    let unit = home
        .path()
        .join(".config/systemd/user/eclipse-cron.service");
    assert!(unit.is_file(), "the unit still lands on disk: {out:?}");
    let err = String::from_utf8_lossy(&out.stderr);
    assert!(
        err.contains("did not enable the timer"),
        "stderr names what failed: {err}"
    );
    assert!(
        stdout(&out).contains("systemctl --user enable --now eclipse-cron.timer"),
        "stdout carries the two commands to run: {}",
        stdout(&out)
    );
}

/// The same rule for the gateway unit. Needs the sibling `eclipse-gateway` binary, which the gate
/// builds (`verify.sh` builds the workspace before the tests), so a tree that only built this crate
/// says so instead of failing for the wrong reason.
#[cfg(unix)]
#[test]
fn gateway_install_fails_when_the_unit_cannot_be_enabled() {
    let beside =
        std::path::Path::new(env!("CARGO_BIN_EXE_eclipse")).with_file_name("eclipse-gateway");
    if !beside.is_file() {
        eprintln!(
            "skipped: {} is not built (run ./verify.sh)",
            beside.display()
        );
        return;
    }
    let (out, home) = with_fake_systemctl(false, &["gateway", "install"]);
    assert!(
        !out.status.success(),
        "a unit that is written but not enabled is a failed install: {out:?}"
    );
    assert!(
        home.path()
            .join(".config/systemd/user/eclipse-gateway.service")
            .is_file(),
        "the unit is still written, so the message can point at it: {out:?}"
    );
    let err = String::from_utf8_lossy(&out.stderr);
    assert!(err.contains("did not enable it"), "{err}");
}

/// A `systemctl` that answers `is-active` and `is-enabled` from what the test says, and records every
/// argv — so "did it restart" is an assertion about the calls, not an inference from the printed line.
#[cfg(unix)]
fn fake_systemd(
    home: &std::path::Path,
    active: bool,
    enabled: bool,
) -> (std::path::PathBuf, std::path::PathBuf) {
    use std::os::unix::fs::PermissionsExt;

    let bin = home.join("fake-bin");
    std::fs::create_dir_all(&bin).unwrap();
    let log = home.join("calls.txt");
    let (active_word, active_code) = if active {
        ("active", 0)
    } else {
        ("inactive", 3)
    };
    let (enabled_word, enabled_code) = if enabled {
        ("enabled", 0)
    } else {
        ("disabled", 1)
    };
    std::fs::write(
        bin.join("systemctl"),
        format!(
            "#!/bin/sh\nprintf '%s\\n' \"$*\" >> {log}\n\
             case \"$*\" in\n\
             \t*is-active*) echo {active_word}; exit {active_code};;\n\
             \t*is-enabled*) echo {enabled_word}; exit {enabled_code};;\n\
             esac\nexit 0\n",
            log = log.display()
        ),
    )
    .unwrap();
    std::fs::set_permissions(
        bin.join("systemctl"),
        std::fs::Permissions::from_mode(0o755),
    )
    .unwrap();
    (bin, log)
}

#[cfg(unix)]
fn run_gateway(home: &std::path::Path, bin: &std::path::Path, args: &[&str]) -> Output {
    Command::new(env!("CARGO_BIN_EXE_eclipse"))
        .args(args)
        .env_clear()
        .env("HOME", home)
        .env("NO_COLOR", "1")
        .env("PATH", format!("{}:/usr/bin:/bin", bin.display()))
        .output()
        .unwrap()
}

/// `#603`: `start` returned on `is_active()` alone, so a gateway that was running but never enabled
/// printed "already up; nothing to do" and then vanished at the next reboot.
#[cfg(unix)]
#[test]
fn gateway_start_enables_a_running_unit_that_was_never_enabled() {
    let home = tempfile::tempdir().unwrap();
    let unit = home
        .path()
        .join(".config/systemd/user/eclipse-gateway.service");
    std::fs::create_dir_all(unit.parent().unwrap()).unwrap();
    std::fs::write(&unit, "[Unit]\nDescription=test\n").unwrap();
    let (bin, log) = fake_systemd(home.path(), true, false);

    let out = run_gateway(home.path(), &bin, &["gateway", "start"]);
    assert!(out.status.success(), "{out:?}");
    assert!(
        stdout(&out).contains("enabled it so it survives a reboot"),
        "an active gateway that was never enabled is not \"nothing to do\": {}",
        stdout(&out)
    );

    let calls = std::fs::read_to_string(&log).unwrap();
    assert!(
        calls.contains("--user enable eclipse-gateway.service"),
        "the enable is the half that survives a reboot: {calls}"
    );
    assert!(
        !calls.contains("--now") && !calls.contains("restart"),
        "the process is already up; enabling must not bounce it: {calls}"
    );
}

/// And the unchanged half: running *and* enabled is still a no-op, with no `enable` in the log.
#[cfg(unix)]
#[test]
fn gateway_start_on_a_running_enabled_gateway_does_nothing() {
    let home = tempfile::tempdir().unwrap();
    let unit = home
        .path()
        .join(".config/systemd/user/eclipse-gateway.service");
    std::fs::create_dir_all(unit.parent().unwrap()).unwrap();
    std::fs::write(&unit, "[Unit]\nDescription=test\n").unwrap();
    let (bin, log) = fake_systemd(home.path(), true, true);

    let out = run_gateway(home.path(), &bin, &["gateway", "start"]);
    assert!(out.status.success(), "{out:?}");
    assert!(stdout(&out).contains("already up; nothing to do"));

    let calls = std::fs::read_to_string(&log).unwrap();
    assert!(
        !calls.contains("--user enable eclipse-gateway.service")
            && !calls.contains("--user restart eclipse-gateway.service"),
        "nothing to do means nothing done: {calls}"
    );
}

/// `#603`: `enable --now` is a no-op on an active unit, so re-running `install` after an upgrade left
/// the *old* process serving the *old* binary while the command reported the new unit as up.
#[cfg(unix)]
#[test]
fn gateway_install_restarts_a_running_gateway() {
    let beside =
        std::path::Path::new(env!("CARGO_BIN_EXE_eclipse")).with_file_name("eclipse-gateway");
    if !beside.is_file() {
        eprintln!(
            "skipped: {} is not built (run ./verify.sh)",
            beside.display()
        );
        return;
    }
    let home = tempfile::tempdir().unwrap();
    let (bin, log) = fake_systemd(home.path(), true, true);

    let out = run_gateway(home.path(), &bin, &["gateway", "install"]);
    assert!(out.status.success(), "{out:?}");
    assert!(
        stdout(&out).contains("restarted"),
        "an install over a running gateway says it replaced the process: {}",
        stdout(&out)
    );

    let calls = std::fs::read_to_string(&log).unwrap();
    assert!(
        calls.contains("--user restart eclipse-gateway.service"),
        "the running process is still the old one without this: {calls}"
    );
    assert!(
        calls.contains("--user enable --now eclipse-gateway.service"),
        "the unit is still enabled: {calls}"
    );
}

/// A stopped gateway was just started by `enable --now`; restarting it too would be a bounce nobody
/// asked for, and on a oneshot-style start it would double the boot work.
#[cfg(unix)]
#[test]
fn gateway_install_does_not_restart_a_stopped_gateway() {
    let beside =
        std::path::Path::new(env!("CARGO_BIN_EXE_eclipse")).with_file_name("eclipse-gateway");
    if !beside.is_file() {
        eprintln!(
            "skipped: {} is not built (run ./verify.sh)",
            beside.display()
        );
        return;
    }
    let home = tempfile::tempdir().unwrap();
    let (bin, log) = fake_systemd(home.path(), false, false);

    let out = run_gateway(home.path(), &bin, &["gateway", "install"]);
    assert!(out.status.success(), "{out:?}");
    assert!(stdout(&out).contains("enabled"), "{}", stdout(&out));

    let calls = std::fs::read_to_string(&log).unwrap();
    assert!(
        !calls.contains("restart"),
        "nothing was running, so nothing is bounced: {calls}"
    );
}

/// `--profile` used to change nothing about where the write went: `config set` edited the base file
/// every profile shares, while the profile's own overlay pinned the key — so the command printed the
/// overlay's old value and the profile kept serving it.
#[test]
fn config_set_with_a_profile_writes_the_overlay_that_actually_wins() {
    let home = tempfile::tempdir().unwrap();
    assert!(run(home.path(), &["config", "init"]).status.success());
    let base = home.path().join(".eclipse/config.toml");
    let before = std::fs::read_to_string(&base).unwrap();

    // What the profile serves today: its overlay pins the model.
    let overlay = home.path().join(".eclipse/profiles/work/config.toml");
    std::fs::create_dir_all(overlay.parent().unwrap()).unwrap();
    std::fs::write(&overlay, "[provider]\nmodel = \"old-model\"\n").unwrap();

    let out = run(
        home.path(),
        &[
            "--profile",
            "work",
            "config",
            "set",
            "provider.model",
            "new-model",
        ],
    );
    assert!(out.status.success(), "{out:?}");
    assert_eq!(
        std::fs::read_to_string(&base).unwrap(),
        before,
        "the base file is shared by every profile and does not change"
    );
    let written = std::fs::read_to_string(&overlay).unwrap();
    assert!(written.contains("model = \"new-model\""), "{written}");
    // The echo is what the profile will serve next, not the value it shadowed.
    let said = stdout(&out);
    assert!(
        said.contains("new-model") && said.contains(&overlay.display().to_string()),
        "{said}"
    );
    let keys = stdout(&run(home.path(), &["--profile", "work", "config", "keys"]));
    assert!(
        keys.contains("provider.model = \"new-model\""),
        "a fresh load under the profile agrees: {keys}"
    );

    // Unsetting goes to the same file, for the same reason.
    let out = run(
        home.path(),
        &["--profile", "work", "config", "unset", "provider.model"],
    );
    assert!(out.status.success(), "{out:?}");
    assert!(
        std::fs::read_to_string(&overlay)
            .unwrap()
            .contains("# model = \"new-model\""),
        "the overlay is where the line was commented out"
    );

    // A profile with no overlay yet gets one, rather than an error about the shared file.
    let fresh = home.path().join(".eclipse/profiles/fresh/config.toml");
    let out = run(
        home.path(),
        &["--profile", "fresh", "config", "set", "web.port", "9100"],
    );
    assert!(out.status.success(), "{out:?}");
    assert!(
        std::fs::read_to_string(&fresh)
            .unwrap()
            .contains("port = 9100"),
        "the first set under a new profile creates its overlay"
    );
    assert_eq!(
        std::fs::read_to_string(&base).unwrap(),
        before,
        "and still leaves the shared file alone"
    );
}

/// `--approvals-out` promises "record the calls that wait, write them here, exit 3". With `--yes` —
/// or `[cli] approval = "auto"` in the config, the same decision written down — nothing waits, so the
/// run did not park, wrote no file, and exited 0. Accepted with no warning.
#[test]
fn approvals_out_is_refused_when_approvals_are_automatic() {
    let home = tempfile::tempdir().unwrap();
    assert!(run(home.path(), &["config", "init"]).status.success());
    let out_file = home.path().join("waiting.json");

    for (args, why) in [
        (
            vec![
                "-y",
                "run",
                "--approvals-out",
                out_file.to_str().unwrap(),
                "hello",
            ],
            "--yes",
        ),
        (
            vec![
                "run",
                "--approvals-out",
                out_file.to_str().unwrap(),
                "hello",
            ],
            "[cli] approval = auto",
        ),
    ] {
        if why == "[cli] approval = auto" {
            assert!(run(home.path(), &["config", "set", "cli.approval", "auto"])
                .status
                .success());
        }
        let out = run(home.path(), &args);
        assert!(
            !out.status.success(),
            "{why}: the pair is not a run that can park: {out:?}"
        );
        let err = String::from_utf8_lossy(&out.stderr).to_string();
        assert!(
            err.contains("--approvals-out") && err.contains("nothing waits"),
            "{why}: {err}"
        );
        assert!(
            !out_file.exists(),
            "{why}: and no file is written by a run that refused to start"
        );
        // Back to asking, so the next round tests its own spelling and not this one.
        assert!(run(home.path(), &["config", "set", "cli.approval", "ask"])
            .status
            .success());
    }
}

/// A delivery path that cannot be written is a fact about one job, not a reason to abandon the tick.
/// The `?` on the write skipped every other due job and lost this one's outcome, so `cron list` kept
/// reporting the run before it — a job that ran, invisibly, every minute.
#[cfg(unix)]
#[test]
fn one_jobs_failed_delivery_does_not_abort_the_tick() {
    let home = tempfile::tempdir().unwrap();
    let config = "[tools]\nwrite_file = \"allow\"\n";
    let (base, bodies, server) =
        serve_replies(vec![text_reply("first reply"), text_reply("second reply")]);

    // The delivery target is itself a directory: the write fails every time.
    let blocked = home.path().join("blocked");
    std::fs::create_dir_all(&blocked).unwrap();
    for (name, deliver) in [("alpha", blocked), ("beta", home.path().join("beta.md"))] {
        let added = run_cmd(
            home.path(),
            config,
            &base,
            &[
                "cron",
                "add",
                "--name",
                name,
                "--schedule",
                "every 1m",
                "--prompt",
                "say something",
                "--deliver",
                deliver.to_str().unwrap(),
            ],
        );
        assert!(added.status.success(), "{added:?}");
    }

    let ran = run_cmd(home.path(), config, &base, &["cron", "run", "--force"]);
    // The mock server is still waiting for the second job's request when the tick gave up on it, so
    // joining it here would hang a broken build instead of failing it. Wait a bounded time for it to
    // finish and carry on either way: the assertions below say what actually happened.
    let (done, waited) = std::sync::mpsc::channel();
    std::thread::spawn(move || {
        let _ = done.send(server.join().is_ok());
    });
    let _ = waited.recv_timeout(Duration::from_secs(10));
    let out = String::from_utf8_lossy(&ran.stdout).to_string();
    let err = String::from_utf8_lossy(&ran.stderr).to_string();

    // Both jobs ran, even though the first could not deliver.
    assert_eq!(
        // `try_iter`, not `iter`: draining the channel to its end would wait for a message that a
        // broken tick never sends, hanging the test instead of failing it.
        bodies.try_iter().count(),
        2,
        "both jobs reached the model: {out}"
    );
    assert!(out.contains("beta"), "the second job still ran: {out}");
    assert!(
        out.contains("the delivery to") && out.contains("failed"),
        "the problem is said out loud: {out}{err}"
    );
    assert!(
        home.path().join("beta.md").is_file(),
        "the second job's delivery landed"
    );

    // The tick reports the failure, and the job whose delivery failed still recorded its outcome.
    assert_eq!(ran.status.code(), Some(1), "{out}{err}");
    let listed = run_cmd(home.path(), config, &base, &["cron", "list"]);
    let listed = String::from_utf8_lossy(&listed.stdout).to_string();
    assert!(listed.contains("alpha"), "{listed}");
    assert!(
        !listed.contains("never run"),
        "a job that ran is not listed as never run: {listed}"
    );

    // And the run log for the job whose delivery failed carries the problem.
    let runs = home.path().join(".eclipse/cron/runs/alpha");
    let log = std::fs::read_dir(&runs).unwrap().next().unwrap().unwrap();
    let text = std::fs::read_to_string(log.path()).unwrap();
    assert!(text.contains("the delivery to"), "{text}");
}

/// `restart` is `systemctl --user restart` and nothing else: composing it out of `stop` and
/// `start` would disable the unit on the way past, and the next boot would have no gateway.
#[cfg(unix)]
#[test]
fn gateway_restart_restarts_without_disabling() {
    use std::os::unix::fs::PermissionsExt;

    let home = tempfile::tempdir().unwrap();
    let unit = home
        .path()
        .join(".config/systemd/user/eclipse-gateway.service");
    std::fs::create_dir_all(unit.parent().unwrap()).unwrap();
    std::fs::write(&unit, "[Unit]\nDescription=test\n").unwrap();
    let bin = home.path().join("fake-bin");
    std::fs::create_dir_all(&bin).unwrap();
    let log = home.path().join("calls.txt");
    std::fs::write(
        bin.join("systemctl"),
        format!(
            "#!/bin/sh\nprintf '%s\\n' \"$*\" >> {log}\n\
             case \"$*\" in\n  *is-active*) echo active; exit 0;;\nesac\nexit 0\n",
            log = log.display()
        ),
    )
    .unwrap();
    std::fs::set_permissions(
        bin.join("systemctl"),
        std::fs::Permissions::from_mode(0o755),
    )
    .unwrap();

    let out = Command::new(env!("CARGO_BIN_EXE_eclipse"))
        .args(["gateway", "restart"])
        .env_clear()
        .env("HOME", home.path())
        .env("NO_COLOR", "1")
        .env("PATH", format!("{}:/usr/bin:/bin", bin.display()))
        .output()
        .unwrap();
    assert!(out.status.success(), "{out:?}");
    assert!(stdout(&out).contains("restarted"), "{}", stdout(&out));
    let calls = std::fs::read_to_string(&log).unwrap();
    assert!(
        calls.contains("--user restart eclipse-gateway.service"),
        "{calls}"
    );
    assert!(
        !calls.contains("disable"),
        "restart never disables: {calls}"
    );
    assert!(!calls.contains("enable"), "nor touches enablement: {calls}");
}

/// With no unit there is nothing to restart, and the refusal names the command that writes one.
#[cfg(unix)]
#[test]
fn gateway_restart_refuses_when_nothing_is_installed() {
    let (out, _home) = with_fake_systemctl(true, &["gateway", "restart"]);
    assert!(!out.status.success(), "{out:?}");
    let err = String::from_utf8_lossy(&out.stderr);
    assert!(err.contains("eclipse gateway install"), "{err}");
}

// ---------------------------------------------------------------------------------------------
// M225: `/bg` and `/tasks` — work that outlives the prompt.
// ---------------------------------------------------------------------------------------------

/// A stub endpoint that answers every non-chat request at once and chat requests after `delay`.
///
/// `delay: None` never answers: the run stays in flight until something kills it, which is what
/// the cancel and the kill tests need. Probes (`/models`, `/props`, anything that opens and
/// closes without a request line) are answered immediately, or counted as turns — the lesson from
/// #224's test, where a reachability probe was answered as if it were the question.
#[cfg(unix)]
fn serve_turns(delay: Option<Duration>, content: &str) -> (String, std::thread::JoinHandle<()>) {
    let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
    let base = format!("http://{}/v1", listener.local_addr().unwrap());
    let content = content.to_string();
    let handle = std::thread::spawn(move || {
        for conn in listener.incoming() {
            let Ok(mut s) = conn else { return };
            let mut head = Vec::new();
            let mut chunk = [0u8; 4096];
            while !head.windows(4).any(|w| w == b"\r\n\r\n") {
                match s.read(&mut chunk) {
                    Ok(0) | Err(_) => break,
                    Ok(n) => head.extend_from_slice(&chunk[..n]),
                }
            }
            // A connection that closed before sending anything is a probe, not a request.
            if head.windows(4).position(|w| w == b"\r\n\r\n").is_none() {
                continue;
            }
            let text = String::from_utf8_lossy(&head).into_owned();
            let is_chat =
                text.starts_with("POST") && text.to_ascii_lowercase().contains("/chat/completions");
            if !is_chat {
                let body = "{\"data\":[{ \"id\": \"m\" }]}";
                let _ = write!(
                    s,
                    "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
                    body.len()
                );
                continue;
            }
            let body = serde_json::json!({
                "choices": [{"message": {"role": "assistant", "content": content}, "finish_reason": "stop"}]
            })
            .to_string();
            match delay {
                // Hold the connection open and answer nothing: the run is waiting on a model,
                // which is where a task spends most of its time.
                None => std::thread::sleep(Duration::from_secs(30)),
                Some(d) => {
                    std::thread::sleep(d);
                    let _ = write!(
                        s,
                        "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
                        body.len()
                    );
                }
            }
        }
    });
    (base, handle)
}

#[cfg(unix)]
fn registry_of(home: &std::path::Path) -> eclipse_core::tasks::Registry {
    eclipse_core::tasks::Registry::new(home.join(".eclipse/state"))
}

/// Poll the registry until `done` holds for the only task in it, or the deadline passes.
#[cfg(unix)]
fn wait_for_task(
    registry: &eclipse_core::tasks::Registry,
    what: &str,
    done: impl Fn(&eclipse_core::tasks::Task) -> bool,
) -> eclipse_core::tasks::Task {
    let deadline = std::time::Instant::now() + Duration::from_secs(20);
    loop {
        if let Some(task) = registry.list().into_iter().next() {
            if done(&task) {
                return task;
            }
        }
        if std::time::Instant::now() > deadline {
            panic!("timed out waiting for {what}: {:?}", registry.list());
        }
        std::thread::sleep(Duration::from_millis(50));
    }
}

#[cfg(unix)]
fn signal(pid: u32, sig: libc::c_int) {
    // SAFETY: sending a signal to a pid this test started; nothing is dereferenced.
    assert_eq!(
        unsafe { libc::kill(pid as libc::pid_t, sig) },
        0,
        "kill({pid}, {sig})"
    );
}

/// #225's first promise: `/bg` returns at once, and the run it started is still going afterwards.
#[cfg(unix)]
#[test]
fn a_background_task_outlives_the_prompt_that_started_it() {
    let home = tempfile::tempdir().unwrap();
    let (base, server) = serve_turns(Some(Duration::from_millis(2_500)), "done and dusted");
    let out = repl_against(
        home.path(),
        "[provider]\nmax_retries = 0\n",
        &base,
        "/bg summarise the issues\n/tasks\n/quit\n",
    );
    let registry = registry_of(home.path());

    // `/bg` answered with an id, and the composer took the next line before the run finished:
    // `/tasks` printed a live state, which is the proof that the prompt came back at once.
    let text = format!("{}{}", stdout(&out), String::from_utf8_lossy(&out.stderr));
    assert!(text.contains("background:"), "{text}");
    assert!(text.contains("summarise the issues"), "{text}");
    assert!(
        text.contains("running") || text.contains("starting"),
        "the task was already finished when /tasks listed it: {text}"
    );
    let listed = registry.list();
    assert_eq!(listed.len(), 1, "one task: {listed:?}");
    let id = listed[0].session.clone();
    assert!(
        text.contains(&id),
        "/tasks did not name the id /bg printed: {text}"
    );
    assert!(
        !listed[0].settled(),
        "the run must outlive the prompt that started it: {:?}",
        listed[0]
    );

    // It finishes on its own, in a process that is not the REPL's.
    let done = wait_for_task(&registry, "the task to finish", |t| t.settled());
    assert_eq!(
        done.state_now(),
        eclipse_core::tasks::State::Done,
        "{done:?}"
    );
    assert_eq!(done.session, id);

    // And it is a session like any other: stored, answered, and listed.
    let store =
        eclipse_core::session::SessionStore::new(home.path().join(".eclipse/state/sessions"));
    let records = store.load_records(&id).expect("the transcript is stored");
    assert_eq!(records.len(), 2, "{records:?}");
    assert_eq!(records[0].message.role, eclipse_core::message::Role::User);
    assert_eq!(
        records[0].message.content.as_deref(),
        Some("summarise the issues")
    );
    assert_eq!(
        records[1].message.content.as_deref(),
        Some("done and dusted"),
        "the answer landed in the background session"
    );
    let list = run(
        home.path(),
        &[
            "--config",
            home.path().join("c.toml").to_str().unwrap(),
            "sessions",
            "list",
        ],
    );
    assert!(list.status.success(), "{list:?}");
    assert!(stdout(&list).contains(&id), "{}", stdout(&list));

    // The stub thread is left looping on `accept`: it has one more connection to answer than
    // this test has turns, and joining it would wait for a request nobody is going to make.
    drop(server);
}

/// The honest answer for a process that was killed: `died`, not `running` for the rest of the day.
#[cfg(unix)]
#[test]
fn a_killed_background_task_reads_died_not_running() {
    let home = tempfile::tempdir().unwrap();
    let (base, _server) = serve_turns(None, "never");
    let out = repl_against(
        home.path(),
        "[provider]\nmax_retries = 0\n",
        &base,
        "/bg wait for a model that never answers\n/quit\n",
    );
    assert!(
        out.status.success() || !out.status.success(),
        "the REPL exited"
    );
    let registry = registry_of(home.path());
    let live = wait_for_task(&registry, "the child to start working", |t| {
        t.state == eclipse_core::tasks::State::Running
    });
    let pid = live.pid;
    signal(pid, libc::SIGKILL);

    let dead = wait_for_task(&registry, "the entry to read died", |t| t.died());
    assert_eq!(
        dead.state,
        eclipse_core::tasks::State::Running,
        "nothing rewrote it"
    );
    assert_eq!(dead.state_now(), eclipse_core::tasks::State::Died);

    // `/tasks` says so, and the row still carries what the run last did.
    let out = repl_against(
        home.path(),
        "[provider]\nmax_retries = 0\n",
        &base,
        "/tasks\n/quit\n",
    );
    let text = stdout(&out);
    assert!(text.contains("died"), "{text}");
    assert!(text.contains(&dead.session), "{text}");
}

/// Stopping a task cancels the turn, so the transcript keeps the question and the entry says it
/// was stopped — the same record a cancelled dashboard run leaves.
#[cfg(unix)]
#[test]
fn stopping_a_background_task_records_that_it_was_stopped() {
    let home = tempfile::tempdir().unwrap();
    let (base, _server) = serve_turns(None, "never");
    let out = repl_against(
        home.path(),
        "[provider]\nmax_retries = 0\n",
        &base,
        "/bg wait for a model that never answers\n/quit\n",
    );
    assert!(out.status.success(), "{out:?}");
    let registry = registry_of(home.path());
    let live = wait_for_task(&registry, "the child to start working", |t| {
        t.state == eclipse_core::tasks::State::Running
    });
    let pid = live.pid;
    signal(pid, libc::SIGTERM);

    let stopped = wait_for_task(&registry, "the entry to say stopped", |t| t.settled());
    assert_eq!(
        stopped.state_now(),
        eclipse_core::tasks::State::Stopped,
        "{stopped:?}"
    );
    assert!(stopped.detail.contains("signal"), "{stopped:?}");

    // The process is gone, and the question is still in the session with no answer beside it.
    let store =
        eclipse_core::session::SessionStore::new(home.path().join(".eclipse/state/sessions"));
    let records = store
        .load_records(&stopped.session)
        .expect("the transcript");
    assert_eq!(
        records.len(),
        1,
        "the question stays, unanswered: {records:?}"
    );
    assert_eq!(
        records[0].message.content.as_deref(),
        Some("wait for a model that never answers")
    );
}

/// `/bg` is a composer's verb: a run, a cron job and the gateway all refuse it in one sentence.
#[cfg(unix)]
#[test]
fn a_run_a_cron_job_and_the_gateway_refuse_bg() {
    let home = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(home.path().join(".eclipse")).unwrap();

    let out = run(home.path(), &["run", "/bg count the files"]);
    assert!(!out.status.success(), "{out:?}");
    let err = String::from_utf8_lossy(&out.stderr);
    assert!(err.contains("/bg"), "{err}");
    assert!(err.contains("eclipse run"), "{err}");

    let out = run(
        home.path(),
        &[
            "cron",
            "add",
            "--name",
            "spawner",
            "--schedule",
            "hourly",
            "--prompt",
            "/bg count the files",
        ],
    );
    assert!(!out.status.success(), "{out:?}");
    let err = String::from_utf8_lossy(&out.stderr);
    assert!(err.contains("/bg") && err.contains("cron job"), "{err}");
    assert!(
        !home.path().join(".eclipse/cron/jobs.toml").exists(),
        "a refused job is not written"
    );
}

/// `#226`: `/yolo on` is a mode this *process* enters, and the assertion is the tool outcome —
/// `read_file` is under `ask`, so with no keyboard it would be declined; under `/yolo on` it runs
/// and the model is sent its output.
#[cfg(unix)]
#[test]
fn yolo_on_runs_a_tool_the_ask_policy_would_have_declined() {
    let home = tempfile::tempdir().unwrap();
    std::fs::write(home.path().join("a.txt"), "FILE-CONTENT-BY-NOX").unwrap();
    let config = "[tools]\nread_file = \"ask\"\n[provider]\nmax_retries = 0\n";
    let (base, bodies, server) = serve_tool_for_repl("read_file", "{\"path\":\"a.txt\"}", "done");
    let out = repl_against(home.path(), config, &base, "/yolo on\nread a.txt\n/quit\n");
    server.join().unwrap();
    assert!(out.status.success(), "{out:?}");
    let sent: Vec<String> = bodies.iter().collect();
    assert_eq!(sent.len(), 2, "one tool call, one follow-up");
    assert!(
        sent[1].contains("FILE-CONTENT-BY-NOX"),
        "the call should have run; the model was sent: {}",
        sent[1]
    );
}

/// And `/yolo off` takes it back inside a session a `--yes` flag started: "this session" is what
/// the flag meant, so the switch has to work in both directions.
#[cfg(unix)]
#[test]
fn yolo_off_parks_the_call_again_in_a_yes_session() {
    let home = tempfile::tempdir().unwrap();
    std::fs::write(home.path().join("a.txt"), "FILE-CONTENT-BY-NOX").unwrap();
    let config = "[tools]\nread_file = \"ask\"\n[provider]\nmax_retries = 0\n";
    let (base, bodies, server) = serve_tool_for_repl("read_file", "{\"path\":\"a.txt\"}", "done");
    let out = repl_with_args(
        home.path(),
        config,
        &base,
        &["--yes"],
        "/yolo off\nread a.txt\n/quit\n",
    );
    server.join().unwrap();
    assert!(out.status.success(), "{out:?}");
    let sent: Vec<String> = bodies.iter().collect();
    assert_eq!(sent.len(), 2, "one tool call, one follow-up");
    assert!(
        !sent[1].contains("FILE-CONTENT-BY-NOX"),
        "the call should have parked: {}",
        sent[1]
    );
    assert!(
        sent[1].contains("declined to run"),
        "expected a refusal, got: {}",
        sent[1]
    );
}

/// The mode lives in the process and nowhere else: toggling it twice leaves the config
/// byte-identical, which is the whole reason a forgotten `/yolo on` cannot become the next
/// session's policy.
#[cfg(unix)]
#[test]
fn yolo_writes_nothing_to_the_config_and_a_new_process_is_back_to_the_file() {
    let home = tempfile::tempdir().unwrap();
    let config =
        "[tools]\nread_file = \"ask\"\n[cli]\napproval = \"ask\"\n[provider]\nmax_retries = 0\n";
    let before = {
        let out = repl_against(
            home.path(),
            config,
            "http://127.0.0.1:1/v1",
            "/yolo on\n/quit\n",
        );
        assert!(out.status.success(), "{out:?}");
        std::fs::read(home.path().join("c.toml")).unwrap()
    };
    let out = repl_against(
        home.path(),
        config,
        "http://127.0.0.1:1/v1",
        "/yolo on\n/yolo off\n/quit\n",
    );
    assert!(out.status.success(), "{out:?}");
    assert_eq!(
        std::fs::read(home.path().join("c.toml")).unwrap(),
        before,
        "`/yolo` is a process setting: the file is untouched"
    );

    // A fresh session from the same config, with no `/yolo` and no `--yes`, is back to `ask` —
    // asserted the same way, through what the tool did.
    std::fs::write(home.path().join("a.txt"), "FILE-CONTENT-BY-NOX").unwrap();
    let (base, bodies, server) = serve_tool_for_repl("read_file", "{\"path\":\"a.txt\"}", "done");
    let out = repl_against(home.path(), config, &base, "read a.txt\n/quit\n");
    server.join().unwrap();
    assert!(out.status.success(), "{out:?}");
    let sent: Vec<String> = bodies.iter().collect();
    assert!(
        sent[1].contains("declined to run") && !sent[1].contains("FILE-CONTENT-BY-NOX"),
        "the mode did not survive the process: {}",
        sent[1]
    );
}

/// A job that starts with every approval pre-answered is a mode nobody can see and nobody can
/// undo, so `cron add` refuses the line instead of storing it.
#[cfg(unix)]
#[test]
fn cron_add_refuses_yolo() {
    let home = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(home.path().join(".eclipse")).unwrap();
    let out = run(
        home.path(),
        &[
            "cron",
            "add",
            "--name",
            "yolo",
            "--schedule",
            "hourly",
            "--prompt",
            "/yolo on",
        ],
    );
    assert!(!out.status.success(), "{out:?}");
    let err = String::from_utf8_lossy(&out.stderr);
    assert!(err.contains("/yolo"), "{err}");
    assert!(err.contains("cron job"), "{err}");
    assert!(err.contains("--yes"), "{err}");
    assert!(
        !home.path().join(".eclipse/cron/jobs.toml").exists(),
        "a refused job is not written"
    );
}

/// `/tasks` with no registry is one line and a clean exit, in both front ends.
#[cfg(unix)]
#[test]
fn tasks_with_nothing_registered_says_so_and_exits_cleanly() {
    let home = tempfile::tempdir().unwrap();
    let (base, _server) = serve_turns(Some(Duration::from_millis(10)), "unused");
    let out = repl_against(
        home.path(),
        "[provider]\nmax_retries = 0\n",
        &base,
        "/tasks\n/tasks 1\n/quit\n",
    );
    assert!(out.status.success(), "{out:?}");
    let text = stdout(&out);
    assert!(text.contains("no background tasks"), "{text}");
    assert!(text.contains("no task matches"), "{text}");
    assert!(
        !home.path().join(".eclipse/state/tasks").exists(),
        "nothing was created"
    );
}

/// `#266`: `eclipse web passwd` is the only way a password is meant to reach `.env`, so the test
/// is about what reaches the file and what does not reach the terminal.
fn passwd(home: &std::path::Path, args: &[&str], stdin: &str) -> Output {
    let mut child = Command::new(env!("CARGO_BIN_EXE_eclipse"))
        .arg("web")
        .arg("passwd")
        .args(args)
        .env_clear()
        .env("HOME", home)
        .env("NO_COLOR", "1")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();
    child
        .stdin
        .take()
        .unwrap()
        .write_all(stdin.as_bytes())
        .unwrap();
    child.wait_with_output().unwrap()
}

/// `#597`: the `(None, None)` arm prompted for a user *before* checking whether anything could
/// answer, so `printf '%s\n' "$PASS" | eclipse web passwd --stdin` ate the password as the username —
/// and then quoted it back at the reader in the rejection, into stderr and a CI log.
#[test]
fn web_passwd_piped_without_a_user_refuses_and_never_prints_the_password() {
    let home = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(home.path().join(".eclipse")).unwrap();
    let out = passwd(home.path(), &["--stdin"], "hunter2 #nope\n");
    assert!(!out.status.success(), "{out:?}");
    let said = format!("{}{}", stdout(&out), String::from_utf8_lossy(&out.stderr));
    assert!(
        !said.contains("hunter2"),
        "the password reached the output: {said}"
    );
    assert!(
        said.contains("--user"),
        "and the refusal says what to do instead: {said}"
    );
    assert!(
        !dotenv_of(home.path()).contains("ECLIPSE_WEB_USER"),
        "nothing was written"
    );
}

/// ...and a stored user still means `--user` is not needed: the password alone is enough, which is
/// the case the arm above exists for.
#[test]
fn web_passwd_piped_with_a_stored_user_keeps_it() {
    let home = tempfile::tempdir().unwrap();
    let dir = home.path().join(".eclipse");
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(dir.join(".env"), "ECLIPSE_WEB_USER=max\n").unwrap();
    let out = passwd(home.path(), &["--stdin"], "open sesame please\n");
    assert!(out.status.success(), "{out:?}");
    let text = dotenv_of(home.path());
    assert!(text.contains("ECLIPSE_WEB_USER=max"), "{text}");
    assert!(text.contains("ECLIPSE_WEB_PASSWORD_HASH"), "{text}");
}

fn dotenv_of(home: &std::path::Path) -> String {
    std::fs::read_to_string(home.join(".eclipse/.env")).unwrap_or_default()
}

fn hash_in(text: &str) -> Option<&str> {
    text.lines()
        .find_map(|l| l.strip_prefix("ECLIPSE_WEB_PASSWORD_HASH="))
}

#[test]
fn web_passwd_writes_a_hash_and_keeps_the_rest_of_env() {
    let home = tempfile::tempdir().unwrap();
    let dir = home.path().join(".eclipse");
    std::fs::create_dir_all(&dir).unwrap();
    let dotenv = dir.join(".env");
    std::fs::write(
        &dotenv,
        "# this install's secrets\n\
         ECLIPSE_WEB_AUTH_TOKEN=0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\n\
         OTHER_SECRET=keep-me\n",
    )
    .unwrap();
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&dotenv, std::fs::Permissions::from_mode(0o600)).unwrap();
    }

    let out = passwd(home.path(), &["max", "--stdin"], "open sesame please\n");
    assert!(out.status.success(), "{out:?}");
    let printed = stdout(&out);
    // Neither the password nor the hash is printed: a scrollback and a CI log are both readable.
    assert!(!printed.contains("open sesame"), "{printed}");
    assert!(!printed.contains("pbkdf2"), "{printed}");
    assert!(printed.contains("ECLIPSE_WEB_PASSWORD_HASH"), "{printed}");

    let text = dotenv_of(home.path());
    assert!(
        text.contains("OTHER_SECRET=keep-me"),
        "other keys survive: {text}"
    );
    assert!(
        text.contains("ECLIPSE_WEB_AUTH_TOKEN=0123456789"),
        "the token stays: {text}"
    );
    assert!(
        text.contains("# this install's secrets"),
        "comments stay: {text}"
    );
    assert!(text.contains("ECLIPSE_WEB_USER=max\n"), "{text}");
    let hash = hash_in(&text).expect("a hash was written").to_string();
    assert!(hash.starts_with("pbkdf2-sha256$600000$"), "{hash}");
    assert!(eclipse_core::auth::verify_password(
        "open sesame please",
        &hash
    ));
    assert!(!eclipse_core::auth::verify_password("open sesame", &hash));

    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mode = std::fs::metadata(&dotenv).unwrap().permissions().mode() & 0o777;
        assert_eq!(mode, 0o600, "a file with a hash in it is owner-only");
    }

    // What was written is what the dashboard will accept — through the same `resolve` the server
    // uses, so this is not a test of a second parser.
    let creds = eclipse_core::auth::Credentials::resolve(|name| {
        let key = format!("{name}=");
        text.lines()
            .find_map(|l| l.strip_prefix(&key).map(str::to_string))
    })
    .expect("the file it wrote loads back");
    assert!(creds.check("max", "open sesame please", "the-token-is-not-this"));
    assert!(!creds.check("max", "something else", "the-token-is-not-this"));

    // A reset without a username keeps the one in the file: retyping a name to change a password
    // is a chance to typo it.
    let again = passwd(home.path(), &["--stdin"], "a better passphrase\n");
    assert!(again.status.success(), "{again:?}");
    let text = dotenv_of(home.path());
    assert!(text.contains("ECLIPSE_WEB_USER=max\n"), "{text}");
    let hash = hash_in(&text).unwrap().to_string();
    assert!(eclipse_core::auth::verify_password(
        "a better passphrase",
        &hash
    ));
    assert!(
        !eclipse_core::auth::verify_password("open sesame please", &hash),
        "the old one is gone"
    );
    // The old hash line is replaced, not appended beside a stale one.
    assert_eq!(
        text.matches("ECLIPSE_WEB_PASSWORD_HASH=").count(),
        1,
        "{text}"
    );
}

#[test]
fn web_passwd_refuses_a_password_or_name_that_would_not_work() {
    let home = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(home.path().join(".eclipse")).unwrap();
    std::fs::write(home.path().join(".eclipse/.env"), "OTHER=1\n").unwrap();

    let short = passwd(home.path(), &["max", "--stdin"], "short\n");
    assert!(!short.status.success(), "{short:?}");
    assert!(
        String::from_utf8_lossy(&short.stderr).contains("at least 8 characters"),
        "{}",
        String::from_utf8_lossy(&short.stderr)
    );

    let spaces = passwd(
        home.path(),
        &["bad name", "--stdin"],
        "a long enough password\n",
    );
    assert!(!spaces.status.success(), "{spaces:?}");
    assert!(
        String::from_utf8_lossy(&spaces.stderr).contains("not usable"),
        "{}",
        String::from_utf8_lossy(&spaces.stderr)
    );

    // Nothing was written by either refusal.
    let text = dotenv_of(home.path());
    assert_eq!(
        text.trim(),
        "OTHER=1",
        "a refused run leaves .env alone: {text}"
    );
}

// ---- the manual (#docs) ---------------------------------------------------------------

/// The page the install carries: written beside the config, self-contained, and describing keys
/// from the same catalogue the program reads. A manual that only exists in a repository is a
/// manual the person who installed a tarball does not have.
#[test]
fn config_docs_writes_a_self_contained_page_beside_the_config() {
    let home = tempfile::tempdir().unwrap();
    assert!(run(home.path(), &["config", "init"]).status.success());
    let page = home.path().join(".eclipse/docs/configuration.html");

    let out = run(home.path(), &["config", "docs"]);
    assert!(out.status.success(), "{out:?}");
    assert!(stdout(&out).contains("configuration.html"), "{out:?}");
    let html = std::fs::read_to_string(&page).unwrap();
    // Every key in the catalogue is on the page, by name.
    for key in [
        "timeout_secs",
        "shell_isolate",
        "reasoning_effort",
        "memory_budget_chars",
        "ECLIPSE_WEB_PASSWORD_HASH",
    ] {
        assert!(html.contains(key), "the manual names `{key}`");
    }
    // Self-contained: a page that fetches a font or a script is a page that breaks offline, and
    // this is the documentation for a tool that runs offline.
    assert!(!html.contains("<script"), "no scripts: {html:.2000}");
    assert!(
        !html.contains("http://") && !html.contains("https://"),
        "no remote assets"
    );
    assert!(html.starts_with("<!doctype html>"), "{html:.200}");
    // The text twin, for the reader that is not a person. Same rows, no markup: an agent that has
    // to answer "what does this key accept" should not be stripping tags to find out.
    let twin = home.path().join(".eclipse/docs/configuration.txt");
    let text = std::fs::read_to_string(&twin).expect("the text manual sits beside the page");
    assert!(text.contains("memory_budget_chars"), "{text:.2000}");
    assert!(text.contains("ECLIPSE_WEB_PASSWORD_HASH"), "{text:.2000}");
    assert!(
        !text.contains("<!doctype") && !text.contains("<p>"),
        "the twin is text, not html: {text:.600}"
    );
    assert!(
        text.len() < html.len(),
        "and it is the smaller file: {} vs {}",
        text.len(),
        html.len()
    );
    // And `config init` already wrote it: the manual is part of a first install, not an extra step.
    std::fs::remove_file(&page).unwrap();
    std::fs::remove_file(&twin).unwrap();
    assert!(run(home.path(), &["config", "init", "--force"])
        .status
        .success());
    assert!(page.exists(), "a first install carries its manual");
    assert!(twin.exists(), "both forms of it");
}

/// The same rows for a model: `--format json` is what an agent reads when it needs to know what a
/// key accepts, and it must parse — one document, both sources.
#[test]
fn config_docs_json_is_a_document_a_model_can_read() {
    let home = tempfile::tempdir().unwrap();
    assert!(run(home.path(), &["config", "init"]).status.success());
    let out = run(home.path(), &["config", "docs", "--format", "json"]);
    assert!(out.status.success(), "{out:?}");
    let text = stdout(&out);
    let rows: serde_json::Value = serde_json::from_str(&text).expect("valid JSON");
    let rows = rows.as_array().expect("an array of rows");
    assert!(rows.len() > 100, "every key and variable: {}", rows.len());
    let one = rows
        .iter()
        .find(|r| r["name"] == "provider.max_retries")
        .expect("a known key");
    assert_eq!(one["kind"], "number");
    assert!(!one["about"].as_str().unwrap().is_empty(), "{one}");
    let env = rows
        .iter()
        .find(|r| r["name"] == "ECLIPSE_WEB_AUTH_TOKEN")
        .expect("the token is documented");
    assert_eq!(env["source"], "env");
    assert_eq!(env["accepts"], "in `.env`");
}

#[test]
fn config_explain_answers_for_a_key_and_for_a_variable() {
    let home = tempfile::tempdir().unwrap();
    assert!(run(home.path(), &["config", "init"]).status.success());
    let text = stdout(&run(
        home.path(),
        &["config", "explain", "provider.temperature"],
    ));
    assert!(text.contains("Sampling temperature"), "{text}");
    assert!(text.contains("now:"), "{text}");
    assert!(
        text.contains("eclipse config set provider.temperature"),
        "{text}"
    );
    let text = stdout(&run(
        home.path(),
        &["config", "explain", "ECLIPSE_WEB_USER"],
    ));
    assert!(text.contains("sign-in name"), "{text}");
    // An unknown name gets the two commands that list the real ones, not a guess.
    let out = run(home.path(), &["config", "explain", "provider.nonsense"]);
    assert!(
        String::from_utf8_lossy(&out.stderr).contains("config docs"),
        "{out:?}"
    );
}

// ---------------------------------------------------------------------------------------------
// `config migrate` — the file comes forward, the values stay.
// ---------------------------------------------------------------------------------------------

/// A config as an older build left it: no stamp, and one line missing entirely.
fn an_older_config(home: &std::path::Path) -> std::path::PathBuf {
    let out = run(home, &["config", "init"]);
    assert!(out.status.success(), "{out:?}");
    let path = home.join(".eclipse/config.toml");
    let text = std::fs::read_to_string(&path).unwrap();
    let older = text
        .replace("config_version = 1\n", "")
        .replace("max_retries = 3\n", "");
    std::fs::write(&path, &older).unwrap();
    path
}

#[test]
fn config_migrate_says_what_it_would_do_and_writes_nothing() {
    let home = tempfile::tempdir().unwrap();
    let path = an_older_config(home.path());
    let before = std::fs::read_to_string(&path).unwrap();

    let out = run(home.path(), &["config", "migrate", "--dry-run"]);
    assert!(out.status.success(), "{out:?}");
    let text = stdout(&out);
    assert!(text.contains("config_version 0 -> 1"), "{text}");
    assert!(text.contains("added    provider.max_retries"), "{text}");
    assert!(text.contains("dry run: nothing was written"), "{text}");
    assert_eq!(
        std::fs::read_to_string(&path).unwrap(),
        before,
        "a dry run does not touch the file"
    );
    assert!(
        !home.path().join(".eclipse/config.toml.bak").exists(),
        "and it does not leave a backup either"
    );
}

#[test]
fn config_migrate_adds_the_missing_key_stamps_the_file_and_keeps_a_backup() {
    let home = tempfile::tempdir().unwrap();
    let path = an_older_config(home.path());
    let before = std::fs::read_to_string(&path).unwrap();

    let out = run(home.path(), &["config", "migrate"]);
    assert!(out.status.success(), "{out:?}");
    assert!(stdout(&out).contains("migrated:"), "{}", stdout(&out));

    let after = std::fs::read_to_string(&path).unwrap();
    assert!(
        after.contains("max_retries = 3"),
        "the key is back: {after}"
    );
    assert!(after.contains("config_version = 1"), "and it is stamped");
    assert_eq!(
        std::fs::read_to_string(home.path().join(".eclipse/config.toml.bak")).unwrap(),
        before,
        "the file as it was survives in the backup"
    );

    // And the result is a config the build can read, with nothing stale in it.
    let check = run(home.path(), &["config", "check", "--strict"]);
    assert!(check.status.success(), "{check:?}");
    let again = run(home.path(), &["config", "migrate"]);
    assert!(
        stdout(&again).contains("already current"),
        "{}",
        stdout(&again)
    );
}

#[test]
fn config_migrate_never_touches_a_value_someone_chose() {
    let home = tempfile::tempdir().unwrap();
    let path = an_older_config(home.path());
    let set = run(
        home.path(),
        &["config", "set", "provider.timeout_secs", "300"],
    );
    assert!(set.status.success(), "{set:?}");
    let set = run(
        home.path(),
        &["config", "set", "provider.model", "my-model"],
    );
    assert!(set.status.success(), "{set:?}");

    let out = run(home.path(), &["config", "migrate"]);
    assert!(out.status.success(), "{out:?}");

    let after = std::fs::read_to_string(&path).unwrap();
    assert!(after.contains("timeout_secs = 300"), "{after}");
    assert!(after.contains("model = \"my-model\""), "{after}");
    let shown = run(home.path(), &["config", "show"]);
    let shown = stdout(&shown);
    assert!(shown.contains("my-model"), "{shown}");
    assert!(shown.contains("300"), "{shown}");
}

#[test]
fn config_migrate_refuses_a_file_that_does_not_load() {
    let home = tempfile::tempdir().unwrap();
    let dir = home.path().join(".eclipse");
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(dir.join("config.toml"), "this is not = toml [[[").unwrap();

    let out = run(home.path(), &["config", "migrate"]);
    assert!(!out.status.success(), "a broken file is not migrated");
    let err = String::from_utf8_lossy(&out.stderr);
    assert!(err.contains("does not load"), "{err}");
    assert_eq!(
        std::fs::read_to_string(dir.join("config.toml")).unwrap(),
        "this is not = toml [[[",
        "and it is left exactly as it was"
    );
}

#[test]
fn config_migrate_says_nothing_to_migrate_when_there_is_no_config() {
    let home = tempfile::tempdir().unwrap();
    let out = run(home.path(), &["config", "migrate"]);
    assert!(!out.status.success());
    let err = String::from_utf8_lossy(&out.stderr);
    assert!(err.contains("no config to migrate"), "{err}");
}

#[test]
fn doctor_names_the_migration_when_the_file_is_a_shape_behind() {
    let home = tempfile::tempdir().unwrap();
    an_older_config(home.path());
    let out = run(home.path(), &["doctor"]);
    let text = stdout(&out);
    assert!(text.contains("written for shape v0"), "{text}");
    assert!(text.contains("eclipse config migrate --dry-run"), "{text}");
}

/// `#352`: a server that will not start is *failed*, with the reason — not zero tools, which is
/// what a reader had to interpret before (and could not tell from "never configured").
#[cfg(unix)]
#[test]
fn mcp_list_says_where_a_server_is_declared_and_whether_it_started() {
    let home = tempfile::tempdir().unwrap();
    write_config(
        home.path(),
        "[provider]\nbase_url = \"http://127.0.0.1:9/v1\"\nmodel = \"m\"\n\n\
         [[mcp]]\nname = \"ghost\"\ncommand = \"/nonexistent/eclipse-mcp-binary\"\n\
         prefix = \"ghost_\"\n",
    );
    let out = run(home.path(), &["mcp", "list"]);
    assert!(out.status.success(), "{out:?}");
    let listed = stdout(&out);
    // The source says which file declared it, and the row says it did not start.
    assert!(listed.contains("ghost"), "{listed}");
    assert!(listed.contains("config:mcp:ghost"), "{listed}");
    assert!(listed.contains("failed"), "{listed}");
    assert!(listed.contains("1 declared in config.toml"), "{listed}");

    // `test` is the verb that proves it: non-zero, and the reason.
    let out = run(home.path(), &["mcp", "test", "ghost"]);
    assert!(!out.status.success(), "a failed server must not exit 0");
    let said = format!("{}{}", stdout(&out), stderr(&out));
    assert!(said.contains("failed:"), "{said}");
    assert!(said.contains("nonexistent"), "{said}");

    // And a name nobody configured is an error, not an empty table.
    let out = run(home.path(), &["mcp", "test", "nope"]);
    assert!(!out.status.success());
    assert!(stderr(&out).contains("no MCP server is called"), "{out:?}");
}

/// `#516`: the variable a `token_env` names is looked up in the environment first and in `.env`
/// second, so a token kept where eclipse keeps secrets is found by this path too. Before the fix
/// `mcp test` refused the variable by name without ever trying the connection.
#[cfg(unix)]
#[test]
fn a_token_env_variable_kept_in_dotenv_resolves_for_mcp_test() {
    let home = tempfile::tempdir().unwrap();
    write_config(
        home.path(),
        "[provider]\nbase_url = \"http://127.0.0.1:9/v1\"\nmodel = \"m\"\n\n\
         [[mcp]]\nname = \"ha\"\ntransport = \"http\"\nurl = \"http://127.0.0.1:9/api/mcp\"\n\
         token_env = \"ECLIPSE_TEST_HA_TOKEN\"\n",
    );
    // The value lives only in `.env`; nothing exports it, and `run` clears the environment.
    std::fs::write(
        home.path().join(".eclipse/.env"),
        "ECLIPSE_TEST_HA_TOKEN=kept-in-dotenv\n",
    )
    .unwrap();

    let out = run(home.path(), &["mcp", "test", "ha"]);
    let said = format!("{}{}", stdout(&out), stderr(&out));
    assert!(
        !said.contains("names a variable that is set neither"),
        "the token in `.env` was not seen: {said}"
    );
    // Port 9 is the discard port: the token resolved and the connection is what failed next.
    assert!(
        !out.status.success(),
        "a dead endpoint is not a pass: {said}"
    );
    assert!(said.contains("ha"), "{said}");
    assert!(
        !said.contains("kept-in-dotenv"),
        "a value is never printed: {said}"
    );
}

/// A plugin whose whole content is a server used to be summarised as contributing nothing.
#[cfg(unix)]
#[test]
fn plugins_list_counts_a_server_only_plugin_as_a_server() {
    let home = tempfile::tempdir().unwrap();
    write_config(
        home.path(),
        "[provider]\nbase_url = \"http://127.0.0.1:9/v1\"\nmodel = \"m\"\n\n\
         [plugins]\nenabled = [\"notes-pack\"]\n",
    );
    let dir = home.path().join(".eclipse/plugins/notes-pack");
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(
        dir.join("plugin.toml"),
        "name = \"notes-pack\"\nversion = \"0.1.0\"\ndescription = \"a server\"\n\n\
         [[mcp]]\nname = \"notes\"\ncommand = \"/nonexistent/eclipse-mcp-binary\"\n",
    )
    .unwrap();
    let listed = stdout(&run(home.path(), &["plugins", "list"]));
    assert!(
        listed.contains("1 MCP server(s)"),
        "a server-only plugin must not read as empty: {listed}"
    );
    // The same row, for a script.
    let json: serde_json::Value =
        serde_json::from_str(&stdout(&run(home.path(), &["plugins", "list", "--json"]))).unwrap();
    assert_eq!(json[0]["mcp_servers"][0], "notes", "{json}");
}

/// `#352`: the verbs edit `config.toml` in place — a comment a person wrote survives every one of
/// them, and the file is a config the loader reads right after each.
#[cfg(unix)]
#[test]
fn mcp_add_disable_and_remove_edit_the_config_without_eating_comments() {
    let home = tempfile::tempdir().unwrap();
    let config = home.path().join(".eclipse/config.toml");
    std::fs::create_dir_all(config.parent().unwrap()).unwrap();
    std::fs::write(
        &config,
        "# hand-written, must survive\n[provider]\nbase_url = \"http://127.0.0.1:9/v1\"\n\
         model = \"m\"\n\n# the notes server\n[[mcp]]\nname = \"notes\"\ncommand = \"true\"\n",
    )
    .unwrap();

    let added = run(
        home.path(),
        &[
            "mcp",
            "add",
            "fs",
            "--command",
            "npx",
            "--arg",
            "-y",
            "--arg",
            "server-fs",
            "--prefix",
            "fs_",
            "--policy",
            "allow",
        ],
    );
    assert!(added.status.success(), "{added:?}");
    let text = std::fs::read_to_string(&config).unwrap();
    assert!(text.contains("# hand-written, must survive"), "{text}");
    assert!(text.contains("# the notes server"), "{text}");
    assert!(text.contains("args = [\"-y\", \"server-fs\"]"), "{text}");
    assert!(text.contains("prefix = \"fs_\""), "{text}");

    // It is a server, and `mcp list` shows the tool count rather than a promise.
    let out = run(home.path(), &["mcp", "list"]);
    let listed = stdout(&out);
    let why = || {
        format!(
            "rc={:?} stdout={listed:?} stderr={:?}",
            out.status.code(),
            String::from_utf8_lossy(&out.stderr)
        )
    };
    assert!(
        listed.contains("fs") && listed.contains("config:mcp:fs"),
        "{}",
        why()
    );
    assert!(listed.contains("2 server(s)"), "{}", why());

    // Off, and the entry stays: `mcp list` says `off` rather than pretending it is gone.
    assert!(run(home.path(), &["mcp", "disable", "fs"]).status.success());
    let text = std::fs::read_to_string(&config).unwrap();
    assert!(text.contains("disabled = true"), "{text}");
    assert!(
        text.contains("command = \"npx\""),
        "disable must not touch the rest:\n{text}"
    );
    let listed = stdout(&run(home.path(), &["mcp", "list"]));
    assert!(listed.contains("off"), "{listed}");

    // Back on.
    assert!(run(home.path(), &["mcp", "enable", "fs"]).status.success());
    assert!(std::fs::read_to_string(&config)
        .unwrap()
        .contains("disabled = false"));

    // Gone — and only it.
    assert!(run(home.path(), &["mcp", "remove", "fs"]).status.success());
    let text = std::fs::read_to_string(&config).unwrap();
    assert!(!text.contains("server-fs"), "{text}");
    assert!(
        text.contains("name = \"notes\""),
        "the other entry stayed:\n{text}"
    );
    assert!(
        text.ends_with("command = \"true\"\n"),
        "no trailing blank left:\n{text:?}"
    );
    assert!(!text.contains("\n\n\n"), "{text:?}");
}

#[cfg(unix)]
#[test]
fn mcp_add_refuses_a_duplicate_and_an_entry_that_makes_no_sense() {
    let home = tempfile::tempdir().unwrap();
    write_config(
        home.path(),
        "[provider]\nbase_url = \"http://127.0.0.1:9/v1\"\nmodel = \"m\"\n\n\
         [[mcp]]\nname = \"notes\"\ncommand = \"true\"\n",
    );
    let dup = run(home.path(), &["mcp", "add", "notes", "--command", "false"]);
    assert!(!dup.status.success());
    assert!(stderr(&dup).contains("already declared"), "{dup:?}");

    // `--url` with `--command` is refused by `Spec::validate`, with the reason, and nothing is
    // written: a half-configured entry that looks configured is the failure this avoids.
    let before = std::fs::read_to_string(home.path().join(".eclipse/config.toml")).unwrap();
    let mixed = run(
        home.path(),
        &[
            "mcp",
            "add",
            "bad",
            "--url",
            "http://h/mcp",
            "--command",
            "x",
        ],
    );
    assert!(!mixed.status.success(), "{mixed:?}");
    assert!(stderr(&mixed).contains("not usable"), "{mixed:?}");
    let after = std::fs::read_to_string(home.path().join(".eclipse/config.toml")).unwrap();
    assert_eq!(before, after, "a refused entry must not touch the file");
}

/// `#352`: a server that exits the instant it starts used to kill the process with `SIGPIPE` — the
/// CLI sets `SIG_DFL` so `eclipse … | head` exits quietly, and the handshake write then *is* the
/// signal. `mcp list` starts every server, so one dead entry killed the command meant to report it.
/// Repeated, because the race is real: the write lands before the child exits, or it does not.
#[cfg(unix)]
#[test]
fn a_server_that_exits_instantly_is_a_failed_row_not_a_dead_process() {
    let home = tempfile::tempdir().unwrap();
    write_config(
        home.path(),
        "[provider]\nbase_url = \"http://127.0.0.1:9/v1\"\nmodel = \"m\"\n\n\
         [[mcp]]\nname = \"dies\"\ncommand = \"/usr/bin/true\"\n",
    );
    for attempt in 0..10 {
        let out = run(home.path(), &["mcp", "list"]);
        assert!(
            out.status.success(),
            "attempt {attempt}: killed, not reported: {out:?}"
        );
        let listed = stdout(&out);
        assert!(
            listed.contains("dies") && listed.contains("failed"),
            "{listed}"
        );
    }
}

/// `#171`: the run ledger has a surface, and it is honest about an empty one. The engine is
/// covered in `eclipse-core`; here is the verb a person types.
#[cfg(unix)]
#[test]
fn flares_list_and_cancel_say_what_they_found() {
    let home = tempfile::tempdir().unwrap();
    write_config(
        home.path(),
        "[provider]\nbase_url = \"http://127.0.0.1:9/v1\"\nmodel = \"m\"\n",
    );
    let out = run(home.path(), &["flares", "list"]);
    assert!(out.status.success(), "{out:?}");
    let listed = stdout(&out);
    assert!(
        listed.contains("no flare runs yet"),
        "an empty ledger says so instead of printing nothing: {listed}"
    );
    assert!(
        listed.contains("eclipse flares run"),
        "and names the verb that starts one: {listed}"
    );

    // A cancel for a run that does not exist is a refusal, not a silent success: the caller
    // asked for something to stop, and it did not stop.
    let out = run(home.path(), &["flares", "cancel", "no-such-run"]);
    assert!(
        !out.status.success(),
        "a missing run was reported as cancelled"
    );
    assert!(stderr(&out).contains("no flare run"), "{}", stderr(&out));

    // `show` on one is the same refusal.
    let out = run(home.path(), &["flares", "show", "no-such-run"]);
    assert!(!out.status.success());
    assert!(stderr(&out).contains("no flare run"), "{}", stderr(&out));

    // `-n` is read, and a bad `--merge` is refused before any model is asked.
    let out = run(
        home.path(),
        &["flares", "run", "split me", "-n", "2", "--merge", "nope"],
    );
    assert!(!out.status.success());
    assert!(stderr(&out).contains("concat"), "{}", stderr(&out));
}