lemurclaw 0.0.1

Command-line interface for the lemurclaw AI coding agent
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
//! Implements the `codex doctor` diagnostic report.
//!
//! Doctor is intentionally read-mostly: checks inspect the current installation,
//! configuration, authentication, terminal, state paths, and bounded reachability
//! probes without attempting repair or starting long-lived services. Each check
//! returns a redacted, serializable row so the same data can back the human
//! summary and `--json` support report.
//!
//! A failing check should describe the problem and remediation, but it should not
//! mutate user state. That keeps the command safe to run before filing a support
//! issue or while diagnosing a broken local installation.

use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::collections::HashMap;
use std::env;
use std::ffi::OsStr;
use std::future::Future;
use std::io::IsTerminal;
use std::io::Read;
use std::net::IpAddr;
use std::path::Path;
use std::path::PathBuf;
use std::process::Command;
use std::sync::Arc;
use std::time::Duration;
use std::time::Instant;

use anyhow::Context;
use clap::Parser;
use lemurclaw_core::api::ApiError;
use lemurclaw_core::api::ResponsesWebsocketClient;
use lemurclaw_core::api::is_azure_responses_provider;
use lemurclaw_server::arg0::Arg0DispatchPaths;
use lemurclaw_core::config::types::McpServerConfig;
use lemurclaw_core::config::types::McpServerTransportConfig;
use lemurclaw_core::config::Config;
use lemurclaw_core::config::ConfigBuilder;
use lemurclaw_core::config::ConfigOverrides;
use lemurclaw_core::config::find_codex_home;
use lemurclaw_core::features::FEATURES;
use lemurclaw_core::install_context::CodexPackageLayout;
use lemurclaw_core::install_context::InstallContext;
use lemurclaw_core::install_context::InstallMethod;
use lemurclaw_core::install_context::StandalonePlatform;
use lemurclaw_core::login::AuthDotJson;
use lemurclaw_core::login::AuthManager;
use lemurclaw_core::login::CODEX_ACCESS_TOKEN_ENV_VAR;
use lemurclaw_core::login::CODEX_API_KEY_ENV_VAR;
use lemurclaw_core::login::CodexAuth;
use lemurclaw_core::login::OPENAI_API_KEY_ENV_VAR;
use lemurclaw_core::login::default_client::build_reqwest_client;
use lemurclaw_core::login::default_client::default_headers;
use lemurclaw_core::login::load_auth_dot_json;
use lemurclaw_core::model_provider::create_model_provider;
use lemurclaw_core::protocol::auth::AuthMode;
use lemurclaw_core::protocol::protocol::AskForApproval;
use lemurclaw_core::terminal_detection::Multiplexer;
use lemurclaw_core::terminal_detection::TerminalInfo;
use lemurclaw_core::terminal_detection::TerminalName;
use lemurclaw_core::terminal_detection::terminal_info;
use lemurclaw_tui::Cli as TuiCli;
use lemurclaw_core::utils_cli::CliConfigOverrides;
use http::HeaderMap;
use http::HeaderValue;
use serde::Serialize;
use supports_color::Stream;

mod background;
mod git;
mod output;
mod progress;
mod runtime;
mod system;
mod thread_inventory;
mod title;
mod updates;

use background::background_server_check;
use git::git_check;
use output::HumanOutputOptions;
use output::redact_detail;
use output::render_human_report;
use progress::DoctorProgress;
use progress::doctor_progress;
use runtime::runtime_check;
use runtime::search_check;
use system::system_check;
use thread_inventory::thread_inventory_check;
use title::terminal_title_check;
use updates::updates_check;

const OPENAI_BETA_HEADER: &str = "OpenAI-Beta";
const RESPONSES_WEBSOCKETS_V2_BETA_HEADER_VALUE: &str = "responses_websockets=2026-02-06";
const WEBSOCKET_IMMEDIATE_CLOSE_GRACE: Duration = Duration::from_millis(250);
const SLOW_CHECK_PROGRESS_THRESHOLD: Duration = Duration::from_secs(2);
const SLOW_CHECK_PROGRESS_INTERVAL: Duration = Duration::from_secs(1);
const PROXY_ENV_VARS: &[&str] = &[
    "HTTP_PROXY",
    "HTTPS_PROXY",
    "ALL_PROXY",
    "NO_PROXY",
    "http_proxy",
    "https_proxy",
    "all_proxy",
    "no_proxy",
];
const COLOR_ENV_VARS: &[&str] = &[
    "COLORTERM",
    "NO_COLOR",
    "CLICOLOR",
    "CLICOLOR_FORCE",
    "FORCE_COLOR",
    "COLORFGBG",
];
const TERMINAL_DIMENSION_ENV_VARS: &[&str] = &["COLUMNS", "LINES"];
const TERMINFO_ENV_VARS: &[&str] = &["TERMINFO", "TERMINFO_DIRS"];
const LOCALE_ENV_VARS: &[&str] = &["LC_ALL", "LC_CTYPE", "LANG"];
#[cfg(windows)]
const NPM_COMMAND: &str = "npm.cmd";
#[cfg(not(windows))]
const NPM_COMMAND: &str = "npm";
const REMOTE_TERMINAL_ENV_VARS: &[&str] = &[
    "SSH_TTY",
    "SSH_CONNECTION",
    "SSH_CLIENT",
    "MOSH_IP",
    "WSL_DISTRO_NAME",
    "WSL_INTEROP",
    "VSCODE_INJECTION",
    "VSCODE_IPC_HOOK_CLI",
    "WAYLAND_DISPLAY",
    "DISPLAY",
    "WT_SESSION",
];
const TMUX_OPTION_NAMES: &[&str] = &[
    "extended-keys",
    "xterm-keys",
    "allow-passthrough",
    "set-clipboard",
    "focus-events",
];
const NARROW_TERMINAL_COLUMNS: u16 = 80;
const NARROW_TERMINAL_ROWS: u16 = 24;

/// Options for building a local Codex diagnostic report.
///
/// The command always runs the full bounded diagnostic set. Human output includes
/// detailed diagnostics by default; --summary keeps the terminal output compact.
#[derive(Debug, Parser)]
pub struct DoctorCommand {
    /// Emit a redacted machine-readable report.
    #[arg(long, default_value_t = false)]
    json: bool,

    /// Only show grouped check rows and the final count summary.
    #[arg(long, default_value_t = false)]
    summary: bool,

    /// Expand long lists in detailed human output.
    #[arg(long, default_value_t = false)]
    all: bool,

    /// Disable ANSI color in human output.
    #[arg(long, default_value_t = false)]
    no_color: bool,

    /// Use ASCII status labels and separators in human output.
    #[arg(long, default_value_t = false)]
    ascii: bool,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Serialize)]
#[serde(rename_all = "snake_case")]
enum CheckStatus {
    Ok,
    Warning,
    Fail,
}

/// Machine-readable doctor output shared by human and JSON renderers.
///
/// The schema is intentionally flat: each check carries its own category,
/// status, details, remediation, and duration so support tooling can filter or
/// redact individual rows without understanding the renderer's section layout.
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct DoctorReport {
    schema_version: u32,
    generated_at: String,
    overall_status: CheckStatus,
    codex_version: String,
    checks: Vec<DoctorCheck>,
}

/// One diagnostic result in the doctor report.
///
/// Summaries are safe for compact human output. Details may include local paths
/// or command output and are redacted before rendering or JSON serialization.
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct DoctorCheck {
    id: String,
    category: String,
    status: CheckStatus,
    summary: String,
    details: Vec<String>,
    issues: Vec<DoctorIssue>,
    remediation: Option<String>,
    duration_ms: u64,
}

/// Structured cause/remedy metadata for a non-ok doctor check.
///
/// Human output uses issues to make warnings and failures self-explanatory:
/// the row headline says what is wrong, matching detail rows show measured vs.
/// expected values, and remedies are printed as explicit next actions.
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct DoctorIssue {
    severity: CheckStatus,
    cause: String,
    measured: Option<String>,
    expected: Option<String>,
    remedy: Option<String>,
    fields: Vec<String>,
}

impl DoctorIssue {
    fn new(severity: CheckStatus, cause: impl Into<String>) -> Self {
        Self {
            severity,
            cause: cause.into(),
            measured: None,
            expected: None,
            remedy: None,
            fields: Vec::new(),
        }
    }

    fn measured(mut self, measured: impl Into<String>) -> Self {
        self.measured = Some(measured.into());
        self
    }

    fn expected(mut self, expected: impl Into<String>) -> Self {
        self.expected = Some(expected.into());
        self
    }

    fn remedy(mut self, remedy: impl Into<String>) -> Self {
        self.remedy = Some(remedy.into());
        self
    }

    fn field(mut self, field: impl Into<String>) -> Self {
        self.fields.push(field.into());
        self
    }
}

impl DoctorCheck {
    fn new(
        id: impl Into<String>,
        category: impl Into<String>,
        status: CheckStatus,
        summary: impl Into<String>,
    ) -> Self {
        Self {
            id: id.into(),
            category: category.into(),
            status,
            summary: summary.into(),
            details: Vec::new(),
            issues: Vec::new(),
            remediation: None,
            duration_ms: 0,
        }
    }

    fn detail(mut self, detail: impl Into<String>) -> Self {
        self.details.push(detail.into());
        self
    }

    fn details(mut self, details: Vec<String>) -> Self {
        self.details.extend(details);
        self
    }

    fn remediation(mut self, remediation: impl Into<String>) -> Self {
        self.remediation = Some(remediation.into());
        self
    }

    fn issue(mut self, issue: DoctorIssue) -> Self {
        self.issues.push(issue);
        self
    }
}

/// Builds, renders, and exits according to the current doctor report.
///
/// This is the CLI entry point for codex doctor. It does not repair issues;
/// failures are represented in the report and cause a non-zero process exit so
/// scripts can distinguish a clean environment from one that needs attention.
pub async fn run_doctor(
    command: DoctorCommand,
    root_config_overrides: CliConfigOverrides,
    interactive: &TuiCli,
    arg0_paths: &Arg0DispatchPaths,
) -> anyhow::Result<()> {
    let report = build_report(&command, root_config_overrides, interactive, arg0_paths).await;

    if command.json {
        println!(
            "{}",
            serde_json::to_string_pretty(&redacted_json_report(&report))?
        );
    } else {
        print!(
            "{}",
            render_human_report(&report, human_output_options(&command))
        );
    }

    if report.overall_status == CheckStatus::Fail {
        std::process::exit(1);
    }

    Ok(())
}

async fn build_report(
    command: &DoctorCommand,
    root_config_overrides: CliConfigOverrides,
    interactive: &TuiCli,
    arg0_paths: &Arg0DispatchPaths,
) -> DoctorReport {
    let progress = doctor_progress(command.json);
    let mut checks = Vec::new();
    checks.push(run_sync_check("system", progress.clone(), system_check));
    checks.push(run_sync_check("installation", progress.clone(), || {
        installation_check(!command.summary)
    }));
    checks.push(run_sync_check("runtime", progress.clone(), runtime_check));
    checks.push(run_sync_check("search", progress.clone(), search_check));

    progress.begin("config");
    let config_result = load_config(root_config_overrides, interactive, arg0_paths).await;
    match &config_result {
        Ok(config) => {
            let auth_manager =
                AuthManager::shared_from_config(config, /*enable_codex_api_key_env*/ true).await;
            let reachability_plan = provider_reachability_plan(config);
            let (
                config_check,
                auth_check,
                updates_check,
                network_check,
                websocket_check,
                mcp_check,
                sandbox_check,
                terminal_check,
                git_check,
                terminal_title_check,
                state_check,
                thread_inventory_check,
                background_server_check,
                reachability_check,
            ) = tokio::join!(
                async { run_sync_check("config", progress.clone(), || config_check(config)) },
                async { run_sync_check("auth", progress.clone(), || auth_check(config)) },
                async { run_sync_check("updates", progress.clone(), || updates_check(config)) },
                async { run_sync_check("network", progress.clone(), network_check) },
                run_async_check(
                    "websocket",
                    progress.clone(),
                    websocket_reachability_check(config, Some(auth_manager)),
                ),
                run_async_check("MCP", progress.clone(), mcp_check(config)),
                async {
                    run_sync_check("sandbox", progress.clone(), || {
                        sandbox_check(config, arg0_paths)
                    })
                },
                async {
                    run_sync_check("terminal", progress.clone(), || {
                        terminal_check(command.no_color)
                    })
                },
                run_async_check("git", progress.clone(), git_check(config.cwd.as_path())),
                async {
                    run_sync_check("terminal title", progress.clone(), || {
                        terminal_title_check(config)
                    })
                },
                run_async_check("state", progress.clone(), state_check(config)),
                run_async_check(
                    "thread inventory",
                    progress.clone(),
                    thread_inventory_check(config),
                ),
                run_async_check(
                    "app-server",
                    progress.clone(),
                    background_server_check(config)
                ),
                run_async_check(
                    "provider reachability",
                    progress.clone(),
                    provider_reachability_check(reachability_plan),
                ),
            );
            checks.extend([
                config_check,
                auth_check,
                updates_check,
                network_check,
                websocket_check,
                mcp_check,
                sandbox_check,
                terminal_check,
                git_check,
                terminal_title_check,
                state_check,
                thread_inventory_check,
                background_server_check,
                reachability_check,
            ]);
        }
        Err(err) => {
            let reachability_plan = default_reachability_plan();
            let fallback_cwd = interactive
                .cwd
                .clone()
                .unwrap_or_else(|| env::current_dir().unwrap_or_else(|_| PathBuf::from(".")));
            let (
                config_check,
                network_check,
                terminal_check,
                git_check,
                state_check,
                reachability_check,
            ) = tokio::join!(
                async {
                    run_sync_check("config", progress.clone(), || {
                        DoctorCheck::new(
                            "config.load",
                            "config",
                            CheckStatus::Fail,
                            "config could not be loaded",
                        )
                        .detail(err.to_string())
                        .remediation("Fix the reported config error, then rerun codex doctor.")
                    })
                },
                async { run_sync_check("network", progress.clone(), network_check) },
                async {
                    run_sync_check("terminal", progress.clone(), || {
                        terminal_check(command.no_color)
                    })
                },
                run_async_check("git", progress.clone(), git_check(fallback_cwd.as_path())),
                async { run_sync_check("state", progress.clone(), fallback_state_check) },
                run_async_check(
                    "provider reachability",
                    progress.clone(),
                    provider_reachability_check(reachability_plan),
                ),
            );
            checks.extend([
                config_check,
                network_check,
                terminal_check,
                git_check,
                state_check,
                reachability_check,
            ]);
        }
    }

    progress.settle();

    let overall_status = overall_status(&checks);
    DoctorReport {
        schema_version: 1,
        generated_at: generated_at(),
        overall_status,
        codex_version: env!("CARGO_PKG_VERSION").to_string(),
        checks,
    }
}

async fn load_config(
    root_config_overrides: CliConfigOverrides,
    interactive: &TuiCli,
    arg0_paths: &Arg0DispatchPaths,
) -> anyhow::Result<Config> {
    let mut cli_kv_overrides = root_config_overrides
        .parse_overrides()
        .map_err(anyhow::Error::msg)?;
    if interactive.web_search {
        cli_kv_overrides.push((
            "web_search".to_string(),
            toml::Value::String("live".to_string()),
        ));
    }

    let overrides = ConfigOverrides {
        ephemeral: Some(true),
        ..config_overrides_from_interactive(interactive, arg0_paths)
    };

    ConfigBuilder::default()
        .cli_overrides(cli_kv_overrides)
        .harness_overrides(overrides)
        .build()
        .await
        .context("failed to load Codex config")
}

fn config_overrides_from_interactive(
    interactive: &TuiCli,
    arg0_paths: &Arg0DispatchPaths,
) -> ConfigOverrides {
    let approval_policy = if interactive.dangerously_bypass_approvals_and_sandbox {
        Some(AskForApproval::Never)
    } else {
        interactive.approval_policy.map(Into::into)
    };
    let sandbox_mode = if interactive.dangerously_bypass_approvals_and_sandbox {
        Some(lemurclaw_core::protocol::config_types::SandboxMode::DangerFullAccess)
    } else {
        interactive.sandbox_mode.map(Into::into)
    };
    ConfigOverrides {
        model: interactive.model.clone(),
        approval_policy,
        sandbox_mode,
        cwd: interactive.cwd.clone(),
        model_provider: interactive
            .oss
            .then(|| interactive.oss_provider.clone())
            .flatten(),
        codex_self_exe: arg0_paths.codex_self_exe.clone(),
        codex_linux_sandbox_exe: arg0_paths.codex_linux_sandbox_exe.clone(),
        main_execve_wrapper_exe: arg0_paths.main_execve_wrapper_exe.clone(),
        show_raw_agent_reasoning: interactive.oss.then_some(true),
        additional_writable_roots: interactive.add_dir.clone(),
        ..Default::default()
    }
}

/// JSON support report emitted by `codex doctor --json`.
///
/// The report is keyed by check id so support tooling can fetch paths like
/// `checks["terminal.metadata"]` without scanning arrays. Human rendering can
/// reorder or group rows independently, but this JSON shape should stay stable
/// across cosmetic output changes.
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct JsonDoctorReport {
    schema_version: u32,
    generated_at: String,
    overall_status: CheckStatus,
    codex_version: String,
    checks: BTreeMap<String, JsonDoctorCheck>,
}

/// One redacted check in the JSON support report.
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct JsonDoctorCheck {
    id: String,
    category: String,
    status: CheckStatus,
    summary: String,
    details: BTreeMap<String, JsonDetailValue>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    issues: Vec<JsonDoctorIssue>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    notes: Vec<String>,
    remediation: Option<String>,
    duration_ms: u64,
}

/// One redacted issue in the JSON support report.
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct JsonDoctorIssue {
    severity: CheckStatus,
    cause: String,
    measured: Option<String>,
    expected: Option<String>,
    remedy: Option<String>,
    fields: Vec<String>,
}

/// JSON detail value that preserves repeated detail keys without inventing names.
#[derive(Clone, Debug, Serialize)]
#[serde(untagged)]
enum JsonDetailValue {
    One(String),
    Many(Vec<String>),
}

impl JsonDetailValue {
    fn push(&mut self, value: String) {
        match self {
            JsonDetailValue::One(previous) => {
                *self = JsonDetailValue::Many(vec![std::mem::take(previous), value]);
            }
            JsonDetailValue::Many(values) => values.push(value),
        }
    }
}

fn redacted_json_report(report: &DoctorReport) -> JsonDoctorReport {
    let checks = report
        .checks
        .iter()
        .map(|check| {
            let json_check = redacted_json_check(check);
            (check.id.clone(), json_check)
        })
        .collect();
    JsonDoctorReport {
        schema_version: report.schema_version,
        generated_at: report.generated_at.clone(),
        overall_status: report.overall_status,
        codex_version: report.codex_version.clone(),
        checks,
    }
}

fn redacted_json_check(check: &DoctorCheck) -> JsonDoctorCheck {
    let (details, notes) = structured_json_details(&check.details);
    JsonDoctorCheck {
        id: check.id.clone(),
        category: check.category.clone(),
        status: check.status,
        summary: check.summary.clone(),
        details,
        issues: check.issues.iter().map(redacted_json_issue).collect(),
        notes,
        remediation: check.remediation.as_deref().map(redact_detail),
        duration_ms: check.duration_ms,
    }
}

fn redacted_json_issue(issue: &DoctorIssue) -> JsonDoctorIssue {
    JsonDoctorIssue {
        severity: issue.severity,
        cause: redact_detail(&issue.cause),
        measured: issue.measured.as_deref().map(redact_detail),
        expected: issue.expected.as_deref().map(redact_detail),
        remedy: issue.remedy.as_deref().map(redact_detail),
        fields: issue
            .fields
            .iter()
            .map(|field| redact_detail(field))
            .collect(),
    }
}

/// Converts redacted `label: value` detail strings into JSON key/value fields.
///
/// Detail strings that do not follow the doctor detail convention are preserved
/// as notes instead of being dropped. Repeated labels become arrays so callers
/// can still retrieve the common scalar case directly while keeping all values.
fn structured_json_details(details: &[String]) -> (BTreeMap<String, JsonDetailValue>, Vec<String>) {
    let mut structured: BTreeMap<String, JsonDetailValue> = BTreeMap::new();
    let mut notes = Vec::new();
    for detail in details {
        let redacted = redact_detail(detail);
        let Some((key, value)) = redacted.split_once(": ") else {
            notes.push(redacted);
            continue;
        };
        let key = key.trim();
        if key.is_empty() {
            notes.push(redacted);
            continue;
        }
        let value = json_detail_value(key, value);
        match structured.get_mut(key) {
            Some(existing) => existing.push(value),
            None => {
                structured.insert(key.to_string(), JsonDetailValue::One(value));
            }
        }
    }
    (structured, notes)
}

fn json_detail_value(key: &str, value: &str) -> String {
    if matches!(
        key,
        "VISUAL" | "EDITOR" | "PAGER" | "GIT_PAGER" | "GH_PAGER" | "LESS"
    ) && !value.eq_ignore_ascii_case("not set")
    {
        // Editor and pager configuration can contain arbitrary arguments or
        // inline environment assignments. Keep full values local to human output
        // because the JSON report may be attached to feedback.
        "set".to_string()
    } else {
        value.to_string()
    }
}

fn run_sync_check(
    label: &'static str,
    progress: Arc<dyn DoctorProgress>,
    f: impl FnOnce() -> DoctorCheck,
) -> DoctorCheck {
    progress.begin(label);
    let start = Instant::now();
    let mut check = f();
    check.duration_ms = start.elapsed().as_millis().try_into().unwrap_or(u64::MAX);
    progress.finish(label, check.status);
    check
}

async fn run_async_check<Fut>(
    label: &'static str,
    progress: Arc<dyn DoctorProgress>,
    future: Fut,
) -> DoctorCheck
where
    Fut: Future<Output = DoctorCheck>,
{
    progress.begin(label);
    let start = Instant::now();
    tokio::pin!(future);
    let mut progress_interval = tokio::time::interval(SLOW_CHECK_PROGRESS_INTERVAL);
    loop {
        tokio::select! {
            mut check = &mut future => {
                check.duration_ms = start.elapsed().as_millis().try_into().unwrap_or(u64::MAX);
                progress.finish(label, check.status);
                return check;
            }
            _ = progress_interval.tick() => {
                let elapsed = start.elapsed();
                if elapsed >= SLOW_CHECK_PROGRESS_THRESHOLD {
                    progress.heartbeat(label, elapsed);
                }
            }
        }
    }
}

fn overall_status(checks: &[DoctorCheck]) -> CheckStatus {
    if checks.iter().any(|check| check.status == CheckStatus::Fail) {
        CheckStatus::Fail
    } else if checks
        .iter()
        .any(|check| check.status == CheckStatus::Warning)
    {
        CheckStatus::Warning
    } else {
        CheckStatus::Ok
    }
}

fn generated_at() -> String {
    match std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH) {
        Ok(duration) => {
            let seconds = duration.as_secs();
            format!("{seconds}s since unix epoch")
        }
        Err(_) => "unknown".to_string(),
    }
}

fn installation_check(show_details: bool) -> DoctorCheck {
    let mut details = Vec::new();
    let current_exe = env::current_exe().ok();
    push_path_detail(&mut details, "current executable", current_exe.as_deref());
    let inherited_managed_env = inherited_managed_env_for_cargo_binary(current_exe.as_deref());
    let install_context = doctor_install_context(current_exe.as_deref());
    details.push(format!(
        "install context: {}",
        describe_install_context(&install_context)
    ));
    if inherited_managed_env {
        details.push(
            "ignored inherited package-manager launch env for cargo-built binary".to_string(),
        );
    }
    details.push(format!(
        "managed by npm: {}",
        doctor_managed_by_npm(current_exe.as_deref())
    ));
    details.push(format!(
        "managed by bun: {}",
        env::var_os("CODEX_MANAGED_BY_BUN").is_some()
    ));
    details.push(format!(
        "managed by pnpm: {}",
        env::var_os("CODEX_MANAGED_BY_PNPM").is_some()
    ));
    push_env_path_detail(
        &mut details,
        "managed package root",
        "CODEX_MANAGED_PACKAGE_ROOT",
    );

    let path_entries = codex_path_entries();
    let mut status = CheckStatus::Ok;
    let mut summary = "installation looks consistent".to_string();
    let mut remediation = None;

    if path_entries.len() > 1 {
        details.push(format!("PATH codex entries: {}", path_entries.len()));
    }
    if show_details || path_entries.len() > 1 {
        details.extend(
            path_entries
                .iter()
                .enumerate()
                .map(|(index, path)| format!("PATH codex #{}: {path}", index + 1)),
        );
    }

    if doctor_managed_by_npm(current_exe.as_deref()) {
        match npm_global_root_check() {
            NpmRootCheck::Match { package_root } => {
                details.push(format!("npm update target: {}", package_root.display()));
            }
            NpmRootCheck::Mismatch {
                running_package_root,
                npm_package_root,
            } => {
                status = CheckStatus::Fail;
                summary =
                    "npm install -g @openai/codex would update a different install".to_string();
                remediation = Some(format!(
                    "Fix PATH or npm prefix so the running package root ({}) matches the npm global package root ({}).",
                    running_package_root.display(),
                    npm_package_root.display()
                ));
                details.push(format!(
                    "running package root: {}",
                    running_package_root.display()
                ));
                details.push(format!("npm package root: {}", npm_package_root.display()));
            }
            NpmRootCheck::MissingPackageRoot => {
                status = status.max(CheckStatus::Warning);
                summary = "npm-managed launch is missing package-root provenance".to_string();
                remediation = Some(
                    "Reinstall or update Codex so the JS shim provides CODEX_MANAGED_PACKAGE_ROOT."
                        .to_string(),
                );
            }
            NpmRootCheck::NpmUnavailable(error) => {
                status = status.max(CheckStatus::Warning);
                summary = "npm-managed launch could not inspect npm global root".to_string();
                details.push(format!("npm root -g failed: {error}"));
            }
        }
    }

    let mut check = DoctorCheck::new("installation", "install", status, summary).details(details);
    if let Some(remediation) = remediation {
        check = check.remediation(remediation);
    }
    check
}

fn doctor_install_context(current_exe: Option<&Path>) -> InstallContext {
    if inherited_managed_env_for_cargo_binary(current_exe) {
        InstallContext {
            method: InstallMethod::Other,
            package_layout: None,
        }
    } else {
        InstallContext::current().clone()
    }
}

fn doctor_managed_by_npm(current_exe: Option<&Path>) -> bool {
    env::var_os("CODEX_MANAGED_BY_NPM").is_some()
        && !inherited_managed_env_for_cargo_binary(current_exe)
}

fn inherited_managed_env_for_cargo_binary(current_exe: Option<&Path>) -> bool {
    if env::var_os("CODEX_MANAGED_BY_NPM").is_none()
        && env::var_os("CODEX_MANAGED_BY_BUN").is_none()
        && env::var_os("CODEX_MANAGED_BY_PNPM").is_none()
    {
        return false;
    }

    let Some(current_exe) = current_exe else {
        return false;
    };
    let components = current_exe
        .components()
        .map(|component| component.as_os_str().to_string_lossy())
        .collect::<Vec<_>>();
    components
        .windows(2)
        .any(|window| window[0] == "target" && matches!(window[1].as_ref(), "debug" | "release"))
}

fn describe_install_context(context: &InstallContext) -> String {
    match &context.method {
        InstallMethod::Standalone {
            release_dir,
            resources_dir,
            platform,
        } => {
            let platform = match platform {
                StandalonePlatform::Unix => "unix",
                StandalonePlatform::Windows => "windows",
            };
            match &context.package_layout {
                Some(package_layout) => {
                    let resources = display_optional_path(package_layout.resources_dir.as_deref());
                    let path = display_optional_path(package_layout.path_dir.as_deref());
                    format!(
                        "standalone ({platform}, package {}, bin {}, resources {resources}, path {path})",
                        package_layout.package_dir.display(),
                        package_layout.bin_dir.display()
                    )
                }
                None => {
                    let resources = display_optional_path(resources_dir.as_deref());
                    format!(
                        "standalone ({platform}, release {}, resources {resources})",
                        release_dir.display()
                    )
                }
            }
        }
        InstallMethod::Npm => {
            describe_method_with_package_layout("npm", context.package_layout.as_ref())
        }
        InstallMethod::Bun => {
            describe_method_with_package_layout("bun", context.package_layout.as_ref())
        }
        InstallMethod::Pnpm => {
            describe_method_with_package_layout("pnpm", context.package_layout.as_ref())
        }
        InstallMethod::Brew => {
            describe_method_with_package_layout("brew", context.package_layout.as_ref())
        }
        InstallMethod::Other => {
            describe_method_with_package_layout("other", context.package_layout.as_ref())
        }
    }
}

fn describe_method_with_package_layout(
    method: &str,
    package_layout: Option<&CodexPackageLayout>,
) -> String {
    match package_layout {
        Some(package_layout) => {
            let resources = display_optional_path(package_layout.resources_dir.as_deref());
            let path = display_optional_path(package_layout.path_dir.as_deref());
            format!(
                "{method} (package {}, bin {}, resources {resources}, path {path})",
                package_layout.package_dir.display(),
                package_layout.bin_dir.display()
            )
        }
        None => method.to_string(),
    }
}

fn display_optional_path(path: Option<&Path>) -> String {
    path.map(|path| path.display().to_string())
        .unwrap_or_else(|| "none".to_string())
}

#[derive(Debug, PartialEq, Eq)]
enum NpmRootCheck {
    Match {
        package_root: PathBuf,
    },
    Mismatch {
        running_package_root: PathBuf,
        npm_package_root: PathBuf,
    },
    MissingPackageRoot,
    NpmUnavailable(String),
}

fn npm_global_root_check() -> NpmRootCheck {
    let Some(running_package_root) = env::var_os("CODEX_MANAGED_PACKAGE_ROOT").map(PathBuf::from)
    else {
        return NpmRootCheck::MissingPackageRoot;
    };

    let output = match run_command(NPM_COMMAND, ["root", "-g"]) {
        Ok(output) => output,
        Err(err) => return NpmRootCheck::NpmUnavailable(err),
    };
    let Some(npm_root) = output.lines().map(str::trim).find(|line| !line.is_empty()) else {
        return NpmRootCheck::NpmUnavailable("empty output from npm root -g".to_string());
    };

    compare_npm_package_roots(&running_package_root, &PathBuf::from(npm_root))
}

fn compare_npm_package_roots(running_package_root: &Path, npm_root: &Path) -> NpmRootCheck {
    let npm_package_root = npm_root.join("@openai").join("codex");
    let running = normalize_path_for_compare(running_package_root);
    let target = normalize_path_for_compare(&npm_package_root);
    if running == target {
        NpmRootCheck::Match {
            package_root: npm_package_root,
        }
    } else {
        NpmRootCheck::Mismatch {
            running_package_root: running_package_root.to_path_buf(),
            npm_package_root,
        }
    }
}

fn normalize_path_for_compare(path: &Path) -> String {
    let canonical = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
    let raw = canonical.to_string_lossy().replace('\\', "/");
    if cfg!(windows) {
        raw.to_ascii_lowercase()
    } else {
        raw
    }
}

fn display_list<T: AsRef<str>>(items: &[T]) -> String {
    if items.is_empty() {
        "none".to_string()
    } else {
        items
            .iter()
            .map(AsRef::as_ref)
            .collect::<Vec<_>>()
            .join(", ")
    }
}

fn codex_path_entries() -> Vec<String> {
    #[cfg(windows)]
    let result = run_command("where", ["codex"]);
    #[cfg(not(windows))]
    let result = run_command("which", ["-a", "codex"]);

    result
        .unwrap_or_default()
        .lines()
        .map(str::trim)
        .filter(|line| !line.is_empty())
        .map(str::to_string)
        .collect()
}

fn run_command<I, S>(program: &str, args: I) -> Result<String, String>
where
    I: IntoIterator<Item = S>,
    S: AsRef<OsStr>,
{
    let output = Command::new(program)
        .args(args)
        .output()
        .map_err(|err| err.to_string())?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
        if stderr.is_empty() {
            return Err(format!("exited with status {}", output.status));
        }
        return Err(stderr);
    }
    Ok(String::from_utf8_lossy(&output.stdout).to_string())
}

fn config_check(config: &Config) -> DoctorCheck {
    let mut details = Vec::new();
    details.push(format!("CODEX_HOME: {}", config.codex_home.display()));
    details.push(format!("cwd: {}", config.cwd.display()));
    details.push(format!(
        "model: {}",
        config.model.as_deref().unwrap_or("<default>")
    ));
    details.push(format!("model provider: {}", config.model_provider_id));
    details.push(format!("log dir: {}", config.log_dir.display()));
    details.push(format!("sqlite home: {}", config.sqlite_home.display()));
    details.push(format!("mcp servers: {}", config.mcp_servers.get().len()));
    feature_flag_details(config, &mut details);
    config_toml_details(config, &mut details);

    let status = if config.startup_warnings.is_empty() {
        CheckStatus::Ok
    } else {
        push_startup_warning_counts(&mut details, &config.startup_warnings);
        details.extend(
            config
                .startup_warnings
                .iter()
                .map(|warning| format!("startup warning: {warning}")),
        );
        CheckStatus::Warning
    };

    DoctorCheck::new("config.load", "config", status, "config loaded").details(details)
}

fn push_startup_warning_counts(details: &mut Vec<String>, warnings: &[String]) {
    details.push(format!("startup warnings: {}", warnings.len()));
    for (label, needle) in [
        ("startup warning skills", "skill"),
        ("startup warning hooks", "hook"),
        ("startup warning plugins", "plugin"),
        ("startup warning MCP", "mcp"),
        ("startup warning deprecated", "deprecated"),
    ] {
        let count = warnings
            .iter()
            .filter(|warning| warning.to_ascii_lowercase().contains(needle))
            .count();
        details.push(format!("{label}: {count}"));
    }
}

fn feature_flag_details(config: &Config, details: &mut Vec<String>) {
    let features = config.features.get();
    let enabled_features = FEATURES
        .iter()
        .filter(|spec| features.enabled(spec.id))
        .map(|spec| spec.key)
        .collect::<Vec<_>>();
    let overrides = FEATURES
        .iter()
        .filter(|spec| features.enabled(spec.id) != spec.default_enabled)
        .map(|spec| format!("{}={}", spec.key, features.enabled(spec.id)))
        .collect::<Vec<_>>();
    details.push(format!("feature flags enabled: {}", enabled_features.len()));
    details.push(format!(
        "enabled feature flags: {}",
        display_list(&enabled_features)
    ));
    details.push(format!(
        "feature flag overrides: {}",
        display_list(&overrides)
    ));
    for usage in features.legacy_feature_usages() {
        details.push(format!(
            "legacy feature flag: {} -> {}",
            usage.alias,
            usage.feature.key()
        ));
    }
}

fn config_toml_details(config: &Config, details: &mut Vec<String>) {
    let config_path = config.codex_home.join(lemurclaw_core::config::CONFIG_TOML_FILE);
    details.push(format!("config.toml: {}", config_path.display()));
    match std::fs::read_to_string(&config_path) {
        Ok(contents) => match toml::from_str::<toml::Value>(&contents) {
            Ok(_) => details.push("config.toml parse: ok".to_string()),
            Err(err) => details.push(format!("config.toml parse: {err}")),
        },
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
            details.push("config.toml: missing".to_string());
        }
        Err(err) => details.push(format!("config.toml read: {err}")),
    }
}

fn auth_check(config: &Config) -> DoctorCheck {
    let mut details = Vec::new();
    let auth_path = config.codex_home.join("auth.json");
    details.push(format!(
        "auth storage mode: {:?}",
        config.cli_auth_credentials_store_mode
    ));
    details.push(format!("auth file: {}", auth_path.display()));

    let env_auth_vars = [
        OPENAI_API_KEY_ENV_VAR,
        CODEX_API_KEY_ENV_VAR,
        CODEX_ACCESS_TOKEN_ENV_VAR,
    ]
    .into_iter()
    .filter(|name| env_var_present(name))
    .collect::<Vec<_>>();
    if !env_auth_vars.is_empty() {
        details.push(format!(
            "auth env vars present: {}",
            env_auth_vars.join(", ")
        ));
    }
    if let Some(check) = provider_specific_auth_check(
        config.model_provider.requires_openai_auth,
        config.model_provider.env_key.as_deref(),
        config.model_provider.env_key_instructions.as_deref(),
        details.clone(),
        env_var_present,
    ) {
        return check;
    }

    match load_auth_dot_json(
        &config.codex_home,
        config.cli_auth_credentials_store_mode,
        config.auth_keyring_backend_kind(),
    ) {
        Ok(Some(auth)) => {
            details.push(format!("stored auth mode: {}", stored_auth_mode(&auth)));
            details.push(format!("stored API key: {}", auth.openai_api_key.is_some()));
            details.push(format!("stored ChatGPT tokens: {}", auth.tokens.is_some()));
            details.push(format!(
                "stored agent identity: {}",
                auth.agent_identity.is_some()
            ));
            let auth_issues = stored_auth_issues(&auth, env_var_present);
            details.extend(
                auth_issues
                    .iter()
                    .map(|issue| format!("stored auth issue: {issue}")),
            );
            let status = if !auth_issues.is_empty() && env_auth_vars.is_empty() {
                CheckStatus::Fail
            } else if !auth_issues.is_empty() || env_auth_vars.len() > 1 {
                CheckStatus::Warning
            } else {
                CheckStatus::Ok
            };
            let summary = match status {
                CheckStatus::Ok => "auth is configured",
                CheckStatus::Warning if !auth_issues.is_empty() => {
                    "auth is provided by environment, but stored credentials are incomplete"
                }
                CheckStatus::Warning => {
                    "auth is configured, but multiple auth env vars are present"
                }
                CheckStatus::Fail => "stored credentials are incomplete",
            };
            let mut check =
                DoctorCheck::new("auth.credentials", "auth", status, summary).details(details);
            if status == CheckStatus::Fail {
                check =
                    check.remediation("Run codex login again or provide a supported auth env var.");
            }
            check
        }
        Ok(None) if !env_auth_vars.is_empty() => DoctorCheck::new(
            "auth.credentials",
            "auth",
            CheckStatus::Ok,
            "auth is provided by environment",
        )
        .details(details),
        Ok(None) => DoctorCheck::new(
            "auth.credentials",
            "auth",
            CheckStatus::Fail,
            "no Codex credentials were found",
        )
        .details(details)
        .remediation("Run codex login or provide an API key through a supported auth env var."),
        Err(err) => DoctorCheck::new(
            "auth.credentials",
            "auth",
            CheckStatus::Fail,
            "stored credentials could not be read",
        )
        .detail(err.to_string())
        .remediation("Fix auth storage access or run codex login again."),
    }
}

fn provider_specific_auth_check(
    requires_openai_auth: bool,
    provider_env_key: Option<&str>,
    provider_env_key_instructions: Option<&str>,
    mut details: Vec<String>,
    env_var_present: impl Fn(&str) -> bool,
) -> Option<DoctorCheck> {
    details.push(format!(
        "model provider requires OpenAI auth: {requires_openai_auth}"
    ));
    if requires_openai_auth {
        return None;
    }

    match provider_env_key {
        Some(env_key) if env_var_present(env_key) => {
            details.push(format!("provider auth env var: {env_key} (present)"));
            Some(
                DoctorCheck::new(
                    "auth.credentials",
                    "auth",
                    CheckStatus::Ok,
                    "auth is provided by the active model provider",
                )
                .details(details),
            )
        }
        Some(env_key) => {
            details.push(format!("provider auth env var: {env_key} (missing)"));
            let remediation = provider_env_key_instructions
                .map(str::to_string)
                .unwrap_or_else(|| format!("Set {env_key} for the active model provider."));
            Some(
                DoctorCheck::new(
                    "auth.credentials",
                    "auth",
                    CheckStatus::Fail,
                    "active model provider auth env var is missing",
                )
                .details(details)
                .remediation(remediation),
            )
        }
        None => Some(
            DoctorCheck::new(
                "auth.credentials",
                "auth",
                CheckStatus::Ok,
                "OpenAI auth is not required for the active model provider",
            )
            .details(details),
        ),
    }
}

fn stored_auth_mode(auth: &lemurclaw_core::login::AuthDotJson) -> &'static str {
    match stored_auth_mode_value(auth) {
        AuthMode::ApiKey => "api_key",
        AuthMode::Chatgpt => "chatgpt",
        AuthMode::ChatgptAuthTokens => "chatgpt_auth_tokens",
        AuthMode::Headers => "headers",
        AuthMode::AgentIdentity => "agent_identity",
        AuthMode::PersonalAccessToken => "personal_access_token",
        AuthMode::BedrockApiKey => "bedrock_api_key",
    }
}

fn stored_auth_mode_value(auth: &AuthDotJson) -> AuthMode {
    if let Some(mode) = auth.auth_mode {
        return mode;
    }
    if auth.personal_access_token.is_some() {
        AuthMode::PersonalAccessToken
    } else if auth.bedrock_api_key.is_some() {
        AuthMode::BedrockApiKey
    } else if auth.openai_api_key.is_some() {
        AuthMode::ApiKey
    } else {
        AuthMode::Chatgpt
    }
}

fn stored_auth_issues(
    auth: &AuthDotJson,
    env_var_present: impl Fn(&str) -> bool,
) -> Vec<&'static str> {
    let mut issues = Vec::new();
    match stored_auth_mode_value(auth) {
        AuthMode::ApiKey => {
            let stored_key_present = auth
                .openai_api_key
                .as_deref()
                .is_some_and(|key| !key.trim().is_empty());
            let env_key_present =
                env_var_present(OPENAI_API_KEY_ENV_VAR) || env_var_present(CODEX_API_KEY_ENV_VAR);
            if !stored_key_present && !env_key_present {
                issues.push("API key auth is missing an API key");
            }
        }
        AuthMode::Chatgpt => {
            match auth.tokens.as_ref() {
                Some(tokens) => {
                    if tokens.access_token.trim().is_empty() {
                        issues.push("ChatGPT auth is missing an access token");
                    }
                    if tokens.refresh_token.trim().is_empty() {
                        issues.push("ChatGPT auth is missing a refresh token");
                    }
                }
                None => issues.push("ChatGPT auth is missing token data"),
            }
            if auth.last_refresh.is_none() {
                issues.push("ChatGPT auth is missing refresh metadata");
            }
        }
        AuthMode::ChatgptAuthTokens => {
            match auth.tokens.as_ref() {
                Some(tokens) => {
                    if tokens.access_token.trim().is_empty() {
                        issues.push("external ChatGPT auth is missing an access token");
                    }
                    if tokens.account_id.is_none() && tokens.id_token.chatgpt_account_id.is_none() {
                        issues.push("external ChatGPT auth is missing a ChatGPT account id");
                    }
                }
                None => issues.push("external ChatGPT auth is missing token data"),
            }
            if auth.last_refresh.is_none() {
                issues.push("external ChatGPT auth is missing refresh metadata");
            }
        }
        AuthMode::Headers => {
            issues.push("header auth cannot be loaded from auth storage");
        }
        AuthMode::AgentIdentity => {
            if auth
                .agent_identity
                .as_ref()
                .is_none_or(|agent_identity| !agent_identity.has_auth_material())
            {
                issues.push("agent identity auth is missing an agent identity token");
            }
        }
        AuthMode::PersonalAccessToken => {
            if auth
                .personal_access_token
                .as_deref()
                .is_none_or(|token| token.trim().is_empty())
            {
                issues.push("personal access token auth is missing a personal access token");
            }
        }
        AuthMode::BedrockApiKey => {
            if auth.bedrock_api_key.is_none() {
                issues.push("Bedrock API key auth is missing a Bedrock API key");
            }
        }
    }
    issues
}

fn network_check() -> DoctorCheck {
    let mut details = Vec::new();
    push_proxy_env_details(&mut details);

    let mut status = CheckStatus::Ok;
    let mut summary = "network-related environment looks readable".to_string();
    for name in ["CODEX_CA_CERTIFICATE", "SSL_CERT_FILE"] {
        if let Some(raw) = env::var_os(name) {
            let path = PathBuf::from(raw);
            match std::fs::metadata(&path) {
                Ok(metadata) if metadata.is_file() => {
                    if let Err(err) = read_probe_file(&path) {
                        status = CheckStatus::Warning;
                        summary = "custom CA env var points at an unreadable file".to_string();
                        details.push(format!("{name}: {} ({err})", path.display()));
                    } else {
                        details.push(format!("{name}: readable file {}", path.display()));
                    }
                }
                Ok(_) => {
                    status = CheckStatus::Warning;
                    summary = "custom CA env var does not point at a file".to_string();
                    details.push(format!("{name}: not a file {}", path.display()));
                }
                Err(err) => {
                    status = CheckStatus::Warning;
                    summary = "custom CA env var points at an unreadable path".to_string();
                    details.push(format!("{name}: {} ({err})", path.display()));
                }
            }
        }
    }

    DoctorCheck::new("network.env", "network", status, summary).details(details)
}

fn push_proxy_env_details(details: &mut Vec<String>) {
    let present_proxy_vars = PROXY_ENV_VARS
        .iter()
        .copied()
        .filter(|name| env_var_present(name))
        .collect::<Vec<_>>();
    if present_proxy_vars.is_empty() {
        details.push("proxy env vars: none".to_string());
    } else {
        details.push(format!(
            "proxy env vars present: {}",
            present_proxy_vars.join(", ")
        ));
    }
}

fn read_probe_file(path: &Path) -> std::io::Result<()> {
    let mut file = std::fs::File::open(path)?;
    let mut buffer = [0_u8; 1];
    let _ = file.read(&mut buffer)?;
    Ok(())
}

async fn mcp_check(config: &Config) -> DoctorCheck {
    mcp_check_from_servers(config.mcp_servers.get()).await
}

async fn mcp_check_from_servers(servers: &HashMap<String, McpServerConfig>) -> DoctorCheck {
    if servers.is_empty() {
        return DoctorCheck::new(
            "mcp.config",
            "mcp",
            CheckStatus::Ok,
            "no MCP servers configured",
        );
    }

    let mut details = Vec::new();
    let mut transport_counts: BTreeMap<&'static str, usize> = BTreeMap::new();
    let mut disabled = 0usize;
    let mut missing_env = Vec::new();
    let mut unreachable_required_http = Vec::new();
    let mut unreachable_optional_http = Vec::new();

    for (name, server) in servers {
        let disabled_server = !server.enabled || server.disabled_reason.is_some();
        if disabled_server {
            disabled += 1;
        }
        match &server.transport {
            McpServerTransportConfig::Stdio {
                command,
                env,
                env_vars,
                cwd,
                ..
            } => {
                *transport_counts.entry("stdio").or_default() += 1;
                if disabled_server {
                    continue;
                }
                let command_is_empty = command.trim().is_empty();
                if command_is_empty {
                    missing_env.push(format!("{name}: stdio command is empty"));
                }
                if server.is_local_environment() {
                    let host_native_cwd = cwd.as_ref().map(|cwd| Path::new(cwd.as_str()));
                    if let Some(cwd) = host_native_cwd
                        && !cwd.exists()
                    {
                        missing_env.push(format!("{name}: cwd does not exist ({})", cwd.display()));
                    }
                    if !command_is_empty
                        && let Err(err) =
                            stdio_command_resolves(command, host_native_cwd, env.as_ref())
                    {
                        missing_env.push(format!(
                            "{name}: stdio command {command:?} is not resolvable ({err})"
                        ));
                    }
                } else {
                    match cwd {
                        Some(cwd) if cwd.to_inferred_path_uri().is_none() => {
                            missing_env
                                .push(format!("{name}: remote stdio cwd is not absolute ({cwd})"));
                        }
                        None => missing_env
                            .push(format!("{name}: remote stdio requires an explicit cwd")),
                        Some(_) => {}
                    }
                }
                if let Some(env) = env {
                    for key in env.keys().filter(|key| key.trim().is_empty()) {
                        missing_env.push(format!("{name}: empty env key {key}"));
                    }
                }
                for env_var in env_vars {
                    if env_var.is_remote_source() {
                        if server.is_local_environment() {
                            missing_env.push(format!(
                                "{name}: env_vars entry `{}` uses source `remote`, which requires remote MCP stdio",
                                env_var.name()
                            ));
                        }
                    } else if !env_var_present(env_var.name()) {
                        missing_env.push(format!("{name}: env var {} is not set", env_var.name()));
                    }
                }
            }
            McpServerTransportConfig::StreamableHttp {
                url,
                bearer_token_env_var,
                env_http_headers,
                ..
            } => {
                *transport_counts.entry("streamable_http").or_default() += 1;
                if disabled_server {
                    continue;
                }
                if let Some(env_var) = bearer_token_env_var
                    && !env_var_present(env_var)
                {
                    missing_env.push(format!("{name}: bearer token env var {env_var} is not set"));
                }
                if let Some(headers) = env_http_headers {
                    for env_var in headers.values() {
                        if !env_var_present(env_var) {
                            missing_env
                                .push(format!("{name}: header env var {env_var} is not set"));
                        }
                    }
                }
                if let Err(err) = mcp_http_probe_url(url).await {
                    let detail = format!("{name}: {url} ({err})");
                    if server.required {
                        unreachable_required_http.push(detail);
                    } else {
                        unreachable_optional_http.push(detail);
                    }
                }
            }
        }
    }

    details.push(format!("configured servers: {}", servers.len()));
    details.push(format!("disabled servers: {disabled}"));
    for (transport, count) in transport_counts {
        details.push(format!("{transport} servers: {count}"));
    }
    details.extend(missing_env.iter().cloned());
    details.extend(
        unreachable_required_http
            .iter()
            .map(|detail| format!("required reachability failed: {detail}")),
    );
    details.extend(
        unreachable_optional_http
            .iter()
            .map(|detail| format!("optional reachability failed: {detail}")),
    );

    let required_missing = servers.iter().any(|(name, server)| {
        server.required
            && missing_env
                .iter()
                .any(|missing| missing.starts_with(&format!("{name}:")))
    });
    let status = if required_missing || !unreachable_required_http.is_empty() {
        CheckStatus::Fail
    } else if !missing_env.is_empty() || !unreachable_optional_http.is_empty() {
        CheckStatus::Warning
    } else {
        CheckStatus::Ok
    };
    let summary = match status {
        CheckStatus::Ok => "MCP configuration is locally consistent",
        CheckStatus::Warning => "MCP configuration has optional issues",
        CheckStatus::Fail => "MCP configuration has failing required inputs or reachability",
    };

    let mut check = DoctorCheck::new("mcp.config", "mcp", status, summary).details(details);
    if status != CheckStatus::Ok {
        check = check.remediation("Set the missing MCP env vars or disable the affected server.");
    }
    check
}

fn sandbox_check(config: &Config, arg0_paths: &Arg0DispatchPaths) -> DoctorCheck {
    let mut details = Vec::new();
    details.push(format!(
        "approval policy: {:?}",
        config.permissions.approval_policy.value()
    ));
    let file_system_sandbox = config.permissions.file_system_sandbox_policy();
    details.push(format!("filesystem sandbox: {}", file_system_sandbox.kind));
    details.push(format!(
        "network sandbox: {}",
        config.permissions.network_sandbox_policy()
    ));
    push_path_detail(
        &mut details,
        "codex-linux-sandbox helper",
        arg0_paths.codex_linux_sandbox_exe.as_deref(),
    );
    push_path_detail(
        &mut details,
        "execve wrapper helper",
        arg0_paths.main_execve_wrapper_exe.as_deref(),
    );

    let mut status = CheckStatus::Ok;
    let mut summary = "sandbox configuration is readable".to_string();
    if let Some(helper) = arg0_paths.codex_linux_sandbox_exe.as_deref()
        && !helper.exists()
    {
        status = CheckStatus::Warning;
        summary = "Linux sandbox helper path does not exist".to_string();
    }

    DoctorCheck::new("sandbox.helpers", "sandbox", status, summary).details(details)
}

#[derive(Clone, Debug)]
struct TerminalCheckInputs {
    info: TerminalInfo,
    env: BTreeMap<String, String>,
    present_env: BTreeSet<String>,
    no_color_flag: bool,
    stdin_is_terminal: bool,
    stdout_is_terminal: bool,
    stderr_is_terminal: bool,
    stream_supports_color: bool,
    terminal_size: Result<(u16, u16), String>,
    tmux_details: Vec<String>,
    windows_console_details: Vec<String>,
}

impl TerminalCheckInputs {
    fn detect(no_color_flag: bool) -> Self {
        let names = terminal_env_names();
        let (env, present_env) = collect_env_snapshot(&names);
        let terminal_size = crossterm::terminal::size().map_err(|err| err.to_string());
        let info = terminal_info();
        let tmux_details = if matches!(info.multiplexer, Some(Multiplexer::Tmux { .. })) {
            tmux_diagnostic_details()
        } else {
            Vec::new()
        };
        let windows_console_details = windows_console_details();
        Self {
            info,
            env,
            present_env,
            no_color_flag,
            stdin_is_terminal: std::io::stdin().is_terminal(),
            stdout_is_terminal: std::io::stdout().is_terminal(),
            stderr_is_terminal: std::io::stderr().is_terminal(),
            stream_supports_color: supports_color::on(Stream::Stdout).is_some(),
            terminal_size,
            tmux_details,
            windows_console_details,
        }
    }

    fn env_value(&self, name: &str) -> Option<&str> {
        self.env.get(name).map(String::as_str)
    }

    fn env_present(&self, name: &str) -> bool {
        self.present_env.contains(name)
    }
}

fn terminal_check(no_color_flag: bool) -> DoctorCheck {
    terminal_check_from_inputs(TerminalCheckInputs::detect(no_color_flag))
}

#[cfg(windows)]
fn windows_console_details() -> Vec<String> {
    use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE;
    use windows_sys::Win32::System::Console::ENABLE_VIRTUAL_TERMINAL_PROCESSING;
    use windows_sys::Win32::System::Console::GetConsoleCP;
    use windows_sys::Win32::System::Console::GetConsoleMode;
    use windows_sys::Win32::System::Console::GetConsoleOutputCP;
    use windows_sys::Win32::System::Console::GetStdHandle;
    use windows_sys::Win32::System::Console::STD_ERROR_HANDLE;
    use windows_sys::Win32::System::Console::STD_OUTPUT_HANDLE;

    let mut details = Vec::new();
    details.push(format!("console input code page: {}", unsafe {
        GetConsoleCP()
    }));
    details.push(format!("console output code page: {}", unsafe {
        GetConsoleOutputCP()
    }));
    details.push(console_mode_detail("stdout console mode", unsafe {
        GetStdHandle(STD_OUTPUT_HANDLE)
    }));
    details.push(console_mode_detail("stderr console mode", unsafe {
        GetStdHandle(STD_ERROR_HANDLE)
    }));

    fn console_mode_detail(label: &str, handle: isize) -> String {
        if handle == 0 || handle == INVALID_HANDLE_VALUE {
            return format!("{label}: unavailable");
        }
        let mut mode = 0_u32;
        if unsafe { GetConsoleMode(handle, &mut mode) } == 0 {
            return format!("{label}: unavailable");
        }
        let vt_enabled = mode & ENABLE_VIRTUAL_TERMINAL_PROCESSING != 0;
        format!("{label}: 0x{mode:08x} (VT processing: {vt_enabled})")
    }

    details
}

#[cfg(not(windows))]
fn windows_console_details() -> Vec<String> {
    Vec::new()
}

fn terminal_check_from_inputs(inputs: TerminalCheckInputs) -> DoctorCheck {
    let info = &inputs.info;
    let name = info.name;
    let mut details = vec![format!("terminal: {}", terminal_name(info))];
    if let Some(term_program) = info.term_program.as_deref() {
        details.push(format!("TERM_PROGRAM: {term_program}"));
    }
    if let Some(version) = info.version.as_deref() {
        details.push(format!("terminal version: {version}"));
    }
    if let Some(term) = info.term.as_deref() {
        details.push(format!("TERM: {term}"));
    }
    if let Some(multiplexer) = info.multiplexer.as_ref() {
        details.push(format!("multiplexer: {}", multiplexer_name(multiplexer)));
    }
    details.push(format!("stdin is terminal: {}", inputs.stdin_is_terminal));
    details.push(format!("stdout is terminal: {}", inputs.stdout_is_terminal));
    details.push(format!("stderr is terminal: {}", inputs.stderr_is_terminal));
    match &inputs.terminal_size {
        Ok((columns, rows)) => details.push(format!("terminal size: {columns}x{rows}")),
        Err(err) => details.push(format!("terminal size: unavailable ({err})")),
    }
    push_terminal_env_values(&mut details, &inputs, TERMINAL_DIMENSION_ENV_VARS);
    details.push(format!("color output: {}", color_output_summary(&inputs)));
    push_terminal_env_values(&mut details, &inputs, COLOR_ENV_VARS);
    let terminfo_warning = push_terminfo_details(&mut details, &inputs);
    let locale = effective_locale(&inputs);
    if let Some(locale) = locale.as_ref() {
        details.push(format!("effective locale: {locale}"));
    }
    push_presence_env_values(&mut details, &inputs, REMOTE_TERMINAL_ENV_VARS);
    details.extend(inputs.tmux_details.iter().cloned());
    details.extend(inputs.windows_console_details.iter().cloned());

    let locale_warning = locale.as_deref().is_some_and(is_non_utf8_locale);
    let mut issues = Vec::new();
    if matches!(name, TerminalName::Dumb) {
        issues.push(
            DoctorIssue::new(
                CheckStatus::Fail,
                "TERM=dumb - colors and cursor control are disabled",
            )
            .measured("TERM=dumb")
            .expected("TERM=xterm-256color or another real terminal type")
            .remedy("set TERM to a real value, for example xterm-256color")
            .field("TERM"),
        );
    }
    if locale_warning {
        let measured = locale.unwrap_or_else(|| "unknown".to_string());
        issues.push(
            DoctorIssue::new(
                CheckStatus::Warning,
                "locale is not UTF-8 - unicode glyphs may render incorrectly",
            )
            .measured(measured)
            .expected("UTF-8 locale, for example en_US.UTF-8")
            .remedy("export LANG=en_US.UTF-8 or another UTF-8 locale")
            .field("effective locale"),
        );
    }
    if terminfo_warning {
        issues.push(
            DoctorIssue::new(
                CheckStatus::Fail,
                "TERMINFO unreadable - terminal capabilities are unknown",
            )
            .expected("readable terminfo file or directory")
            .remedy("check that $TERMINFO points to a readable directory")
            .field("TERMINFO")
            .field("TERMINFO_DIRS entry"),
        );
    }
    issues.extend(terminal_size_issues(&inputs));

    let status = issues
        .iter()
        .map(|issue| issue.severity)
        .max()
        .unwrap_or(CheckStatus::Ok);
    let summary = issues
        .first()
        .map(|issue| issue.cause.as_str())
        .unwrap_or("terminal metadata was detected");
    let mut check = DoctorCheck::new("terminal.env", "terminal", status, summary).details(details);
    for issue in issues {
        check = check.issue(issue);
    }
    check
}

fn terminal_name(info: &TerminalInfo) -> &'static str {
    match info.name {
        TerminalName::AppleTerminal => "Apple Terminal",
        TerminalName::Ghostty => "Ghostty",
        TerminalName::Iterm2 => "iTerm2",
        TerminalName::WarpTerminal => "Warp",
        TerminalName::VsCode => "VS Code",
        TerminalName::WezTerm => "WezTerm",
        TerminalName::Kitty => "kitty",
        TerminalName::Alacritty => "Alacritty",
        TerminalName::Konsole => "Konsole",
        TerminalName::GnomeTerminal => "GNOME Terminal",
        TerminalName::Vte => "VTE",
        TerminalName::WindowsTerminal => "Windows Terminal",
        TerminalName::Dumb => "dumb",
        TerminalName::Unknown => "unknown",
    }
}

fn multiplexer_name(multiplexer: &Multiplexer) -> String {
    match multiplexer {
        Multiplexer::Tmux { version } => match version {
            Some(version) => format!("tmux {version}"),
            None => "tmux".to_string(),
        },
        Multiplexer::Zellij { version } => match version {
            Some(version) => format!("zellij {version}"),
            None => "zellij".to_string(),
        },
    }
}

fn terminal_env_names() -> BTreeSet<&'static str> {
    let mut names = BTreeSet::from(["TERM", "TERM_PROGRAM", "TERM_PROGRAM_VERSION"]);
    names.extend(COLOR_ENV_VARS.iter().copied());
    names.extend(TERMINAL_DIMENSION_ENV_VARS.iter().copied());
    names.extend(TERMINFO_ENV_VARS.iter().copied());
    names.extend(LOCALE_ENV_VARS.iter().copied());
    names.extend(REMOTE_TERMINAL_ENV_VARS.iter().copied());
    names
}

fn collect_env_snapshot(
    names: &BTreeSet<&'static str>,
) -> (BTreeMap<String, String>, BTreeSet<String>) {
    let mut values = BTreeMap::new();
    let mut present = BTreeSet::new();
    for name in names {
        if let Some(raw) = env::var_os(name) {
            present.insert((*name).to_string());
            let value = raw.to_string_lossy().trim().to_string();
            if !value.is_empty() {
                values.insert((*name).to_string(), value);
            }
        }
    }
    (values, present)
}

fn push_terminal_env_values(
    details: &mut Vec<String>,
    inputs: &TerminalCheckInputs,
    names: &[&str],
) {
    for name in names {
        if let Some(value) = inputs.env_value(name) {
            details.push(format!("{name}: {value}"));
        } else if inputs.env_present(name) {
            details.push(format!("{name}: present"));
        }
    }
}

fn push_presence_env_values(
    details: &mut Vec<String>,
    inputs: &TerminalCheckInputs,
    names: &[&str],
) {
    for name in names {
        if inputs.env_present(name) {
            details.push(format!("{name}: present"));
        }
    }
}

fn color_output_summary(inputs: &TerminalCheckInputs) -> String {
    if should_enable_color(
        inputs.no_color_flag,
        inputs.env_present("NO_COLOR"),
        inputs.env_value("TERM"),
        inputs.stdout_is_terminal,
        inputs.stream_supports_color,
    ) {
        return "enabled".to_string();
    }

    let reason = if inputs.no_color_flag {
        "--no-color"
    } else if inputs.env_present("NO_COLOR") {
        "NO_COLOR"
    } else if inputs.env_value("TERM") == Some("dumb") {
        "TERM=dumb"
    } else if !inputs.stdout_is_terminal {
        "stdout is not a terminal"
    } else if !inputs.stream_supports_color {
        "terminal color support not detected"
    } else {
        "disabled"
    };
    format!("disabled ({reason})")
}

fn push_terminfo_details(details: &mut Vec<String>, inputs: &TerminalCheckInputs) -> bool {
    let mut has_warning = false;
    if let Some(raw) = inputs.env_value("TERMINFO") {
        let path = PathBuf::from(raw);
        let (status, warning) = terminal_path_readiness(&path);
        details.push(format!("TERMINFO: {} ({status})", path.display()));
        has_warning |= warning;
    }
    if let Some(raw) = inputs.env_value("TERMINFO_DIRS") {
        for path in env::split_paths(raw).filter(|path| !path.as_os_str().is_empty()) {
            let (status, warning) = terminal_path_readiness(&path);
            details.push(format!(
                "TERMINFO_DIRS entry: {} ({status})",
                path.display()
            ));
            has_warning |= warning;
        }
    } else if inputs.env_present("TERMINFO_DIRS") {
        details.push("TERMINFO_DIRS: present".to_string());
    }
    has_warning
}

fn terminal_path_readiness(path: &Path) -> (String, bool) {
    match std::fs::metadata(path) {
        Ok(metadata) if metadata.is_dir() => match std::fs::read_dir(path) {
            Ok(_) => ("dir".to_string(), false),
            Err(err) => (format!("dir unreadable: {err}"), true),
        },
        Ok(metadata) if metadata.is_file() => match read_probe_file(path) {
            Ok(_) => ("file".to_string(), false),
            Err(err) => (format!("file unreadable: {err}"), true),
        },
        Ok(_) => ("not a file or directory".to_string(), true),
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => ("missing".to_string(), true),
        Err(err) => (err.to_string(), true),
    }
}

fn effective_locale(inputs: &TerminalCheckInputs) -> Option<String> {
    LOCALE_ENV_VARS
        .iter()
        .find_map(|name| inputs.env_value(name).map(ToString::to_string))
}

fn is_non_utf8_locale(locale: &str) -> bool {
    let locale = locale.to_ascii_lowercase();
    !(locale.contains("utf-8") || locale.contains("utf8"))
}

fn terminal_size_issues(inputs: &TerminalCheckInputs) -> Vec<DoctorIssue> {
    let mut issues = Vec::new();
    if let Ok((columns, rows)) = inputs.terminal_size {
        if columns > 0 && columns < NARROW_TERMINAL_COLUMNS {
            issues.push(
                DoctorIssue::new(
                    CheckStatus::Warning,
                    format!("width {columns} cols - output may wrap (recommended >=80)"),
                )
                .measured(format!("{columns} x {rows}"))
                .expected(format!(">= {NARROW_TERMINAL_COLUMNS} columns"))
                .remedy("resize the window to at least 80 columns")
                .field("terminal size"),
            );
        }
        if rows > 0 && rows < NARROW_TERMINAL_ROWS {
            issues.push(
                DoctorIssue::new(
                    CheckStatus::Warning,
                    format!("height {rows} rows - content may scroll off (recommended >=24)"),
                )
                .measured(format!("{columns} x {rows}"))
                .expected(format!(">= {NARROW_TERMINAL_ROWS} rows"))
                .remedy("resize the window to at least 24 rows")
                .field("terminal size"),
            );
        }
    }

    if let Some(columns) = inputs
        .env_value("COLUMNS")
        .and_then(|columns| columns.parse::<u16>().ok())
        && columns > 0
        && columns < NARROW_TERMINAL_COLUMNS
    {
        issues.push(
            DoctorIssue::new(
                CheckStatus::Warning,
                format!("COLUMNS={columns} - output may wrap (recommended >=80)"),
            )
            .measured(format!("{columns} columns"))
            .expected(format!(">= {NARROW_TERMINAL_COLUMNS} columns"))
            .remedy("resize the window to at least 80 columns")
            .field("COLUMNS"),
        );
    }
    if let Some(rows) = inputs
        .env_value("LINES")
        .and_then(|rows| rows.parse::<u16>().ok())
        && rows > 0
        && rows < NARROW_TERMINAL_ROWS
    {
        issues.push(
            DoctorIssue::new(
                CheckStatus::Warning,
                format!("LINES={rows} - content may scroll off (recommended >=24)"),
            )
            .measured(format!("{rows} rows"))
            .expected(format!(">= {NARROW_TERMINAL_ROWS} rows"))
            .remedy("resize the window to at least 24 rows")
            .field("LINES"),
        );
    }

    issues
}

fn tmux_diagnostic_details() -> Vec<String> {
    let mut details = Vec::new();
    push_tmux_display_detail(&mut details, "tmux client termtype", "#{client_termtype}");
    push_tmux_display_detail(&mut details, "tmux client termname", "#{client_termname}");
    for option in TMUX_OPTION_NAMES {
        let value = tmux_option_value(option).unwrap_or_else(|| "unavailable".to_string());
        details.push(format!("tmux {option}: {value}"));
    }
    details
}

fn push_tmux_display_detail(details: &mut Vec<String>, label: &str, format: &str) {
    if let Some(value) = tmux_display_message(format) {
        details.push(format!("{label}: {value}"));
    }
}

fn tmux_option_value(option: &str) -> Option<String> {
    let output = Command::new("tmux")
        .args(["show-options", "-gqv", option])
        .output()
        .ok()?;
    if !output.status.success() {
        return None;
    }
    non_empty_trimmed(String::from_utf8(output.stdout).ok()?)
}

fn tmux_display_message(format: &str) -> Option<String> {
    let output = Command::new("tmux")
        .args(["display-message", "-p", format])
        .output()
        .ok()?;
    if !output.status.success() {
        return None;
    }
    non_empty_trimmed(String::from_utf8(output.stdout).ok()?)
}

fn non_empty_trimmed(value: String) -> Option<String> {
    let value = value.trim().to_string();
    if value.is_empty() { None } else { Some(value) }
}

async fn state_check(config: &Config) -> DoctorCheck {
    let mut details = Vec::new();
    path_readiness(&mut details, "CODEX_HOME", &config.codex_home);
    path_readiness(&mut details, "log dir", &config.log_dir);
    path_readiness(&mut details, "sqlite home", &config.sqlite_home);
    let mut integrity_failures = Vec::new();
    for db in lemurclaw_core::state::runtime_db_paths(&config.sqlite_home) {
        path_readiness(&mut details, db.label, &db.path);
        sqlite_integrity_detail(&mut details, &mut integrity_failures, db.label, &db.path).await;
    }
    rollout_stats_details(&mut details, &config.codex_home);
    standalone_release_cache_details(&mut details);

    let status = if integrity_failures.is_empty() {
        CheckStatus::Ok
    } else {
        CheckStatus::Fail
    };
    let summary = if status == CheckStatus::Ok {
        "state paths and databases are inspectable"
    } else {
        "state database integrity check failed"
    };
    let mut check = DoctorCheck::new("state.paths", "state", status, summary).details(details);
    if status == CheckStatus::Fail {
        check = check.remediation(
            "Move the damaged SQLite database aside, then restart the interactive CLI or app server so it can rebuild that runtime database from saved data. Other entry points may not rebuild automatically.",
        );
    }
    check
}

async fn sqlite_integrity_detail(
    details: &mut Vec<String>,
    integrity_failures: &mut Vec<String>,
    label: &str,
    path: &Path,
) {
    if !path.is_file() {
        details.push(format!("{label} integrity: skipped (missing)"));
        return;
    }

    match lemurclaw_core::state::sqlite_integrity_check(path).await {
        Ok(rows) if rows.iter().all(|row| row == "ok") => {
            details.push(format!("{label} integrity: ok"));
        }
        Ok(rows) => {
            let message = format!("{label} integrity: {}", rows.join("; "));
            integrity_failures.push(message.clone());
            details.push(message);
        }
        Err(err) => {
            let message = format!("{label} integrity: {err}");
            integrity_failures.push(message.clone());
            details.push(message);
        }
    }
}

fn rollout_stats_details(details: &mut Vec<String>, codex_home: &Path) {
    let active = collect_rollout_stats(&codex_home.join("sessions"));
    let archived = collect_rollout_stats(&codex_home.join("archived_sessions"));
    push_rollout_stats_detail(details, "active rollout files", active);
    push_rollout_stats_detail(details, "archived rollout files", archived);
}

fn push_rollout_stats_detail(details: &mut Vec<String>, label: &str, stats: RolloutStats) {
    match stats.error {
        Some(error) => details.push(format!("{label}: scan failed ({error})")),
        None => details.push(format!(
            "{label}: {} files, {} total bytes, {} average bytes",
            stats.files,
            stats.total_bytes,
            stats.average_bytes()
        )),
    }
}

#[derive(Default)]
struct RolloutStats {
    files: u64,
    total_bytes: u64,
    error: Option<String>,
}

impl RolloutStats {
    fn average_bytes(&self) -> u64 {
        self.total_bytes.checked_div(self.files).unwrap_or(0)
    }
}

fn collect_rollout_stats(root: &Path) -> RolloutStats {
    let mut stats = RolloutStats::default();
    collect_rollout_stats_inner(root, &mut stats);
    stats
}

fn collect_rollout_stats_inner(path: &Path, stats: &mut RolloutStats) {
    if stats.error.is_some() {
        return;
    }
    let entries = match std::fs::read_dir(path) {
        Ok(entries) => entries,
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => return,
        Err(err) => {
            stats.error = Some(err.to_string());
            return;
        }
    };

    for entry in entries {
        let entry = match entry {
            Ok(entry) => entry,
            Err(err) => {
                stats.error = Some(err.to_string());
                return;
            }
        };
        let path = entry.path();
        let metadata = match entry.metadata() {
            Ok(metadata) => metadata,
            Err(err) => {
                stats.error = Some(err.to_string());
                return;
            }
        };
        if metadata.is_dir() {
            collect_rollout_stats_inner(&path, stats);
        } else if metadata.is_file() && is_rollout_file(&path) {
            stats.files += 1;
            stats.total_bytes = stats.total_bytes.saturating_add(metadata.len());
        }
    }
}

fn is_rollout_file(path: &Path) -> bool {
    path.extension() == Some(OsStr::new("jsonl"))
        && path
            .file_name()
            .and_then(OsStr::to_str)
            .is_some_and(|name| name.starts_with("rollout-"))
}

async fn websocket_reachability_check(
    config: &Config,
    auth_manager: Option<Arc<AuthManager>>,
) -> DoctorCheck {
    let provider = &config.model_provider;
    let mut details = vec![
        format!("model provider: {}", config.model_provider_id),
        format!("provider name: {}", provider.name),
        format!("wire API: {}", provider.wire_api),
        format!("supports websockets: {}", provider.supports_websockets),
    ];
    push_proxy_env_details(&mut details);

    if !provider.supports_websockets {
        return DoctorCheck::new(
            "network.websocket_reachability",
            "websocket",
            CheckStatus::Ok,
            "Responses WebSocket is not enabled for the active provider",
        )
        .details(details);
    }

    details.push(format!(
        "connect timeout: {} ms",
        provider.websocket_connect_timeout().as_millis()
    ));

    let runtime_provider = create_model_provider(provider.clone(), auth_manager);
    let auth = runtime_provider.auth().await;
    details.push(format!(
        "auth mode: {}",
        auth.as_ref().map(auth_mode_name).unwrap_or("none")
    ));

    let api_provider = match runtime_provider.api_provider().await {
        Ok(api_provider) => api_provider,
        Err(err) => {
            return websocket_probe_warning(
                "Responses WebSocket provider setup failed",
                details,
                format!("provider setup failed: {err}"),
            );
        }
    };
    match api_provider.websocket_url_for_path("responses") {
        Ok(url) => {
            details.push(format!("endpoint: {url}"));
            if let Some(host) = url.host_str()
                && let Some(port) = url.port_or_known_default()
            {
                details.extend(dns_address_family_details(host, port).await);
            }
        }
        Err(err) => {
            return websocket_probe_warning(
                "Responses WebSocket endpoint could not be built",
                details,
                format!("endpoint build failed: {err}"),
            );
        }
    }

    let api_auth = match runtime_provider.api_auth().await {
        Ok(api_auth) => api_auth,
        Err(err) => {
            return websocket_probe_warning(
                "Responses WebSocket auth could not be resolved",
                details,
                format!("auth resolution failed: {err}"),
            );
        }
    };

    let mut extra_headers = HeaderMap::new();
    extra_headers.insert(
        OPENAI_BETA_HEADER,
        HeaderValue::from_static(RESPONSES_WEBSOCKETS_V2_BETA_HEADER_VALUE),
    );
    let client = ResponsesWebsocketClient::new(api_provider, api_auth);
    let http_client_factory = config.http_client_factory();
    match tokio::time::timeout(
        provider.websocket_connect_timeout(),
        client.probe_handshake(
            &http_client_factory,
            extra_headers,
            default_headers(),
            WEBSOCKET_IMMEDIATE_CLOSE_GRACE,
        ),
    )
    .await
    {
        Ok(Ok(probe)) => {
            details.push(format!("handshake result: HTTP {}", probe.status));
            details.push(format!("reasoning header: {}", probe.reasoning_included));
            details.push(format!(
                "models etag present: {}",
                probe.models_etag_present
            ));
            details.push(format!(
                "server model present: {}",
                probe.server_model_present
            ));
            if let Some(close) = probe.immediate_close {
                details.push(format!("immediate close code: {}", close.code));
                details.push(format!("immediate close reason: {}", close.reason));
                return DoctorCheck::new(
                    "network.websocket_reachability",
                    "websocket",
                    CheckStatus::Warning,
                    "Responses WebSocket closed immediately after handshake",
                )
                .details(details)
                .remediation(
                    "Check proxy, VPN, firewall, DNS, custom CA, and WebSocket policy support.",
                );
            }
            DoctorCheck::new(
                "network.websocket_reachability",
                "websocket",
                CheckStatus::Ok,
                "Responses WebSocket handshake succeeded",
            )
            .details(details)
        }
        Ok(Err(err)) => websocket_probe_warning(
            "Responses WebSocket failed; HTTPS fallback may still work",
            details,
            websocket_error_detail(&err),
        ),
        Err(_) => websocket_probe_warning(
            "Responses WebSocket timed out; HTTPS fallback may still work",
            details,
            "handshake timed out".to_string(),
        ),
    }
}

fn websocket_probe_warning(
    summary: &'static str,
    mut details: Vec<String>,
    error_detail: String,
) -> DoctorCheck {
    details.push(error_detail);
    DoctorCheck::new(
        "network.websocket_reachability",
        "websocket",
        CheckStatus::Warning,
        summary,
    )
    .details(details)
    .remediation("Check proxy, VPN, firewall, DNS, custom CA, and WebSocket policy support.")
}

fn websocket_error_detail(err: &ApiError) -> String {
    match err {
        ApiError::Transport(transport) => format!("handshake transport error: {transport}"),
        ApiError::Api { status, message } => {
            format!("handshake API error: {status} {message}")
        }
        ApiError::Stream(message) => format!("handshake stream error: {message}"),
        ApiError::ContextWindowExceeded
        | ApiError::QuotaExceeded
        | ApiError::UsageNotIncluded
        | ApiError::Retryable { .. }
        | ApiError::RateLimit(_)
        | ApiError::InvalidRequest { .. }
        | ApiError::CyberPolicy { .. }
        | ApiError::ServerOverloaded => format!("handshake error: {err}"),
    }
}

fn auth_mode_name(auth: &CodexAuth) -> &'static str {
    match auth.auth_mode() {
        AuthMode::ApiKey => "api_key",
        AuthMode::Chatgpt => "chatgpt",
        AuthMode::ChatgptAuthTokens => "chatgpt_auth_tokens",
        AuthMode::Headers => "headers",
        AuthMode::AgentIdentity => "agent_identity",
        AuthMode::PersonalAccessToken => "personal_access_token",
        AuthMode::BedrockApiKey => "bedrock_api_key",
    }
}

async fn dns_address_family_details(host: &str, port: u16) -> Vec<String> {
    match tokio::net::lookup_host((host, port)).await {
        Ok(addresses) => {
            let addresses = addresses.collect::<Vec<_>>();
            let ipv4_count = addresses
                .iter()
                .filter(|address| matches!(address.ip(), IpAddr::V4(_)))
                .count();
            let ipv6_count = addresses
                .iter()
                .filter(|address| matches!(address.ip(), IpAddr::V6(_)))
                .count();
            let first_family = addresses
                .first()
                .map(|address| match address.ip() {
                    IpAddr::V4(_) => "IPv4",
                    IpAddr::V6(_) => "IPv6",
                })
                .unwrap_or("none");
            vec![format!(
                "DNS: {ipv4_count} IPv4, {ipv6_count} IPv6, first {first_family}"
            )]
        }
        Err(err) => vec![format!("DNS: lookup failed ({err})")],
    }
}

fn fallback_state_check() -> DoctorCheck {
    let codex_home = find_codex_home();
    match codex_home {
        Ok(path) => DoctorCheck::new(
            "state.paths",
            "state",
            CheckStatus::Ok,
            "CODEX_HOME was resolved without config",
        )
        .detail(format!("CODEX_HOME: {}", path.display())),
        Err(err) => DoctorCheck::new(
            "state.paths",
            "state",
            CheckStatus::Warning,
            "CODEX_HOME could not be resolved",
        )
        .detail(err.to_string()),
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
struct ReachabilityPlan {
    description: String,
    endpoints: Vec<ReachabilityEndpoint>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
struct ReachabilityEndpoint {
    label: String,
    url: String,
    required: bool,
    route_probe_url: Option<String>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ProviderAuthReachabilityMode {
    NotRequired,
    ApiKey,
    Chatgpt,
}

impl ProviderAuthReachabilityMode {
    fn description(self) -> &'static str {
        match self {
            Self::NotRequired => "provider auth",
            Self::ApiKey => "API key auth",
            Self::Chatgpt => "ChatGPT auth",
        }
    }
}

fn provider_reachability_plan(config: &Config) -> ReachabilityPlan {
    let stored_auth = load_auth_dot_json(
        &config.codex_home,
        config.cli_auth_credentials_store_mode,
        config.auth_keyring_backend_kind(),
    )
    .ok()
    .flatten();
    let mode = provider_auth_reachability_mode_from_auth(
        config.model_provider.requires_openai_auth,
        env_var_present,
        stored_auth.as_ref(),
    );
    provider_reachability_plan_from_parts(
        mode,
        &config.model_provider_id,
        &config.model_provider.name,
        config.model_provider.base_url.as_deref(),
        config.model_provider.query_params.as_ref(),
        config.model_provider.is_amazon_bedrock(),
        &config.chatgpt_base_url,
    )
}

fn default_reachability_plan() -> ReachabilityPlan {
    provider_reachability_plan_from_parts(
        ProviderAuthReachabilityMode::Chatgpt,
        "openai",
        "OpenAI",
        /*provider_base_url*/ None,
        /*provider_query_params*/ None,
        /*is_amazon_bedrock*/ false,
        "https://chatgpt.com/backend-api/",
    )
}

fn provider_auth_reachability_mode_from_auth(
    requires_openai_auth: bool,
    env_var_present: impl Fn(&str) -> bool,
    stored_auth: Option<&AuthDotJson>,
) -> ProviderAuthReachabilityMode {
    if !requires_openai_auth {
        return ProviderAuthReachabilityMode::NotRequired;
    }
    if env_var_present(OPENAI_API_KEY_ENV_VAR) || env_var_present(CODEX_API_KEY_ENV_VAR) {
        return ProviderAuthReachabilityMode::ApiKey;
    }
    if env_var_present(CODEX_ACCESS_TOKEN_ENV_VAR) {
        return ProviderAuthReachabilityMode::Chatgpt;
    }
    match stored_auth.map(stored_auth_mode_value) {
        Some(AuthMode::ApiKey | AuthMode::BedrockApiKey) => ProviderAuthReachabilityMode::ApiKey,
        Some(
            AuthMode::Chatgpt
            | AuthMode::ChatgptAuthTokens
            | AuthMode::Headers
            | AuthMode::AgentIdentity
            | AuthMode::PersonalAccessToken,
        )
        | None => ProviderAuthReachabilityMode::Chatgpt,
    }
}

fn provider_reachability_plan_from_parts(
    mode: ProviderAuthReachabilityMode,
    provider_id: &str,
    provider_name: &str,
    provider_base_url: Option<&str>,
    provider_query_params: Option<&HashMap<String, String>>,
    is_amazon_bedrock: bool,
    chatgpt_base_url: &str,
) -> ReachabilityPlan {
    let provider_route_probe_url = provider_base_url
        .or_else(|| {
            (mode == ProviderAuthReachabilityMode::ApiKey).then_some("https://api.openai.com/v1")
        })
        .and_then(|url| {
            should_probe_models_route(provider_name, url, is_amazon_bedrock)
                .then(|| provider_url_for_path(url, "models", provider_query_params))
        });
    let endpoints = match mode {
        ProviderAuthReachabilityMode::ApiKey => vec![ReachabilityEndpoint {
            label: format!("{provider_id} API"),
            url: provider_base_url
                .unwrap_or("https://api.openai.com/v1")
                .to_string(),
            required: true,
            route_probe_url: provider_route_probe_url,
        }],
        ProviderAuthReachabilityMode::Chatgpt => vec![ReachabilityEndpoint {
            label: "ChatGPT".to_string(),
            url: chatgpt_base_url.to_string(),
            required: true,
            route_probe_url: None,
        }],
        ProviderAuthReachabilityMode::NotRequired => provider_base_url
            .map(|url| {
                vec![ReachabilityEndpoint {
                    label: format!("{provider_id} API"),
                    url: url.to_string(),
                    required: true,
                    route_probe_url: provider_route_probe_url,
                }]
            })
            .unwrap_or_default(),
    };
    ReachabilityPlan {
        description: mode.description().to_string(),
        endpoints,
    }
}

fn should_probe_models_route(provider_name: &str, base_url: &str, is_amazon_bedrock: bool) -> bool {
    !is_amazon_bedrock && !is_azure_responses_provider(provider_name, Some(base_url))
}

fn provider_url_for_path(
    base_url: &str,
    path: &str,
    query_params: Option<&HashMap<String, String>>,
) -> String {
    let base = base_url.trim_end_matches('/');
    let path = path.trim_start_matches('/');
    let mut url = if path.is_empty() {
        base.to_string()
    } else {
        format!("{base}/{path}")
    };

    if let Some(params) = query_params
        && !params.is_empty()
    {
        let separator = if url.contains('?') { '&' } else { '?' };
        url.push(separator);
        url.push_str(
            &params
                .iter()
                .map(|(key, value)| format!("{key}={value}"))
                .collect::<Vec<_>>()
                .join("&"),
        );
    }

    url
}

async fn provider_reachability_check(plan: ReachabilityPlan) -> DoctorCheck {
    let mut details = vec![format!("reachability mode: {}", plan.description)];
    if plan.endpoints.is_empty() {
        details.push("active provider endpoint: none configured".to_string());
        return DoctorCheck::new(
            "network.provider_reachability",
            "reachability",
            CheckStatus::Ok,
            "active provider has no HTTP endpoint to probe",
        )
        .details(details);
    }

    let mut failures = Vec::new();
    let mut optional_failures = Vec::new();
    let mut route_failures = Vec::new();
    let mut route_warnings = Vec::new();
    let mut issues = Vec::new();
    for endpoint in plan.endpoints {
        match http_probe_url(&endpoint.url).await {
            Ok(status) => details.push(format!(
                "{} base URL: {} reachable ({status})",
                endpoint.label, endpoint.url
            )),
            Err(err) => {
                let requirement = if endpoint.required {
                    "required"
                } else {
                    "optional"
                };
                details.push(format!(
                    "{} base URL: {} {err} ({requirement})",
                    endpoint.label, endpoint.url
                ));
                if endpoint.required {
                    failures.push(endpoint.url);
                } else {
                    optional_failures.push(endpoint.url);
                }
                continue;
            }
        }

        let Some(route_probe_url) = endpoint.route_probe_url.as_deref() else {
            continue;
        };
        match provider_route_probe_url(route_probe_url).await {
            RouteProbeOutcome::Ok(status) => {
                details.push(format!(
                    "{} route probe: {route_probe_url} route exists ({status})",
                    endpoint.label,
                ));
            }
            RouteProbeOutcome::Warning(status) => {
                details.push(format!(
                    "{} route probe: {route_probe_url} returned {status} (warning)",
                    endpoint.label,
                ));
                route_warnings.push(route_probe_url.to_string());
            }
            RouteProbeOutcome::Fail(status) => {
                details.push(format!(
                    "{} route probe: {route_probe_url} returned {status} (required)",
                    endpoint.label,
                ));
                route_failures.push(route_probe_url.to_string());
                issues.push(
                    DoctorIssue::new(
                        CheckStatus::Fail,
                        "provider base URL route returned 404 - verify the configured API prefix",
                    )
                    .measured(format!("{route_probe_url} returned {status}"))
                    .expected("GET /models returns 2xx, 401, or 403")
                    .remedy("Set base_url to the provider API root, for example https://api.openai.com/v1")
                    .field("route probe"),
                );
            }
            RouteProbeOutcome::TransportError(err) => {
                details.push(format!(
                    "{} route probe: {route_probe_url} {err} (required)",
                    endpoint.label,
                ));
                route_failures.push(route_probe_url.to_string());
                issues.push(
                    DoctorIssue::new(
                        CheckStatus::Fail,
                        "provider route probe could not connect - verify network access to the provider API",
                    )
                    .measured(format!("{route_probe_url} {err}"))
                    .expected("GET /models completes")
                    .remedy("Check proxy, VPN, firewall, DNS, and custom CA configuration.")
                    .field("route probe"),
                );
            }
        }
    }

    let (status, summary) = provider_reachability_outcome(
        failures.len() + route_failures.len(),
        optional_failures.len() + route_warnings.len(),
    );
    let mut check = DoctorCheck::new(
        "network.provider_reachability",
        "reachability",
        status,
        summary,
    )
    .details(details);
    for issue in issues {
        check = check.issue(issue);
    }
    if status != CheckStatus::Ok {
        check = check.remediation("Check proxy, VPN, firewall, DNS, and custom CA configuration.");
    }
    check
}

enum RouteProbeOutcome {
    Ok(String),
    Warning(String),
    Fail(String),
    TransportError(String),
}

async fn provider_route_probe_url(url: &str) -> RouteProbeOutcome {
    match http_get_probe_status_with_timeout(url, Duration::from_secs(3)).await {
        Ok(status) if (200..300).contains(&status) || matches!(status, 401 | 403) => {
            RouteProbeOutcome::Ok(format!("HTTP {status}"))
        }
        Ok(404) => RouteProbeOutcome::Fail("HTTP 404".to_string()),
        Ok(status) => RouteProbeOutcome::Warning(format!("HTTP {status}")),
        Err(err) => RouteProbeOutcome::TransportError(err),
    }
}

fn provider_reachability_outcome(
    required_failures: usize,
    warnings: usize,
) -> (CheckStatus, &'static str) {
    match (required_failures, warnings) {
        (0, 0) => (
            CheckStatus::Ok,
            "active provider endpoints are reachable over HTTP",
        ),
        (0, _) => (
            CheckStatus::Warning,
            "provider endpoint checks returned warnings",
        ),
        (_, _) => (
            CheckStatus::Fail,
            "one or more required provider endpoints are unreachable over HTTP",
        ),
    }
}

async fn http_probe_url(url: &str) -> Result<String, String> {
    http_probe_url_with_timeout(url, Duration::from_secs(3)).await
}

async fn mcp_http_probe_url(url: &str) -> Result<String, String> {
    mcp_http_probe_url_with_timeout(url, Duration::from_secs(3)).await
}

async fn mcp_http_probe_url_with_timeout(url: &str, timeout: Duration) -> Result<String, String> {
    match http_probe_url_with_timeout(url, timeout).await {
        Ok(status) => Ok(status),
        Err(head_err) => match http_get_probe_url_with_timeout(url, timeout).await {
            Ok(status) => Ok(status),
            Err(get_err) => Err(format!("HEAD {head_err}; GET {get_err}")),
        },
    }
}

async fn http_probe_url_with_timeout(url: &str, timeout: Duration) -> Result<String, String> {
    let response = build_reqwest_client()
        .head(url)
        .timeout(timeout)
        .send()
        .await
        .map_err(|err| {
            if err.is_timeout() {
                "request timed out".to_string()
            } else if err.is_connect() {
                "connect failed".to_string()
            } else if err.is_builder() {
                "request could not be built".to_string()
            } else {
                err.to_string()
            }
        })?;
    Ok(format!("HTTP {}", response.status().as_u16()))
}

async fn http_get_probe_url_with_timeout(url: &str, timeout: Duration) -> Result<String, String> {
    http_get_probe_status_with_timeout(url, timeout)
        .await
        .map(|status| format!("HTTP {status}"))
}

async fn http_get_probe_status_with_timeout(url: &str, timeout: Duration) -> Result<u16, String> {
    let response = build_reqwest_client()
        .get(url)
        .timeout(timeout)
        .send()
        .await
        .map_err(|err| {
            if err.is_timeout() {
                "request timed out".to_string()
            } else if err.is_connect() {
                "connect failed".to_string()
            } else if err.is_builder() {
                "request could not be built".to_string()
            } else {
                err.to_string()
            }
        })?;
    Ok(response.status().as_u16())
}

fn stdio_command_resolves(
    command: &str,
    cwd: Option<&Path>,
    server_env: Option<&HashMap<String, String>>,
) -> Result<(), String> {
    let command_path = Path::new(command);
    if command_path.is_absolute() {
        return executable_path_exists(command_path);
    }

    if command_path.components().count() > 1 {
        let base = cwd
            .map(Path::to_path_buf)
            .or_else(|| env::current_dir().ok())
            .unwrap_or_else(|| PathBuf::from("."));
        return executable_path_exists(&base.join(command_path));
    }

    let Some(path_env) = server_env
        .and_then(|env| env.get("PATH").map(String::as_str))
        .map(std::ffi::OsString::from)
        .or_else(|| env::var_os("PATH"))
    else {
        return Err("PATH is not set".to_string());
    };

    for dir in env::split_paths(&path_env) {
        let candidate = dir.join(command);
        if executable_path_exists(&candidate).is_ok() {
            return Ok(());
        }
        #[cfg(windows)]
        {
            let pathext = env::var("PATHEXT").unwrap_or_else(|_| ".COM;.EXE;.BAT;.CMD".to_string());
            for extension in pathext.split(';').filter(|extension| !extension.is_empty()) {
                let candidate = dir.join(format!("{command}{extension}"));
                if executable_path_exists(&candidate).is_ok() {
                    return Ok(());
                }
            }
        }
    }
    Err("not found on PATH".to_string())
}

fn executable_path_exists(path: &Path) -> Result<(), String> {
    match std::fs::metadata(path) {
        Ok(metadata) if metadata.is_file() => executable_file_permission(path, &metadata),
        Ok(_) => Err("path is not a file".to_string()),
        Err(err) => Err(err.to_string()),
    }
}

#[cfg(unix)]
fn executable_file_permission(path: &Path, metadata: &std::fs::Metadata) -> Result<(), String> {
    use std::os::unix::fs::PermissionsExt;

    if metadata.permissions().mode() & 0o111 == 0 {
        Err(format!("{} is not executable", path.display()))
    } else {
        Ok(())
    }
}

#[cfg(not(unix))]
fn executable_file_permission(_path: &Path, _metadata: &std::fs::Metadata) -> Result<(), String> {
    Ok(())
}

fn path_readiness(details: &mut Vec<String>, label: &str, path: &Path) {
    match std::fs::metadata(path) {
        Ok(metadata) => {
            let kind = if metadata.is_dir() {
                "dir"
            } else if metadata.is_file() {
                "file"
            } else {
                "other"
            };
            details.push(format!("{label}: {} ({kind})", path.display()));
        }
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
            details.push(format!("{label}: {} (missing)", path.display()));
        }
        Err(err) => details.push(format!("{label}: {} ({err})", path.display())),
    }
}

fn standalone_release_cache_details(details: &mut Vec<String>) {
    let context = InstallContext::current();
    let InstallMethod::Standalone { release_dir, .. } = &context.method else {
        return;
    };
    let Some(releases_dir) = release_dir.parent() else {
        return;
    };
    let Ok(entries) = std::fs::read_dir(&releases_dir) else {
        return;
    };
    let release_count = entries.filter_map(Result::ok).count();
    details.push(format!(
        "standalone release cache: {release_count} entries in {}",
        releases_dir.display()
    ));
}

fn push_path_detail(details: &mut Vec<String>, label: &str, path: Option<&Path>) {
    match path {
        Some(path) => details.push(format!("{label}: {}", path.display())),
        None => details.push(format!("{label}: none")),
    }
}

fn push_env_path_detail(details: &mut Vec<String>, label: &str, name: &str) {
    match env::var_os(name) {
        Some(path) => details.push(format!("{label}: {}", PathBuf::from(path).display())),
        None => details.push(format!("{label}: not set")),
    }
}

fn env_var_present(name: &str) -> bool {
    env::var_os(name).is_some_and(|value| !value.is_empty())
}

fn human_output_options(command: &DoctorCommand) -> HumanOutputOptions {
    let term = env::var("TERM").ok();
    let color_enabled = should_enable_color(
        command.no_color,
        env::var_os("NO_COLOR").is_some(),
        term.as_deref(),
        std::io::stdout().is_terminal(),
        supports_color::on(Stream::Stdout).is_some(),
    );
    HumanOutputOptions {
        show_details: !command.summary,
        show_all: command.all,
        ascii: command.ascii,
        color_enabled,
    }
}

fn should_enable_color(
    no_color_flag: bool,
    no_color_env: bool,
    term: Option<&str>,
    stdout_is_tty: bool,
    stream_supports_color: bool,
) -> bool {
    !no_color_flag
        && !no_color_env
        && term != Some("dumb")
        && stdout_is_tty
        && stream_supports_color
}

#[cfg(test)]
mod tests {
    use std::io::Read;
    use std::io::Write;
    use std::net::TcpListener;
    use std::sync::Mutex;

    use clap::Parser;
    use lemurclaw_core::protocol::config_types::SandboxMode;
    use pretty_assertions::assert_eq;

    use super::*;

    #[derive(Default)]
    struct RecordingProgress {
        events: Mutex<Vec<String>>,
    }

    impl RecordingProgress {
        fn events(&self) -> Vec<String> {
            self.events.lock().expect("events lock").clone()
        }
    }

    impl DoctorProgress for RecordingProgress {
        fn begin(&self, label: &'static str) {
            self.events
                .lock()
                .expect("events lock")
                .push(format!("begin {label}"));
        }

        fn heartbeat(&self, label: &'static str, elapsed: Duration) {
            self.events
                .lock()
                .expect("events lock")
                .push(format!("heartbeat {label} {}", elapsed.as_secs()));
        }

        fn finish(&self, label: &'static str, status: CheckStatus) {
            self.events
                .lock()
                .expect("events lock")
                .push(format!("finish {label} {status:?}"));
        }

        fn settle(&self) {
            self.events
                .lock()
                .expect("events lock")
                .push("settle".to_string());
        }
    }

    fn respond_once(listener: &TcpListener, response: &[u8]) {
        let (mut stream, _) = listener.accept().expect("accept probe request");
        let mut request = [0; 1024];
        let _ = stream.read(&mut request);
        stream.write_all(response).expect("write response");
    }

    #[test]
    fn overall_status_prefers_fail() {
        let checks = vec![
            DoctorCheck::new("a", "config", CheckStatus::Warning, "warning"),
            DoctorCheck::new("b", "auth", CheckStatus::Fail, "fail"),
        ];
        assert_eq!(overall_status(&checks), CheckStatus::Fail);
    }

    #[test]
    fn run_sync_check_notifies_progress() {
        let progress_impl = Arc::new(RecordingProgress::default());
        let progress: Arc<dyn DoctorProgress> = progress_impl.clone();

        let check = run_sync_check("test", progress, || {
            DoctorCheck::new("test", "test", CheckStatus::Ok, "ok")
        });

        assert_eq!(check.status, CheckStatus::Ok);
        assert_eq!(
            progress_impl.events(),
            vec!["begin test".to_string(), "finish test Ok".to_string()]
        );
    }

    #[tokio::test]
    async fn run_async_check_notifies_progress() {
        let progress_impl = Arc::new(RecordingProgress::default());
        let progress: Arc<dyn DoctorProgress> = progress_impl.clone();

        let check = run_async_check("test", progress, async {
            DoctorCheck::new("test", "test", CheckStatus::Warning, "warning")
        })
        .await;

        assert_eq!(check.status, CheckStatus::Warning);
        assert_eq!(
            progress_impl.events(),
            vec!["begin test".to_string(), "finish test Warning".to_string()]
        );
    }

    #[test]
    fn compare_npm_package_roots_detects_match() {
        let running = PathBuf::from("/prefix/lib/node_modules/@openai/codex");
        let npm_root = PathBuf::from("/prefix/lib/node_modules");
        assert_eq!(
            compare_npm_package_roots(&running, &npm_root),
            NpmRootCheck::Match {
                package_root: npm_root.join("@openai").join("codex")
            }
        );
    }

    #[test]
    fn compare_npm_package_roots_detects_mismatch() {
        let running = PathBuf::from("/old/lib/node_modules/@openai/codex");
        let npm_root = PathBuf::from("/new/lib/node_modules");
        assert_eq!(
            compare_npm_package_roots(&running, &npm_root),
            NpmRootCheck::Mismatch {
                running_package_root: running,
                npm_package_root: npm_root.join("@openai").join("codex"),
            }
        );
    }

    #[test]
    fn startup_warning_counts_group_known_sources() {
        let warnings = vec![
            "Skipped loading 2 skill(s) due to invalid SKILL.md files.".to_string(),
            "[features].codex_hooks is deprecated. Use [features].hooks instead.".to_string(),
            "plugin example failed to load".to_string(),
            "MCP server example failed to start".to_string(),
        ];
        let mut details = Vec::new();

        push_startup_warning_counts(&mut details, &warnings);

        assert_eq!(
            details,
            vec![
                "startup warnings: 4",
                "startup warning skills: 1",
                "startup warning hooks: 1",
                "startup warning plugins: 1",
                "startup warning MCP: 1",
                "startup warning deprecated: 1",
            ]
        );
    }

    #[test]
    fn config_overrides_from_interactive_preserves_global_options() {
        let interactive = TuiCli::parse_from([
            "codex",
            "--oss",
            "--local-provider",
            "ollama",
            "--model",
            "llama3.2",
            "--cd",
            "/tmp",
            "--sandbox",
            "danger-full-access",
            "--ask-for-approval",
            "never",
            "--add-dir",
            "/var/tmp",
        ]);
        let arg0_paths = Arg0DispatchPaths {
            codex_self_exe: Some(PathBuf::from("/bin/codex")),
            codex_linux_sandbox_exe: Some(PathBuf::from("/bin/codex-linux-sandbox")),
            main_execve_wrapper_exe: Some(PathBuf::from("/bin/codex-execve-wrapper")),
        };

        let overrides = config_overrides_from_interactive(&interactive, &arg0_paths);

        assert_eq!(overrides.model.as_deref(), Some("llama3.2"));
        assert_eq!(overrides.model_provider.as_deref(), Some("ollama"));
        assert_eq!(overrides.cwd.as_deref(), Some(Path::new("/tmp")));
        assert_eq!(overrides.approval_policy, Some(AskForApproval::Never));
        assert_eq!(overrides.sandbox_mode, Some(SandboxMode::DangerFullAccess));
        assert_eq!(overrides.show_raw_agent_reasoning, Some(true));
        assert_eq!(
            overrides.additional_writable_roots,
            vec![PathBuf::from("/var/tmp")]
        );
        assert_eq!(overrides.codex_self_exe, arg0_paths.codex_self_exe);
        assert_eq!(
            overrides.codex_linux_sandbox_exe,
            arg0_paths.codex_linux_sandbox_exe
        );
        assert_eq!(
            overrides.main_execve_wrapper_exe,
            arg0_paths.main_execve_wrapper_exe
        );
    }

    #[test]
    fn redacted_json_report_structures_and_sanitizes_details() {
        let report = DoctorReport {
            schema_version: 1,
            generated_at: "0s since unix epoch".to_string(),
            overall_status: CheckStatus::Warning,
            codex_version: "0.0.0".to_string(),
            checks: vec![
                DoctorCheck::new(
                    "system.environment",
                    "system",
                    CheckStatus::Ok,
                    "OS language en-US",
                )
                .detail("VISUAL: code --wait")
                .detail("EDITOR: env AWS_ACCESS_KEY_ID=AKIAEXAMPLE vim")
                .detail("PAGER: env PRIVATE_PAGER_VALUE=pager-secret less")
                .detail("GIT_PAGER: delta")
                .detail("GH_PAGER: less")
                .detail("LESS: -FRX"),
                DoctorCheck::new(
                    "mcp.config",
                    "mcp",
                    CheckStatus::Warning,
                    "MCP configuration has optional issues",
                )
                .detail(
                    "optional reachability failed: remote: https://user:pass@example.com/mcp?x=abc (connect failed)",
                )
                .detail("OPENAI_API_KEY: sk-live-secret")
                .detail("duplicate: one")
                .detail("duplicate: two")
                .detail("freeform note")
                .issue(
                    DoctorIssue::new(
                        CheckStatus::Warning,
                        "remote https://user:pass@example.com/mcp?x=abc is unreachable",
                    )
                    .measured("https://user:pass@example.com/mcp?x=abc")
                    .expected("reachable MCP endpoint")
                    .remedy("Check https://user:pass@example.com/help?x=abc.")
                    .field("optional reachability failed"),
                )
                .remediation("Open https://user:pass@example.com/help?x=abc."),
            ],
        };

        let redacted_report = redacted_json_report(&report);
        let redacted = serde_json::to_string(&redacted_report).expect("serialize report");
        let json = serde_json::to_value(redacted_report).expect("report should serialize");

        assert!(!redacted.contains("user:pass"));
        assert!(!redacted.contains("x=abc"));
        assert!(!redacted.contains("sk-live-secret"));
        assert!(!redacted.contains("AKIAEXAMPLE"));
        assert!(!redacted.contains("pager-secret"));
        assert!(!redacted.contains("code --wait"));
        assert!(redacted.contains("https://example.com/mcp"));
        assert_eq!(json["checks"].is_object(), true);
        assert_eq!(
            json["checks"]["system.environment"]["details"]["VISUAL"],
            "set"
        );
        assert_eq!(
            json["checks"]["system.environment"]["details"]["EDITOR"],
            "set"
        );
        assert_eq!(
            json["checks"]["system.environment"]["details"]["PAGER"],
            "set"
        );
        assert_eq!(
            json["checks"]["system.environment"]["details"]["GIT_PAGER"],
            "set"
        );
        assert_eq!(
            json["checks"]["system.environment"]["details"]["GH_PAGER"],
            "set"
        );
        assert_eq!(
            json["checks"]["system.environment"]["details"]["LESS"],
            "set"
        );
        assert_eq!(json["checks"]["mcp.config"]["id"], "mcp.config");
        assert_eq!(
            json["checks"]["mcp.config"]["details"]["OPENAI_API_KEY"],
            "<redacted>"
        );
        assert_eq!(
            json["checks"]["mcp.config"]["details"]["duplicate"],
            serde_json::json!(["one", "two"])
        );
        assert_eq!(
            json["checks"]["mcp.config"]["notes"],
            serde_json::json!(["freeform note"])
        );
        assert_eq!(
            json["checks"]["mcp.config"]["issues"][0]["measured"],
            "https://example.com/mcp"
        );
        assert_eq!(
            json["checks"]["mcp.config"]["issues"][0]["remedy"],
            "Check https://example.com/help."
        );
    }

    #[tokio::test]
    async fn mcp_check_ignores_disabled_servers() {
        let disabled_server: McpServerConfig = toml::from_str(
            r#"
                url = "http://127.0.0.1:9/mcp"
                enabled = false
                required = true
                bearer_token_env_var = "CODEX_DOCTOR_DISABLED_MCP_TOKEN"
            "#,
        )
        .expect("should deserialize disabled MCP config");
        let servers = HashMap::from([("disabled".to_string(), disabled_server)]);

        let check = mcp_check_from_servers(&servers).await;

        assert_eq!(check.status, CheckStatus::Ok);
        assert_eq!(check.summary, "MCP configuration is locally consistent");
        assert!(check.details.contains(&"disabled servers: 1".to_string()));
        assert!(
            check
                .details
                .iter()
                .all(|detail| !detail.contains("CODEX_DOCTOR_DISABLED_MCP_TOKEN"))
        );
        assert!(
            check
                .details
                .iter()
                .all(|detail| !detail.contains("reachability failed"))
        );
    }

    #[tokio::test]
    async fn mcp_check_warns_for_optional_http_reachability() {
        let optional_server: McpServerConfig = toml::from_str(
            r#"
                url = "http://127.0.0.1:9/mcp"
            "#,
        )
        .expect("should deserialize optional MCP config");
        let servers = HashMap::from([("optional".to_string(), optional_server)]);

        let check = mcp_check_from_servers(&servers).await;

        assert_eq!(check.status, CheckStatus::Warning);
        assert_eq!(check.summary, "MCP configuration has optional issues");
        assert!(
            check
                .details
                .iter()
                .any(|detail| detail.contains("optional reachability failed: optional:"))
        );
    }

    #[tokio::test]
    async fn mcp_check_fails_required_remote_stdio_env_var() {
        let command = toml::Value::String(
            std::env::current_exe()
                .expect("current exe")
                .to_string_lossy()
                .into_owned(),
        );
        let required_server: McpServerConfig = toml::from_str(&format!(
            r#"
                command = {command}
                required = true
                env_vars = [{{ name = "REMOTE_ONLY_TOKEN", source = "remote" }}]
            "#,
        ))
        .expect("should deserialize required MCP config");
        let servers = HashMap::from([("required".to_string(), required_server)]);

        let check = mcp_check_from_servers(&servers).await;

        assert_eq!(check.status, CheckStatus::Fail);
        assert!(check.details.iter().any(|detail| {
            detail.contains(
                "required: env_vars entry `REMOTE_ONLY_TOKEN` uses source `remote`, which requires remote MCP stdio",
            )
        }));
    }

    #[tokio::test]
    async fn mcp_check_does_not_probe_environment_stdio_on_the_host() {
        let remote_server: McpServerConfig = toml::from_str(
            r#"
                command = "remote-only-command"
                environment_id = "remote"
                cwd = "C:\\plugins\\demo"
                required = true
                env_vars = [{ name = "REMOTE_ONLY_TOKEN", source = "remote" }]
            "#,
        )
        .expect("remote MCP config");
        let servers = HashMap::from([("remote".to_string(), remote_server)]);

        let check = mcp_check_from_servers(&servers).await;

        assert_eq!(check.status, CheckStatus::Ok);
        assert_eq!(check.summary, "MCP configuration is locally consistent");
    }

    #[test]
    fn provider_specific_auth_allows_non_openai_provider_without_env_key() {
        let check = provider_specific_auth_check(
            /*requires_openai_auth*/ false,
            /*provider_env_key*/ None,
            /*provider_env_key_instructions*/ None,
            Vec::new(),
            |_| false,
        )
        .expect("non-OpenAI provider should produce a provider-specific check");

        assert_eq!(check.status, CheckStatus::Ok);
        assert_eq!(
            check.summary,
            "OpenAI auth is not required for the active model provider"
        );
    }

    #[test]
    fn provider_specific_auth_fails_when_provider_env_key_is_missing() {
        let check = provider_specific_auth_check(
            /*requires_openai_auth*/ false,
            Some("PROVIDER_API_KEY"),
            Some("Set PROVIDER_API_KEY before running Codex."),
            Vec::new(),
            |_| false,
        )
        .expect("non-OpenAI provider should produce a provider-specific check");

        assert_eq!(check.status, CheckStatus::Fail);
        assert_eq!(
            check.summary,
            "active model provider auth env var is missing"
        );
        assert_eq!(
            check.remediation,
            Some("Set PROVIDER_API_KEY before running Codex.".to_string())
        );
    }

    #[test]
    fn stored_auth_validation_rejects_missing_api_key() {
        let auth = AuthDotJson {
            auth_mode: Some(AuthMode::ApiKey),
            openai_api_key: None,
            tokens: None,
            last_refresh: None,
            agent_identity: None,
            personal_access_token: None,
            bedrock_api_key: None,
        };

        assert_eq!(
            stored_auth_issues(&auth, |_| false),
            vec!["API key auth is missing an API key"]
        );
        assert!(stored_auth_issues(&auth, |name| name == OPENAI_API_KEY_ENV_VAR).is_empty());
    }

    #[test]
    fn stored_auth_validation_rejects_missing_chatgpt_tokens() {
        let auth = AuthDotJson {
            auth_mode: None,
            openai_api_key: None,
            tokens: None,
            last_refresh: None,
            agent_identity: None,
            personal_access_token: None,
            bedrock_api_key: None,
        };

        assert_eq!(
            stored_auth_issues(&auth, |_| false),
            vec![
                "ChatGPT auth is missing token data",
                "ChatGPT auth is missing refresh metadata",
            ]
        );
    }

    #[test]
    fn stored_auth_validation_handles_personal_access_token() {
        let mut auth = AuthDotJson {
            auth_mode: None,
            openai_api_key: None,
            tokens: None,
            last_refresh: None,
            agent_identity: None,
            personal_access_token: Some("at-test".to_string()),
            bedrock_api_key: None,
        };

        assert_eq!(stored_auth_mode(&auth), "personal_access_token");
        assert!(stored_auth_issues(&auth, |_| false).is_empty());

        auth.auth_mode = Some(AuthMode::PersonalAccessToken);
        auth.personal_access_token = None;
        assert_eq!(
            stored_auth_issues(&auth, |_| false),
            vec!["personal access token auth is missing a personal access token"]
        );
    }

    #[test]
    fn provider_reachability_mode_uses_api_key_auth() {
        let api_key_auth = AuthDotJson {
            auth_mode: Some(AuthMode::ApiKey),
            openai_api_key: Some("sk-test".to_string()),
            tokens: None,
            last_refresh: None,
            agent_identity: None,
            personal_access_token: None,
            bedrock_api_key: None,
        };

        assert_eq!(
            provider_auth_reachability_mode_from_auth(
                /*requires_openai_auth*/ true,
                |_| false,
                Some(&api_key_auth),
            ),
            ProviderAuthReachabilityMode::ApiKey
        );
        assert_eq!(
            provider_auth_reachability_mode_from_auth(
                /*requires_openai_auth*/ true,
                |name| name == OPENAI_API_KEY_ENV_VAR,
                /*stored_auth*/ None,
            ),
            ProviderAuthReachabilityMode::ApiKey
        );
    }

    #[test]
    fn provider_reachability_uses_active_provider_endpoint() {
        assert_eq!(
            provider_reachability_plan_from_parts(
                ProviderAuthReachabilityMode::NotRequired,
                "azure",
                "azure",
                Some("https://example.openai.azure.com/openai/v1"),
                /*provider_query_params*/ None,
                /*is_amazon_bedrock*/ false,
                "https://chatgpt.com/backend-api/",
            ),
            ReachabilityPlan {
                description: "provider auth".to_string(),
                endpoints: vec![ReachabilityEndpoint {
                    label: "azure API".to_string(),
                    url: "https://example.openai.azure.com/openai/v1".to_string(),
                    required: true,
                    route_probe_url: None,
                }],
            }
        );
    }

    #[test]
    fn provider_reachability_adds_models_route_probe_for_openai_compatible_base_urls() {
        let query_params = HashMap::from([("api-version".to_string(), "2026-01-01".to_string())]);

        assert_eq!(
            provider_reachability_plan_from_parts(
                ProviderAuthReachabilityMode::NotRequired,
                "custom",
                "Custom",
                Some("https://example.com/openai/v1/"),
                Some(&query_params),
                /*is_amazon_bedrock*/ false,
                "https://chatgpt.com/backend-api/",
            ),
            ReachabilityPlan {
                description: "provider auth".to_string(),
                endpoints: vec![ReachabilityEndpoint {
                    label: "custom API".to_string(),
                    url: "https://example.com/openai/v1/".to_string(),
                    required: true,
                    route_probe_url: Some(
                        "https://example.com/openai/v1/models?api-version=2026-01-01".to_string()
                    ),
                }],
            }
        );
    }

    #[test]
    fn provider_reachability_skips_route_probe_for_bedrock() {
        let plan = provider_reachability_plan_from_parts(
            ProviderAuthReachabilityMode::NotRequired,
            "amazon-bedrock",
            "Amazon Bedrock",
            Some("https://bedrock-runtime.us-east-1.amazonaws.com/openai/v1"),
            /*provider_query_params*/ None,
            /*is_amazon_bedrock*/ true,
            "https://chatgpt.com/backend-api/",
        );

        assert_eq!(plan.endpoints[0].route_probe_url, None);
    }

    #[test]
    fn provider_reachability_api_key_does_not_require_chatgpt() {
        let plan = provider_reachability_plan_from_parts(
            ProviderAuthReachabilityMode::ApiKey,
            "openai",
            "OpenAI",
            /*provider_base_url*/ None,
            /*provider_query_params*/ None,
            /*is_amazon_bedrock*/ false,
            "https://chatgpt.com/backend-api/",
        );

        assert_eq!(
            plan.endpoints,
            vec![ReachabilityEndpoint {
                label: "openai API".to_string(),
                url: "https://api.openai.com/v1".to_string(),
                required: true,
                route_probe_url: Some("https://api.openai.com/v1/models".to_string()),
            }]
        );
    }

    #[test]
    fn provider_reachability_outcome_reports_required_failures() {
        assert_eq!(
            provider_reachability_outcome(/*required_failures*/ 0, /*warnings*/ 1,),
            (
                CheckStatus::Warning,
                "provider endpoint checks returned warnings",
            )
        );
        assert_eq!(
            provider_reachability_outcome(/*required_failures*/ 1, /*warnings*/ 0,),
            (
                CheckStatus::Fail,
                "one or more required provider endpoints are unreachable over HTTP",
            )
        );
    }

    #[tokio::test]
    async fn provider_reachability_route_404_fails_bad_base_url_path() {
        let listener = TcpListener::bind("127.0.0.1:0").expect("bind test listener");
        let addr = listener.local_addr().expect("listener address");
        let server = std::thread::spawn(move || {
            respond_once(
                &listener,
                b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
            );
            respond_once(
                &listener,
                b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
            );
        });
        let plan = provider_reachability_plan_from_parts(
            ProviderAuthReachabilityMode::ApiKey,
            "openai",
            "OpenAI",
            Some(&format!("http://{addr}/xxxx")),
            /*provider_query_params*/ None,
            /*is_amazon_bedrock*/ false,
            "https://chatgpt.com/backend-api/",
        );

        let check = provider_reachability_check(plan).await;
        server.join().expect("probe server thread should finish");

        assert_eq!(check.status, CheckStatus::Fail);
        assert!(
            check
                .details
                .iter()
                .any(|detail| detail.contains("route probe:") && detail.contains("HTTP 404"))
        );
        assert_eq!(check.issues.len(), 1);
        assert_eq!(
            check.issues[0].remedy.as_deref(),
            Some("Set base_url to the provider API root, for example https://api.openai.com/v1")
        );
    }

    #[tokio::test]
    async fn provider_reachability_route_401_keeps_reachability_ok() {
        let listener = TcpListener::bind("127.0.0.1:0").expect("bind test listener");
        let addr = listener.local_addr().expect("listener address");
        let server = std::thread::spawn(move || {
            respond_once(
                &listener,
                b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
            );
            respond_once(
                &listener,
                b"HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
            );
        });
        let plan = provider_reachability_plan_from_parts(
            ProviderAuthReachabilityMode::ApiKey,
            "openai",
            "OpenAI",
            Some(&format!("http://{addr}/v1")),
            /*provider_query_params*/ None,
            /*is_amazon_bedrock*/ false,
            "https://chatgpt.com/backend-api/",
        );

        let check = provider_reachability_check(plan).await;
        server.join().expect("probe server thread should finish");

        assert_eq!(check.status, CheckStatus::Ok);
        assert!(
            check
                .details
                .iter()
                .any(|detail| detail.contains("route exists (HTTP 401)"))
        );
    }

    #[test]
    fn collect_rollout_stats_counts_nested_rollout_files() {
        let temp = tempfile::tempdir().expect("create temp dir");
        let nested = temp
            .path()
            .join("sessions")
            .join("2026")
            .join("05")
            .join("13");
        std::fs::create_dir_all(&nested).expect("create nested rollout dir");
        std::fs::write(
            nested.join("rollout-2026-05-13T00-00-00-test.jsonl"),
            "12345",
        )
        .expect("write rollout file");
        std::fs::write(nested.join("not-a-rollout.jsonl"), "ignored").expect("write ignored jsonl");

        let stats = collect_rollout_stats(&temp.path().join("sessions"));

        assert_eq!(stats.files, 1);
        assert_eq!(stats.total_bytes, 5);
        assert_eq!(stats.average_bytes(), 5);
        assert_eq!(stats.error, None);
    }

    #[tokio::test]
    async fn http_probe_treats_http_status_as_reachable() {
        let listener = TcpListener::bind("127.0.0.1:0").expect("bind test listener");
        let addr = listener.local_addr().expect("listener address");
        let server = std::thread::spawn(move || {
            let (mut stream, _) = listener.accept().expect("accept probe request");
            let mut request = [0; 1024];
            let _ = stream.read(&mut request);
            stream
                .write_all(
                    b"HTTP/1.1 405 Method Not Allowed\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
                )
                .expect("write response");
        });

        let status = http_probe_url(&format!("http://{addr}/mcp")).await;
        server.join().expect("probe server thread should finish");

        assert_eq!(status, Ok("HTTP 405".to_string()));
    }

    #[tokio::test]
    async fn mcp_http_probe_falls_back_to_get_when_head_times_out() {
        let listener = TcpListener::bind("127.0.0.1:0").expect("bind test listener");
        let addr = listener.local_addr().expect("listener address");
        let server = std::thread::spawn(move || {
            let (mut head_stream, _) = listener.accept().expect("accept HEAD probe request");
            let head = std::thread::spawn(move || {
                let mut request = [0; 1024];
                let _ = head_stream.read(&mut request);
                std::thread::sleep(Duration::from_millis(50));
            });

            let (mut get_stream, _) = listener.accept().expect("accept GET probe request");
            let mut request = [0; 1024];
            let _ = get_stream.read(&mut request);
            get_stream
                .write_all(
                    b"HTTP/1.1 405 Method Not Allowed\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
                )
                .expect("write response");
            head.join().expect("HEAD holder should finish");
        });

        let status = mcp_http_probe_url_with_timeout(
            &format!("http://{addr}/mcp"),
            Duration::from_millis(10),
        )
        .await;
        server.join().expect("probe server thread should finish");

        assert_eq!(status, Ok("HTTP 405".to_string()));
    }

    #[tokio::test]
    async fn mcp_check_fails_required_missing_stdio_command() {
        let required_server: McpServerConfig = toml::from_str(
            r#"
                command = "definitely-missing-codex-doctor-mcp"
                required = true
            "#,
        )
        .expect("should deserialize required MCP config");
        let servers = HashMap::from([("required".to_string(), required_server)]);

        let check = mcp_check_from_servers(&servers).await;

        assert_eq!(check.status, CheckStatus::Fail);
        assert_eq!(
            check.summary,
            "MCP configuration has failing required inputs or reachability"
        );
        assert!(check.details.iter().any(|detail| {
            detail.contains(
                "required: stdio command \"definitely-missing-codex-doctor-mcp\" is not resolvable",
            )
        }));
    }

    #[tokio::test]
    async fn mcp_check_skips_host_path_checks_for_remote_stdio() {
        #[cfg(not(windows))]
        let cwd = r"C:\Users\openai\share";
        #[cfg(windows)]
        let cwd = "/home/openai/share";
        let cwd = toml::Value::String(cwd.to_string());
        let remote_server: McpServerConfig = toml::from_str(&format!(
            r#"
                command = "definitely-missing-codex-doctor-mcp"
                environment_id = "remote"
                cwd = {cwd}
                required = true
                env_vars = [{{ name = "REMOTE_ONLY_TOKEN", source = "remote" }}]
            "#,
        ))
        .expect("should deserialize remote MCP config");
        let servers = HashMap::from([("remote".to_string(), remote_server)]);

        let check = mcp_check_from_servers(&servers).await;

        assert_eq!(check.status, CheckStatus::Ok);
        assert_eq!(check.summary, "MCP configuration is locally consistent");
    }

    #[tokio::test]
    async fn mcp_check_validates_remote_stdio_cwd() {
        let missing_cwd: McpServerConfig = toml::from_str(
            r#"
                command = "echo"
                environment_id = "remote"
                required = true
            "#,
        )
        .expect("should deserialize remote MCP config without cwd");
        let relative_cwd: McpServerConfig = toml::from_str(
            r#"
                command = "echo"
                environment_id = "remote"
                cwd = "relative"
                required = true
            "#,
        )
        .expect("should deserialize remote MCP config with relative cwd");
        let servers = HashMap::from([
            ("missing".to_string(), missing_cwd),
            ("relative".to_string(), relative_cwd),
        ]);

        let check = mcp_check_from_servers(&servers).await;

        assert_eq!(check.status, CheckStatus::Fail);
        assert!(
            check
                .details
                .contains(&"missing: remote stdio requires an explicit cwd".to_string())
        );
        assert!(
            check
                .details
                .contains(&"relative: remote stdio cwd is not absolute (relative)".to_string())
        );
    }

    #[cfg(unix)]
    #[test]
    fn read_probe_file_rejects_unreadable_file() {
        use std::os::unix::fs::PermissionsExt;

        let file = tempfile::NamedTempFile::new().expect("create temp file");
        std::fs::write(file.path(), "cert").expect("write temp file");
        let mut permissions = std::fs::metadata(file.path())
            .expect("metadata")
            .permissions();
        permissions.set_mode(0o000);
        std::fs::set_permissions(file.path(), permissions).expect("remove read permissions");

        let result = read_probe_file(file.path());

        let mut permissions = std::fs::metadata(file.path())
            .expect("metadata")
            .permissions();
        permissions.set_mode(0o600);
        std::fs::set_permissions(file.path(), permissions).expect("restore read permissions");
        assert!(result.is_err());
    }

    #[cfg(unix)]
    #[test]
    fn executable_path_exists_rejects_non_executable_file() {
        use std::os::unix::fs::PermissionsExt;

        let file = tempfile::NamedTempFile::new().expect("create temp file");
        std::fs::write(file.path(), "#!/bin/sh\n").expect("write temp file");
        let mut permissions = std::fs::metadata(file.path())
            .expect("metadata")
            .permissions();
        permissions.set_mode(0o600);
        std::fs::set_permissions(file.path(), permissions).expect("set non-executable mode");

        let result = executable_path_exists(file.path());

        assert!(result.is_err());
        let mut permissions = std::fs::metadata(file.path())
            .expect("metadata")
            .permissions();
        permissions.set_mode(0o700);
        std::fs::set_permissions(file.path(), permissions).expect("set executable mode");
        assert_eq!(executable_path_exists(file.path()), Ok(()));
    }

    #[test]
    fn should_enable_color_respects_terminal_inputs() {
        assert!(should_enable_color(
            /*no_color_flag*/ false,
            /*no_color_env*/ false,
            Some("xterm-256color"),
            /*stdout_is_tty*/ true,
            /*stream_supports_color*/ true,
        ));
        assert!(!should_enable_color(
            /*no_color_flag*/ true,
            /*no_color_env*/ false,
            Some("xterm-256color"),
            /*stdout_is_tty*/ true,
            /*stream_supports_color*/ true,
        ));
        assert!(!should_enable_color(
            /*no_color_flag*/ false,
            /*no_color_env*/ true,
            Some("xterm-256color"),
            /*stdout_is_tty*/ true,
            /*stream_supports_color*/ true,
        ));
        assert!(!should_enable_color(
            /*no_color_flag*/ false,
            /*no_color_env*/ false,
            Some("dumb"),
            /*stdout_is_tty*/ true,
            /*stream_supports_color*/ true,
        ));
        assert!(!should_enable_color(
            /*no_color_flag*/ false,
            /*no_color_env*/ false,
            Some("xterm-256color"),
            /*stdout_is_tty*/ false,
            /*stream_supports_color*/ true,
        ));
    }

    fn terminal_inputs() -> TerminalCheckInputs {
        TerminalCheckInputs {
            info: TerminalInfo {
                name: TerminalName::Unknown,
                term_program: None,
                version: None,
                term: Some("xterm-256color".to_string()),
                multiplexer: None,
            },
            env: BTreeMap::from([("TERM".to_string(), "xterm-256color".to_string())]),
            present_env: BTreeSet::from(["TERM".to_string()]),
            no_color_flag: false,
            stdin_is_terminal: true,
            stdout_is_terminal: true,
            stderr_is_terminal: true,
            stream_supports_color: true,
            terminal_size: Ok((120, 40)),
            tmux_details: Vec::new(),
            windows_console_details: Vec::new(),
        }
    }

    fn set_terminal_env(inputs: &mut TerminalCheckInputs, name: &str, value: &str) {
        inputs.present_env.insert(name.to_string());
        if value.is_empty() {
            inputs.env.remove(name);
        } else {
            inputs.env.insert(name.to_string(), value.to_string());
        }
    }

    #[test]
    fn terminal_check_warns_for_dumb_terminal() {
        let mut inputs = terminal_inputs();
        inputs.info.name = TerminalName::Dumb;
        inputs.info.term = Some("dumb".to_string());
        set_terminal_env(&mut inputs, "TERM", "dumb");

        let check = terminal_check_from_inputs(inputs);

        assert_eq!(check.status, CheckStatus::Fail);
        assert_eq!(
            check.summary,
            "TERM=dumb - colors and cursor control are disabled"
        );
        assert_eq!(check.issues.len(), 1);
        assert_eq!(
            check.issues[0].remedy.as_deref(),
            Some("set TERM to a real value, for example xterm-256color")
        );
    }

    #[test]
    fn terminal_check_warns_for_narrow_terminal() {
        let mut inputs = terminal_inputs();
        inputs.terminal_size = Ok((79, 24));

        let check = terminal_check_from_inputs(inputs);

        assert_eq!(check.status, CheckStatus::Warning);
        assert_eq!(
            check.summary,
            "width 79 cols - output may wrap (recommended >=80)"
        );
        assert_eq!(check.issues[0].expected.as_deref(), Some(">= 80 columns"));
        assert_eq!(
            check.issues[0].remedy.as_deref(),
            Some("resize the window to at least 80 columns")
        );
    }

    #[test]
    fn terminal_check_warns_for_declared_narrow_terminal() {
        let mut inputs = terminal_inputs();
        set_terminal_env(&mut inputs, "COLUMNS", "60");

        let check = terminal_check_from_inputs(inputs);

        assert_eq!(check.status, CheckStatus::Warning);
        assert_eq!(
            check.summary,
            "COLUMNS=60 - output may wrap (recommended >=80)"
        );
        assert!(check.details.contains(&"COLUMNS: 60".to_string()));
        assert_eq!(check.issues[0].fields, vec!["COLUMNS".to_string()]);
    }

    #[test]
    fn terminal_check_warns_for_non_utf8_locale() {
        let mut inputs = terminal_inputs();
        set_terminal_env(&mut inputs, "LANG", "C");

        let check = terminal_check_from_inputs(inputs);

        assert_eq!(check.status, CheckStatus::Warning);
        assert_eq!(
            check.summary,
            "locale is not UTF-8 - unicode glyphs may render incorrectly"
        );
        assert!(check.details.contains(&"effective locale: C".to_string()));
        assert_eq!(
            check.issues[0].remedy.as_deref(),
            Some("export LANG=en_US.UTF-8 or another UTF-8 locale")
        );
    }

    #[test]
    fn terminal_check_warns_for_unreadable_terminfo_path() {
        let tempdir = tempfile::tempdir().expect("create tempdir");
        let missing = tempdir.path().join("missing-terminfo");
        let mut inputs = terminal_inputs();
        set_terminal_env(&mut inputs, "TERMINFO", &missing.to_string_lossy());

        let check = terminal_check_from_inputs(inputs);

        assert_eq!(check.status, CheckStatus::Fail);
        assert_eq!(
            check.summary,
            "TERMINFO unreadable - terminal capabilities are unknown"
        );
        assert!(
            check
                .details
                .iter()
                .any(|detail| detail.starts_with("TERMINFO: ") && detail.ends_with(" (missing)"))
        );
        assert_eq!(
            check.issues[0].remedy.as_deref(),
            Some("check that $TERMINFO points to a readable directory")
        );
    }

    #[test]
    fn terminal_check_reports_remote_indicators_as_present_only() {
        let mut inputs = terminal_inputs();
        set_terminal_env(&mut inputs, "SSH_CONNECTION", "10.0.0.1 1 10.0.0.2 22");

        let check = terminal_check_from_inputs(inputs);

        assert!(
            check
                .details
                .contains(&"SSH_CONNECTION: present".to_string())
        );
        assert!(
            !check
                .details
                .iter()
                .any(|detail| detail.contains("10.0.0.1"))
        );
    }

    #[test]
    fn terminal_check_includes_windows_console_details() {
        let mut inputs = terminal_inputs();
        inputs
            .windows_console_details
            .push("stdout console mode: 0x00000004 (VT processing: true)".to_string());

        let check = terminal_check_from_inputs(inputs);

        assert!(
            check
                .details
                .contains(&"stdout console mode: 0x00000004 (VT processing: true)".to_string())
        );
    }

    #[test]
    fn terminal_check_keeps_tmux_probe_failures_non_fatal() {
        let mut inputs = terminal_inputs();
        inputs.info.multiplexer = Some(Multiplexer::Tmux { version: None });

        let check = terminal_check_from_inputs(inputs);

        assert_eq!(check.status, CheckStatus::Ok);
        assert_eq!(check.summary, "terminal metadata was detected");
    }

    #[test]
    fn color_output_summary_reports_disabled_reasons() {
        let mut inputs = terminal_inputs();
        inputs.no_color_flag = true;
        assert_eq!(color_output_summary(&inputs), "disabled (--no-color)");

        inputs = terminal_inputs();
        set_terminal_env(&mut inputs, "NO_COLOR", "");
        assert_eq!(color_output_summary(&inputs), "disabled (NO_COLOR)");

        inputs = terminal_inputs();
        inputs.info.term = Some("dumb".to_string());
        set_terminal_env(&mut inputs, "TERM", "dumb");
        assert_eq!(color_output_summary(&inputs), "disabled (TERM=dumb)");

        inputs = terminal_inputs();
        inputs.stdout_is_terminal = false;
        assert_eq!(
            color_output_summary(&inputs),
            "disabled (stdout is not a terminal)"
        );
    }
}